Makefile by Example: Patterns
Pattern rules allow you to define a generic rule for many files. This sample shows how to compile all .c files to .o files.
Code
CC = gcc
CFLAGS = -I.
# Pattern rule: How to build any .o file from a .c file
# % matches the stem (filename without extension)
%.o: %.c
$(CC) -c -o $@ $< $(CFLAGS)
# We just list the objects, Make figures out how to build them
OBJ = main.o math.o io.o
myprog: $(OBJ)
$(CC) -o $@ $^ $(CFLAGS)Explanation
Writing a separate rule for every single source file is tedious and error-prone. Pattern rules solve this by using the % character as a wildcard. A rule like %.o: %.c tells Make: "Here is how to create any file ending in .o from a corresponding file ending in .c".
When Make needs to build main.o, it looks for a pattern rule that matches. It finds %.o: %.c, matches % to main, and checks if main.c exists. If it does, it applies the rule. This drastically reduces the size of Makefiles for large projects.
Inside the command of a pattern rule, you use automatic variables. $@ stands for the target file name (e.g., main.o), and $< stands for the first dependency (e.g., main.c). This allows the command to be generic and work for any matched file pair.
Code Breakdown
%.o: %.c is the pattern rule header. The stem matched by % must be the same for target and dependency.$< is an automatic variable representing the prerequisite (the .c file).
