When I first started learning Makefiles, I thought of them as a kind of instruction manual — they tell the computer: which file you want, where that file comes from, and which command produces it.
The core idea comes down to a single sentence:
Which file depends on what, and which command produces the target file.
This is the Makefile I wrote while practicing my Process Manager (pshow):
CC = gcc
CFLAGS = -Wall -Wextra -O2
TARGET = pshow
all: $(TARGET)
$(TARGET): main.c
$(CC) $(CFLAGS) -o $(TARGET) main.c
clean:
rm -f $(TARGET)
.PHONY: all clean
CC = gcc
CFLAGS = -Wall -Wextra -O2
TARGET = pshow
Set the compiler and its flags as variables, then reference them later with $(variable_name). The benefit: if you switch compilers or tune the flags later, you only change one line.
$(TARGET): main.c
$(CC) $(CFLAGS) -o $(TARGET) main.c
$(TARGET) (that is, pshow) depends on main.c. If main.c changes, running make again recompiles it automatically.
The character in front of the second line is a Tab, not spaces — that's a Makefile syntax requirement.
.PHONY: all clean
Tells make that all and clean are command names, not actual files. Without this line, if the directory happened to contain a file named clean, make would assume that target is already done and skip it.
| Flag | Description |
|---|---|
-Wall | Show basic warnings |
-Wextra | Show more warnings |
-O2 | Optimization level 2 |
-o | Specify the output filename |
make # build (runs all)
make clean # remove generated files
gcc -Wall -O2 -o output source.c is the basic compile commandmake.PHONY is how you distinguish a "command" from a "file"