Anatomy of a Rule
Every Makefile is built from rules. A rule tells Make how to produce a target from its prerequisites using a recipe.
# Basic rule structure
target: prerequisites
recipe-command # MUST be indented with a TAB, not spaces
# Example: compile main.o from main.c and config.h
main.o: main.c config.h
gcc -c main.c -o main.o
Recipe lines must begin with a literal TAB character. Spaces will cause a *** missing separator error. Configure your editor to insert real tabs in Makefiles.
Core Concepts at a Glance
| Concept | Syntax | Purpose |
|---|---|---|
| Target | name: |
File to create or action to run |
| Prerequisite | target: dep1 dep2 |
Files that must exist / be newer |
| Recipe | command |
Shell commands to build the target |
| Default goal | First target in file | What make builds with no arguments |
| Comment | # text |
Ignored by Make |
| Line continuation | \ at end of line |
Split long lines |
Multiple Targets & Rules
# Multiple targets sharing a recipe
foo.o bar.o: %.o: %.c
$(CC) -c $< -o $@
# Multiple prerequisites on separate lines
app: main.o
app: utils.o
app: config.o
$(CC) $^ -o $@
# Order-only prerequisites (right of |, never trigger rebuild)
output/report.pdf: report.tex | output
pdflatex -output-directory=output report.tex
output:
mkdir -p output
Running Make
Build default target
make
Runs the first target in the Makefile
Build specific target
make clean
Build only the named target
Parallel builds
make -j$(nproc)
Run recipes in parallel using all CPU cores
Override a variable
make CC=clang
Pass variable on the command line
Use alternate file
make -f build.mk
Read a Makefile with a non-default name
Keep going on error
make -k
Continue building other targets after a failure