2. The Anatomy of a Makefile
Build automation that has stood the test of time
make has been around since 1976. Fifty years later, it's still everywhere —
building C programs, orchestrating Docker images, deploying websites, running
test suites. Entire ecosystems (the Linux kernel, GNU, countless open-source
projects) depend on it daily.
The reason is simple: make solves a universal problem. You have files that
depend on other files, and you want to rebuild only what's changed. That idea
maps onto almost any build process.
The Fundamental Unit: A Rule
Everything in a Makefile is built from rules. A rule has three parts:
target: prerequisites
recipe
- Target — the file (or name) you want to build
- Prerequisites — files the target depends on
- Recipe — shell commands that produce the target
A minimal rule
hello: hello.c
gcc -o hello hello.c
hello depends on hello.c. If hello.c is newer than hello (or hello doesn't exist), make runs the recipe.
Critical detail: recipe lines must be indented with a tab character, not spaces. This is the single most common Makefile mistake.
How Make Decides What to Build
When you run make target, the algorithm is:
- Look at the target's prerequisites
- Recursively ensure each prerequisite is up to date
- If any prerequisite is newer than the target (by modification time), run the recipe
- If the target doesn't exist, run the recipe
This is a dependency graph — make walks it top-down, builds bottom-up, and skips anything already current.
A two-step build
program: main.o utils.o
gcc -o program main.o utils.o
main.o: main.c defs.h
gcc -c main.c
utils.o: utils.c defs.h
gcc -c utils.c
Change utils.c and run make — only utils.o and program get rebuilt. main.o is untouched.
Variables
Variables reduce repetition and make Makefiles easier to maintain:
CC = gcc
CFLAGS = -Wall -O2
SRCS = main.c utils.c
OBJS = $(SRCS:.c=.o)
program: $(OBJS)
$(CC) $(CFLAGS) -o $@ $^
Assignment Flavors
| Syntax | Name | Behavior |
|---|---|---|
= |
Recursive | Expanded every time it's used |
:= |
Simple | Expanded once at assignment time |
?= |
Conditional | Set only if not already defined |
+= |
Append | Add to existing value |
The difference between = and := trips up many beginners:
Recursive vs. simple
A = $(B)
B = hello
$(A) expands to "hello" — B is looked up when A is used
C := $(D)
D = world
$(C) expands to "" — D wasn't defined when C was assigned
Automatic Variables
Inside a recipe, make provides shorthand for common values:
| Variable | Meaning |
|---|---|
$@ |
The target |
$< |
The first prerequisite |
$^ |
All prerequisites (deduplicated) |
$? |
Prerequisites newer than the target |
$* |
The stem matched by % in a pattern rule |
These eliminate hardcoded filenames and make rules reusable.
Pattern Rules
Instead of writing a rule for every .o file, use a pattern rule:
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
The % is a wildcard. When make needs utils.o, it matches % to utils,
finds utils.c as the prerequisite, and runs the recipe.
Phony Targets
Not every target is a file. Phony targets are names for actions:
.PHONY: clean test deploy
clean:
rm -f $(OBJS) program
test: program
./run_tests.sh
deploy: program
scp program server:/opt/app/
.PHONY tells make these targets don't correspond to files — so it won't
skip them if a file named clean happens to exist.
Functions
GNU Make has built-in functions for text manipulation:
| Function | Example | Result |
|---|---|---|
$(wildcard *.c) |
Glob files | main.c utils.c |
$(patsubst %.c,%.o,$(SRCS)) |
Pattern substitution | main.o utils.o |
$(filter %.c,$(FILES)) |
Keep matching items | Only .c files |
$(shell cmd) |
Run a shell command | Command output |
$(word 2,$(LIST)) |
N-th word | Second word |
$(sort $(LIST)) |
Sort and deduplicate | Sorted list |
Auto-discover sources
SRCS := $(wildcard src/*.c)
OBJS := $(patsubst src/%.c, build/%.o, $(SRCS))
build/%.o: src/%.c
@mkdir -p build
$(CC) $(CFLAGS) -c $< -o $@
Conditional Logic
Makefiles support conditional blocks:
ifeq ($(DEBUG),1)
CFLAGS += -g -DDEBUG
else
CFLAGS += -O2
endif
Use sparingly — heavy conditionals are a sign you might need a configure script or a more capable build system.
Conventions and Best Practices
Default target
The first rule in the file is the default. Convention is to name it all:
all: program docs
Self-documenting help
.PHONY: help
help: ## Show this help
@grep -E '^[a-zA-Z_-]+:.*##' $(MAKEFILE_LIST) | \
awk 'BEGIN {FS = ":.*## "}; {printf " %-15s %s\n", $$1, $$2}'
Silence vs. verbosity
Prefix a recipe line with @ to suppress echoing:
test:
@echo "Running tests..."
@./run_tests.sh
Error handling
Prefix with - to ignore errors:
clean:
-rm -f $(OBJS)
A Real-World Example
Here's a complete Makefile for a small C project:
CC := gcc
CFLAGS := -Wall -Wextra -std=c11
LDFLAGS :=
SRCS := $(wildcard src/*.c)
OBJS := $(patsubst src/%.c, build/%.o, $(SRCS))
TARGET := bin/app
.PHONY: all clean test
all: $(TARGET)
$(TARGET): $(OBJS)
@mkdir -p bin
$(CC) $(LDFLAGS) -o $@ $^
build/%.o: src/%.c
@mkdir -p build
$(CC) $(CFLAGS) -c $< -o $@
test: $(TARGET)
@./tests/run.sh
clean:
rm -rf build bin
This is everything most small-to-medium projects need: auto-discovered sources, a build directory, incremental compilation, and clean/test targets.
When Make Isn't Enough
make starts to strain when:
- You need cross-platform builds (Make is Unix-centric)
- The dependency graph is dynamic (generated at build time)
- You want hermetic builds (guaranteed reproducibility)
In those cases, tools like CMake, Meson, Bazel, or Nix pick up where Make leaves off. But for orchestrating tasks with file dependencies, Make remains the simplest tool that could possibly work.
Summary
- A Makefile is built from rules: target, prerequisites, recipe
makeonly rebuilds what's out of date, by comparing timestamps- Variables (
CC,CFLAGS) reduce repetition;:=vs=matters - Automatic variables (
$@,$<,$^) make rules generic - Pattern rules (
%.o: %.c) handle entire classes of files - Phony targets name actions, not files
- For file-dependency-driven builds and task automation,
makeis still the simplest, most universal tool available