Makefile basics
- C course
- Intermediate
- Lesson 62/116
- 5 min
Learn build automation with Makefile.
What is a Makefile?
A Makefile is the build recipe file that make reads. In multi-file C projects, compiling each file by hand is tiring; Makefile automates it. Each rule has a target, prerequisites and a recipe line.
Format: app: main.c utils.c (target: prerequisites), the next line starts with a TAB and holds the recipe gcc -o app main.c utils.c. Running make app builds the target. Make detects changed files; it only rebuilds what's needed. That's why it saves time in large projects.
Variables and clean
A Makefile defines variables: CC = gcc, CFLAGS = -Wall -g. In recipes use $(CC) $(CFLAGS) -o app main.c. This lets you change the compiler and flags in one place.
A common target is clean: under clean: write rm -f app *.o. Running make clean removes build products. For phony targets (clean, all) the .PHONY: clean declaration is recommended; it prevents clashes with file names. This pattern is standard across C projects.
Practice Write a Makefile
Write a Makefile: the CC = gcc variable, the app: main.c target, a TAB-led recipe $(CC) -o app main.c, the clean: target and a TAB-led rm -f app recipe. Output should be gcc -o app main.c.
Starter code
# Makefile: write app and clean targets
# CC = gcc
# app: main.c
# Compile app with $(CC)
# clean:
# Remove appSample solution
CC = gcc
app: main.c
$(CC) -o app main.c
clean:
rm -f appExpected output
gcc -o app main.c
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How must a Makefile recipe line start?
- With two spaces
- With a space
- With a TAB Correct answer
- With a comment
Explanation: A Makefile recipe line must start with a TAB.
2 Complete the Makefile target
app: main.c utils.c
gcc -o ____ main.c utils.c
app: main.c utils.c
gcc -o app main.c utils.c
Explanation: gcc -o app main.c utils.c names the output app.
3 Match Makefile parts
| Term | Meaning |
|---|---|
app: main.c |
Target and prerequisite |
gcc ... |
Recipe line |
CC = gcc |
Variable definition |
clean: |
Phony target |