本文根据 Devhints / Makefile 翻译。代码示例及版本范围沿用原文。
变量赋值
foo = "bar"
bar = $(foo) foo # dynamic (renewing) assignment
foo := "boo" # one time assignment, $(bar) now is "boo foo"
foo ?= /usr/local # safe assignment, $(foo) and $(bar) still the same
bar += world # append, "boo foo world"
foo != echo fooo # exec shell command and assign to foo
# $(bar) now is "fooo foo world"
= 表达式仅在被使用时才会求值。
魔术变量
out.o: src.c src.h
$@ # "out.o" (target)
$< # "src.c" (first prerequisite)
$^ # "src.c src.h" (all prerequisites)
%.o: %.c
$* # the 'stem' with which an implicit rule matches ("foo" in "foo.c")
also:
$+ # prerequisites (all, with duplication)
$? # prerequisites (new ones)
$| # prerequisites (order-only?)
$(@D) # target directory
命令前缀
| 前缀 | 说明 |
|---|---|
- | 忽略错误 |
@ | 不打印命令 |
+ | 即使 Make 处于“不执行”模式,也进行运行 |
build:
@echo "compiling"
-gcc $< $@
-include .depend
Find 个文件
js_files := $(wildcard test/*.js)
all_files := $(shell find images -name "*")
替换
file = $(SOURCE:.cpp=.o) # foo.cpp => foo.o
outputs = $(files:src/%.coffee=lib/%.js)
outputs = $(patsubst %.c, %.o, $(wildcard *.c))
assets = $(patsubst images/%, assets/%, $(wildcard images/*))
更多函数
$(strip $(string_var))
$(filter %.less, $(files))
$(filter-out %.less, $(files))
构建文件
%.o: %.c
ffmpeg -i $< > $@ # Input and output
foo $^
包含 (Includes)
-include foo.make
选项
make
-e, --environment-overrides
-B, --always-make
-s, --silent
-j, --jobs=N # parallel processing
条件判断
foo: $(objects)
ifeq ($(CC),gcc)
$(CC) -o foo $(objects) $(libs_for_gcc)
else
$(CC) -o foo $(objects) $(normal_libs)
endif
递归
deploy:
$(MAKE) deploy2