makefile:
.PHONY:clean
CC = gcc
RM = rm
TARGET = simple
SRCS= $(wildcard *.c)
OBJS = $(patsubst %.c,%.o,$(SRCS))
$(TARGET):$(OBJS)
$(CC) -o $@ $^
%.o:%.c
$(CC) -o $@ -c $^
clean:
$(RM) $(TARGET) $(OBJS)
test:$(TARGET)
@./$(TARGET)
1.⽬标放在‘:’的前⾯,其名字可以是由字⺟和下划线‘_’组成 .‘:’后⾯是告诉 make⽬标依赖 的项
2.命令语法是tab键,注意是linux下的tab,windows下敲击会无法识别
$(CC) -o $@ $^就是⽣成⽬标的命令,这些命令可以是任何你可以在你的环境中运⾏的命令以及 make 所定义的函数等等。 $(TARGET)的定义,其实是定义了如何⽣成 ,也称之为规则
@可以取消命令运行时显示
假目标,避免所定义的目标和的已经存在文件重名的情况,比如存在一个交clean文件
⼀个变量的定义就是⼀个名字(变量名)后⾯跟上⼀个等号,然后在等号的后⾯放这个变量所期望的值。对于变量的引⽤,则需要采⽤$(变量名)或者${变量名}这种模式
比如本例:
CC = gcc
RM = rm
TARGET = simple
SRCS= $(wildcard *.c)
OBJS = $(patsubst %.c,%.o,$(SRCS))
举个例子
.PHONY:all
all:first second third
@echo "\$$@ = $@"
@echo "\$$^ = $^"
@echo "\$$< = $<"
first second third:
运行结果
$@ = all
$^ = first second third
$< = first
.PHONY:all
foo=$(bar)
bar=$(sfa)
sfa=hello
all:
@echo $(foo)
ll@localhost lesson4]$ make
hello
⽤“:=”操作符来定义,make 只对其进⾏⼀次扫描和替换
[ll@localhost lesson5]$ cat makefile
.PHONY:all
x = foo
y = $(x) b
x = later
xx := foo
yy := $(xx) b
xx := later
all:
@echo "$(x) , $(y) , $(xx) , $(yy)"
[ll@localhost lesson5]$ make
later , later b , later , foo b
x和y都按最新的值设置变量,xx和yy只是做简单替换,即只进行一次扫描和替换
条件赋值符“?=”,条件赋值的意思是当变量以前没有定义时,就定义它并且将左边的值赋值给它,如果已经定义了那么就不再改变其值
[linsz@localhost lesson6]$ cat makefile
.PHONY:all
foo = x
foo ?= y
bar ?= y
all:
@echo "$(foo) $(bar)"
[linsz@localhost lesson6]$ make
x y
可以看到foo值没有改变
[linsz@localhost lesson7]$ cat makefile
.PHONY:all
objects = main.o foo.o
objects += test.o
all:
@echo $(objects)
[linsz@localhost lesson7]$ make
main.o foo.o test.o
override 变量
定义的某个变量不被覆盖掉
[linsz@localhost lesson8]$ cat makefile
.PHONY:all
override foo = x
all:
@echo $(foo)
[linsz@localhost lesson8]$ make foo=12
x
[linsz@localhost lesson8]$
[linsz@localhost lesson8]$
[linsz@localhost lesson8]$ vi makefile
[linsz@localhost lesson8]$ make foo=12
12
[linsz@localhost lesson8]$ cat makefile
.PHONY:all
foo = x
all:
@echo $(foo)
[linsz@localhost lesson8]$
⽤“%”表示通配符
.PHONY:clean
CC = gcc
RM = rm
TARGET = simple
SRCS= $(wildcard *.c)
OBJS = $(patsubst %.c,%.o,$(SRCS))
$(TARGET):$(OBJS)
$(CC) -o $@ $^
%.o:%.c
$(CC) -o $@ -c $^
clean:
$(RM) $(TARGET) $(OBJS)
test:$(TARGET)
@./$(TARGET)
按% 进行匹配替换
SRCS = $(wildcard *.c)
OBJS = $(patsubst %.c,%.o,$(SRCS))