别的不多说,以下笔记都是自己从书上摘录下来的,以供后续复习使用,也给初学者提供一些基本的语法解释。
make规则:
目标【target】:依赖【prerequisite】
命令【cmd】
定义变量的赋值方法:
+= :添加赋值,以补充的方式
?= :若是之前没有赋值,则赋值
:= :覆盖赋值,将原来的值替换掉
= :直接赋值,不用通过=来修改原来定义的值,必须使用 := 或者 +=
所有的赋值都会去取文件中的最后一次定义的值,除了?=在之前有定义的时候。感觉最好不要在使用该值后在使用处的后面再修改原定义,最好在开始就把所有的值赋好。
one = one
two := two
three ?= three
four = four
one = $(one) one1 //此处报错,one在之前已经定义,必须使用 := 对 one 进行重新赋值
two := $(two) two1
three ?= three1
four += four1
all:
@echo $(one) 将=改为:=后, one one1 将下方注释放开, one2
@echo $(two) one的修改版, two two1 将下方注释放开, two2
@echo $(three) three 将下方注释放开, three2
@echo $(four) four four1 将下方注释放开, four four1 four2
#one = one2
#two = two2
#three = three2
#four = four2
在makefile使用shell命令调用shell中的$时为了和makefile中的$区分开,使用$$表示使用shell中的$符号
例如:
在makefile中:
cp:
cp `ls | grep .*[^o$] | tr '\n' ' '` ../src/ 错误写法
cp `ls | grep .*[^o$$] | tr '\n' ' '` ../src/ 修改后的写法,这样就可以成功cp文件了,输入make cp后
命令解析,去掉以.o结尾的文件将\n换成空格拷贝到../src目录中
makefile基本函数:
一、字符串分析函数:
1.替换:
$(subst, ee, EE, feet on street) :输出 fEEt on strEEt 参数之间不要加空格
$(patsubst %.c,%.o,main.c src.c test.c) :输出 main.o src.o test.o
2.去除多余空格:
$(strip a b c ) : 输出 a b c
3.字符串查找
$(findstring hello, da jia hello world) 输出hello
4.内容过滤
$(filter %.c %.o, a.c b.c s.o q.s d.h) 输出 a.c b.c s.o 选出匹配的内容
$(filter-out %.c %.o, a.c b.c s.o q.s d.h) 输出 q.s d.h
5.文件名排序
$(sort s.c b.c i.o p.s a.h)
二、文件名函数
大约有dir,notdir,basename,suffix,addsuffix,addpresuffix
src下有 a.c b.c s.c b.o a.o h.s s.h
$(wildcard *.c *.h) 输出 a.c b.c s.c s.h
三、其他命令
VPATH src: ./src
vpath %.h ./include
$(shell ls *.c) a.c b.c s.c
例子,该目录下只有两个文件chunk.c Makefile
one = one
two := two
three = three
four = four
one := $(one) one1
two := $(two) two1
three ?= three1
four += four1
test = $(subst ee,EE, feet on street)
test1 = $(patsubst %.c, %.o, main.c test.c)
test2 = $(strip a b c )
test3 = $(findstring hello, dajia hello world)
test4 = $(filter %.c %o, a.c b.c s.o q.s d.h)
test5 = $(filter-out %.c %o, a.c b.c s.o q.s d.h)
test6 = $(sort s.c b.c i.o p.s a.h)
test7 = $(wildcard *.c)
test8 = $(shell ls *.c)
all:
@echo $(one)
@echo $(two)
@echo $(three)
@echo $(four)
@echo $(test)
@echo $(test1)
@echo $(test2)
@echo $(test3)
@echo $(test4)
@echo $(test5)
@echo $(test6)
@echo $(test7)
@echo $(test8)
结果如下:
one one1
two two1
three
four four1
fEEt on strEEt
main.o test.o
a b c
hello
a.c b.c s.o
q.s d.h
a.h b.c i.o p.s s.c
chunk.c
chunk.c
Makefile基本语法:
ifeq (“abc”, “dcb”)
@echo “hello”
else
@echo “world”
endif
$(if test,true,flase) 格式:$(if condition, then, else)
all:%.o
gcc $^ -o $@
# $@:目标文件名,$^:所依赖的所有文件名,$<:第一个依赖的文件名
通配符:make中是%.c %.o ,而shell中是*.c *.o
多级make时使用 $(MAKE) -C
初步学习这些基本的也就够了吧,还有那种自动生成的Makefile,cmake等是大型工程所用到的不需要自己手动编写makefile