Skip to content
Latchkey

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 files

Variable assignment

FormMeans
VAR = xRecursive (expanded at use)
VAR := xSimple (expanded once)
VAR ?= xSet only if undefined
VAR += xAppend
$(VAR)Reference a variable

Automatic variables

VarMeans
$@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

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →