English | 中文版
[TOC]
make is an automated build tool that builds projects by reading the "makefile" file.
- GNU make
- BSD make
- Microsoft nmake
MACRO = file1 file2
target (file to generate) : prerequisites (dependent files)
command1 # comment
commandn
@# echo
.PHONY: target-
#indicates a comment -
target...prerequisitestargetUsed to tell make when and how to regenerate the target or execute the commands under the target; target is usually the name of the file we want to generate, prerequisites are the list of files needed to generate the target.
-
.PHONYphony targetPrevents conflicts between command-only targets defined in the Makefile and actual files in the working directory with the same name.
-
Macro
A "macro" is a way to substitute one string for another; in makefile, use
=to define a macro, use$(MACRO)to use it; you can also use+=to append to a macro; by convention, macro names are uppercase. -
Echo
By default, make prints each command before executing it, called echoing.
Use
@to turn off echoing. -
Wildcards
Wildcards are used to specify a set of matching filenames. Makefile wildcards are the same as Bash:
*,?,%,... -
Variables
-
Implicit Variables
make provides a series of built-in variables:
$(CC)points to the current compiler$(MAKE)points to the current make tool- ...
-
Automatic Variables
make also provides some automatic variables whose values depend on the current rule, mainly:
-
$@refers to the current targetExample:
a.txt b.txt touch $@
Equivalent to
a.txt touch a.txt b.txt touch b.txt
-
$<refers to the first prerequisiteExample:
a.txt: b.txt c.txt cp $< $@
Equivalent to
a.txt: b.txt c.txt cp b.txt a.txt -
$?refers to all prerequisites that are newer than the target, separated by spaces. -
$^refers to all prerequisites, separated by spaces. -
$ -
$(@D)and$(@F)refer to the directory and filename of$@respectively. -
$(<D)and$(<F)refer to the directory and filename of$<respectively.
-
-
-
Functions
Makefile supports the following functions:
-
shellexecutes shell commandsExample:
srcfiles := $(shell echo src/{00..99}.txt)
-
wildcardreplaces bash wildcards in makefileExample:
srcfiles := $(wildcard src/*.txt)
-
substfor text replacementUsage:
$(subst from,to,text)Example:
# Replace "feet on the street" with "fEEt on the strEEt" $(subst ee,EE,feet on the street) -
patsubstfor pattern matching replacementExample:
# Replace filenames "x.c.c bar.c" with "x.c.o bar.o" $(patsubst %.c,%.o,x.c.c bar.c)
-
Example:
OBJECTS = main.o text.o
editor: $(OBJECTS)
gcc -o editor $(OBJECTS)
main.o: main.c def.h
gcc -c main.c
text.o: text.c com.h
gcc -c text.c
%.o: other.c
clean:
rm editor main.o text.o *.o
install:editor
mv editor $(INSTALL_PATH)
@# make end
.PHONY: editor clean