Makefiles help programmers automate compiling, testing, cleaning, and packaging software projects. This cheat sheet covers the structure and rules used by make, so students can build programs reliably without typing long commands each time. It is especially useful for C, C++, Java, and mixed projects where files depend on each other.
Key Facts
- A basic rule has the form target: prerequisites followed by an indented recipe command on the next line.
- The command lines in a Makefile recipe must begin with a tab character, not ordinary spaces.
- make target runs the recipe for target only if the target file is missing or older than one of its prerequisites.
- The variable assignment CC = gcc stores a compiler command, and it can be used later as $(CC).
- Automatic variable < means the first prerequisite, and $^ means all prerequisites.
- A pattern rule such as %.o: %.c can describe how to build any .o file from a matching .c file.
- .PHONY: clean tells make that clean is a command name, not a real file that should be checked for timestamps.
- The command make -j4 allows up to 4 jobs to run in parallel when dependency order permits it.
Vocabulary
- Makefile
- A Makefile is a text file that tells the make program how to build, rebuild, test, or clean a project.
- Target
- A target is the file or task name that make tries to create or update, such as app, main.o, or clean.
- Prerequisite
- A prerequisite is a file or target that must exist or be up to date before another target can be built.
- Recipe
- A recipe is the list of shell commands that make runs to build a target.
- Variable
- A variable stores reusable text such as a compiler name, flags, file list, or output directory.
- Phony Target
- A phony target is a task name that does not represent a real file, such as clean, test, or install.
Common Mistakes to Avoid
- Using spaces before recipe commands is wrong because make usually requires a tab character at the start of each command line.
- Forgetting prerequisites is wrong because make may skip rebuilding a file even when a source file or header has changed.
- Naming a real file clean is a problem if clean is not marked .PHONY, because make may think the target is already up to date.
- Putting shell variables and make variables in the wrong form causes errors, because $PATH passes a shell variable.
- Assuming make always rebuilds everything is wrong because make uses timestamps to rebuild only missing or outdated targets.
Practice Questions
- 1 A file program depends on main.o and utils.o. Write the Makefile rule header for building program from those two object files.
- 2 If main.o was last modified at 10:00 and main.c was last modified at 10:15, will make rebuild main.o? Explain using timestamps.
- 3 In the rule %.o: %.c, what do < represent when building math.o from math.c?
- 4 Why should a build system describe dependencies instead of only listing commands in the order a programmer usually runs them?