Makefile Cheat Sheet: Targets, Variables & Automatic Vars
Makefile targets, variables, and automatic variables in one reference.
Targets, prerequisites, and variable assignment for GNU Make.
Anatomy
Makefile
build: deps # target: prerequisites
go build ./... # recipe (TAB-indented)
.PHONY: build test # not real filesVariable assignment
| Form | Means |
|---|---|
| VAR = x | Recursive (expanded at use) |
| VAR := x | Simple (expanded once) |
| VAR ?= x | Set only if undefined |
| VAR += x | Append |
| $(VAR) | Reference a variable |
Automatic variables
| Var | Means |
|---|---|
| $@ | Target name |
| $< | First prerequisite |
| $^ | All prerequisites |
| $? | Prereqs newer than target |
| $* | Stem of a pattern match |
Patterns
pattern rule
%.o: %.c
$(CC) -c $< -o $@
.PHONY: clean
clean:
rm -rf build/Key takeaways
- Recipes must be TAB-indented, not spaces.
- Mark non-file targets .PHONY so they always run.
- := expands once; = re-expands on every use.
Related guides
Bash Scripting Cheat Sheet: Variables, Tests & LoopsA bash scripting cheat sheet - variables, parameter expansion, test conditions, loops, functions, and strict-…
GitHub Actions Cheat Sheet: Syntax, Contexts & CommandsA GitHub Actions cheat sheet - triggers, jobs, steps, contexts, expressions, caching, matrix, and the workflo…
Exit Codes Cheat Sheet: Shell Status Codes ExplainedAn exit codes cheat sheet - what 0, 1, 2, 126, 127, 130, and signal-derived codes mean, and how to read $? in…