makefile 文件名
默认情况下,make 命令会尝试寻找下面的文件名作为 makefile 输入:
- ‘Makefile’ 推荐使用
- ‘makefile’
- ‘GNUmakefile’ 这个文件名只对GNU make 起作用,不推荐
也可以使用-f file_name
指定makefile。
makefile 基本格式
targets : prerequisites
command
command
...
- targets 是由空格分割的文件名,通常只有一个。
- prerequisites 也是由空格分割的文件名。这些文件必须在command执行前存在。
- command 是一些列执行命令,通常用来生成targets。每行必须由tab开头。
make 命令
默认情况下,make 执行第一个target (不以 ‘.’ 开头的target),这个target叫做 default goal.
-C dir, --directory=dir
指定文件夹
-f file, --file=file
指定文件作为makefile
V=1
指定变量V的值
= := += ?= 区别
符号 | 名称 |
---|---|
= | recursive expansion variable |
:= | simply expanded variable |
?= | conditional variable |
+= | add more text to the value of a variable already defined |
- =
迭代展开变量。含有变量引用,在最后执行的时候才进行变量的迭代展开。因此可能回造成无穷迭代。foo = $(bar) bar = $(ugh) ugh = Huh all:;echo $(foo) # 结果为 Huh
- :=
简单展开变量。不含有变量的引用,在变量定义的时候就进行展开。x := foo y := $(x) bar x := later # is equivalent to y := foo bar # 如果前面是迭代展开的话,这里则为 later bar x := later
- ?=
如果变量未定义,则为变量赋值 - +=
为已定义变量添加更多text。如果变量之前未定义,则想当于=
(recursive expansion variable)variable := value variable += more # 相当于 variable := value variable := $(variable) more # 注意空格
变量
make 变量使用一个$
,shell 变量使用两个 $$
SHELL=/bin/bash # 指定shell
LIST = one two three
all:
for i in $(LIST); do \
echo $$i; \
done
自动变量
自动变量 | 意义 |
---|---|
$@ | target的文件名 |
$< | 第一个prerequisite的文件名 |
$^ | 所有prerequisite的文件名,去除重复项 |
$+ | 所有prerequisite的文件名,不去重,且保留顺序 |
命令回显和关闭
默认情况下,make在执行command 之前都会显示当前行。
在command前面添加@
可以关闭当前行的显示,但是不会影响执行结果的显示。
all:
@echo "This line not printed"
echo "But this line will"
通配符
通配符
make 里面的通配符有三种:‘*’, ‘?’ and ‘[...]’
反斜杠 \
可以关闭通配符。
通配符函数
在进行变量定义的时候,通配符不会展开,这时候需要采用通配符函数
objects = *.o # objects的值实际上是字符串 ‘*.o’.
objects := $(wildcard *.o) # 这种情况下才通配符才能展开
include 其他文件
include filenames... # 导入其他文件
# 下面两种写法,在文件不存在的时候,不报错
-include filenames...
sininclude filenames...