Lesson 28 of 50 · c
Makefiles – Building Large Projects
Duration: 12 mins
A Makefile automates compilation, tracks dependencies, and avoids rebuilding unchanged files.
Key concepts:
- Targets – file to be generated (
myprog). - Prerequisites – files the target depends on (
main.o utils.o). - Recipes – commands to run (
$(CC) -o $@ $^). - Variables –
CC,CFLAGS,LDFLAGS. - Phony targets –
clean,all.
Example (expanded):
CC = gcc
CFLAGS = -Wall -Wextra -O2 -Iinclude
LDFLAGS =
SRCS = $(wildcard src/*.c)
OBJS = $(SRCS:.c=.o)
.PHONY: all clean run
all: myprog
myprog: $(OBJS)
$(CC) $(LDFLAGS) -o $@ $^
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
run: myprog
./myprog
clean:
rm -f $(OBJS) myprog
Running make rebuilds only files whose source changed.
📈 Benefits
- Incremental builds – fast iteration.
- Centralised configuration (flags, includes).
- Works across platforms (GNU Make, BSD make).