OSDN Git Service

Regular updates
[twpd/master.git] / makefile.md
1 ---
2 title: Makefile
3 prism_languages: [makefile]
4 layout: 2017/sheet
5 category: CLI
6 ---
7
8 ## Var assignment
9
10 ```makefile
11 uglify = $(uglify)        # lazy assignment
12 compressor := $(uglify)   # immediate assignment
13 prefix ?= /usr/local      # safe assignment
14 hello += world            # append
15 ```
16
17 `=` expressions are only evaluated when they're being used.
18
19 ## Magic variables
20
21 ```makefile
22 out.o: src.c src.h
23   $@   # "out.o" (target)
24   $<   # "src.c" (first prerequisite)
25   $^   # "src.c src.h" (all prerequisites)
26
27 %.o: %.c
28   $*   # the 'stem' with which an implicit rule matches ("foo" in "foo.c")
29
30 also:
31   $+   # prerequisites (all, with duplication)
32   $?   # prerequisites (new ones)
33   $|   # prerequisites (order-only?)
34
35   $(@D) # target directory
36 ```
37
38 ## Command prefixes
39
40 | Prefix | Description                                 |
41 | ------ | ------------------------------------------- |
42 | `-`    | Ignore errors                               |
43 | `@`    | Don't print command                         |
44 | `+`    | Run even if Make is in 'don't execute' mode |
45
46 ```makefile
47 build:
48     @echo "compiling"
49     -gcc $< $@
50
51 -include .depend
52 ```
53
54 ## Find files
55
56 ```makefile
57 js_files  := $(wildcard test/*.js)
58 all_files := $(shell find images -name "*")
59 ```
60
61 ## Substitutions
62
63 ```makefile
64 file     = $(SOURCE:.cpp=.o)   # foo.cpp => foo.o
65 outputs  = $(files:src/%.coffee=lib/%.js)
66
67 outputs  = $(patsubst %.c, %.o, $(wildcard *.c))
68 assets   = $(patsubst images/%, assets/%, $(wildcard images/*))
69 ```
70
71 ## More functions
72
73 ```makefile
74 $(strip $(string_var))
75
76 $(filter %.less, $(files))
77 $(filter-out %.less, $(files))
78 ```
79
80 ## Building files
81
82 ```makefile
83 %.o: %.c
84   ffmpeg -i $< > $@   # Input and output
85   foo $^
86 ```
87
88 ## Includes
89
90 ```makefile
91 -include foo.make
92 ```
93
94 ## Options
95
96 ```sh
97 make
98   -e, --environment-overrides
99   -B, --always-make
100   -s, --silent
101
102   -j, --jobs=N   # parallel processing
103 ```
104
105 ## Conditionals
106
107 ```makefile
108 foo: $(objects)
109 ifeq ($(CC),gcc)
110         $(CC) -o foo $(objects) $(libs_for_gcc)
111 else
112         $(CC) -o foo $(objects) $(normal_libs)
113 endif
114 ```
115
116 ## Recursive
117
118 ```makefile
119 deploy:
120   $(MAKE) deploy2
121 ```
122
123 ## Further reading
124
125 - [isaacs's Makefile](https://gist.github.com/isaacs/62a2d1825d04437c6f08)
126 - [Your Makefiles are wrong](https://tech.davis-hansson.com/p/make/)
127 - [Manual](https://www.gnu.org/software/make/manual/html_node/index.html)