Introduction
A Makefile holds the rules for the make program, the Unix build tool
first written in 1976. Each rule says how to make a file, such as a program or an
object file, from the files it depends on. make compares the files’
modification times and runs only the commands whose results are out of date.
The main file usually has no extension at all: make looks for a file
named GNUmakefile, makefile or Makefile in the
current folder. Makefiles that are included by others, or kept in a library of shared
rules, are often named .mk. Tools such as
CMake and Autotools write Makefiles for a project
rather than having people write them by hand.
Structure
A Makefile is plain text. A rule is a line naming a target, a colon and its
prerequisites, followed by the recipe: commands on lines that must start with a tab
character, not spaces. Variables are set with = or := and used
as $(NAME). Automatic variables stand for parts of the rule:
$@ is the target, $< the first prerequisite and
$^ all of them. Pattern rules with % describe how to make any
file of one kind from another, and .PHONY marks targets such as
clean that are not files.
CC = cc
CFLAGS = -O2 -Wall
app: main.o util.o
$(CC) -o $@ $^
%.o: %.c
$(CC) $(CFLAGS) -c $<
.PHONY: clean
clean:
rm -f app *.o
GNU make, BSD make and Microsoft’s NMAKE share this core but differ in their extensions, such as conditionals and functions, so a Makefile is often written for one of them.