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