Makefile Variables & Pattern Rules
Intermediatev1.0.0
Master Makefile variables, pattern rules, and functions — environment overrides, conditional logic, automatic variables, and DRY patterns for maintainable build files.
Content
Overview
Makefile variables and pattern rules eliminate duplication and make build files maintainable. Variables define reusable values, pattern rules handle repetitive targets, and functions transform strings — all essential for Makefiles beyond trivial use.
Why This Matters
- -DRY builds — define once, use everywhere
- -Environment overrides —
make deploy ENV=staging - -Pattern rules — one rule handles many files
- -Maintainability — change a version/path in one place
Variable Types
Simple vs Recursive
Using Variables
Pattern Rules
Automatic Variables
| Variable | Meaning | Example |
|---|---|---|
| `$@` | Target name | bin/myapp |
| `$<` | First prerequisite | cmd/myapp/main.go |
| `$^` | All prerequisites | file1.go file2.go |
| `$*` | Pattern stem | myapp (from bin/%) |
| `$(@D)` | Directory of target | bin/ |
| `$(<D)` | Directory of first prereq | cmd/myapp/ |
Functions
Best Practices
- -Use := for most variables — predictable evaluation
- -Use ?= for overridable defaults — CLI-friendly
- -Use pattern rules for repetitive file transformations
- -Group variables at the top of the Makefile
- -Use $(shell ...) sparingly — each call spawns a subshell
Common Mistakes
- -Using = when := is intended (unexpected lazy evaluation)
- -Not quoting shell commands inside $(shell ...)
- -Forgetting that each recipe line runs in a separate shell
- -Using pattern rules for targets that aren't file-based
FAQ
Discussion
Loading comments...