Makefile 要点备忘

本文包含常用的 Makefile 语法,在这里总结一下,方便以后查阅。

变量与赋值

uglify = $(uglify)        # lazy assignment
compressor := $(uglify)   # immediate assignment
prefix ?= /usr/local      # safe assignment

特殊变量

out.o: src.c src.h
  [email protected]   # "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

命令前缀

- Ignore errors
@ Don’t print command
+ Run even if Make is in ‘don’t execute’ mode

build:
    @echo "compiling"
    -gcc $< [email protected]

-include .depend

文件相关操作

列举所有文件

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 $< > [email protected]   # Input and output
  foo $^

引入其他 makefile 文件

-include foo.make

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

Comments

Comments powered by Disqus