Skip to content
systemcoding.dev
Toolchains

Compile Object Files With Pattern Rules in Make

Replace one rule per source file with a single %.o: %.c pattern rule, add automatic header dependencies with -MMD, and know when make's built-in rule is enough.

6 min read
Summarize in AI
Flat illustration of source code passing through a compiler and linker into a binary, with the GNU, LLVM and C logos.

A Makefile with a separate rule for every .c file works until the project has thirty of them. A pattern rule says "any .o file can be built from the .c file with the same name" in one place, and make applies it to every object it needs. This post writes that rule, explains how the % matching works, adds header dependency tracking so edits to headers rebuild the right files, and compares the hand-written rule with the one make already knows. The examples use GNU Make 4.4.1 and GCC 14.2, and the behaviour is described in the manual's chapter on pattern rules.

The pattern rule

A pattern rule looks like a normal rule, but the target contains a %, which matches any non-empty string called the stem. The same stem is substituted wherever % appears in the prerequisites.

Makefilemakefile
CC     := gcc
CFLAGS := -Wall -Wextra -O2

SRCS := main.c util.c parse.c
OBJS := $(SRCS:.c=.o)

app: $(OBJS)
	$(CC) -o $@ $^

%.o: %.c
	$(CC) $(CFLAGS) -c $< -o $@

clean:
	rm -f app $(OBJS)

.PHONY: clean

The rule %.o: %.c reads: to make a file ending in .o, with some stem, you need the file with the same stem ending in .c. When make needs parse.o, the stem is parse, the prerequisite is parse.c, and the recipe runs with $< set to parse.c and $@ to parse.o. One rule, any number of files.

$(SRCS:.c=.o) is a substitution reference: it takes the value of SRCS and replaces a trailing .c with .o in each word, which gives main.o util.o parse.o. Add a new source to SRCS and nothing else needs to change.

Shell
make
Text
gcc -Wall -Wextra -O2 -c main.c -o main.o
gcc -Wall -Wextra -O2 -c util.c -o util.o
gcc -Wall -Wextra -O2 -c parse.c -o parse.o
gcc -o app main.o util.o parse.o

Make already has this rule

You may not need to write it. GNU Make has built in implicit rules, and one of them is exactly this compile step.

Shell
make -p -f /dev/null | grep -A3 '^%.o: %.c'
Text
%.o: %.c
	$(COMPILE.c) $(OUTPUT_OPTION) $<

COMPILE.c expands to $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c, so if you set CC, CFLAGS and CPPFLAGS and delete your own %.o: %.c, the built in rule compiles your files the same way. The reason to write your own is control: to add a flag, to print a shorter message, or to put objects in a different directory. If the built in rule is enough, leave it out and the Makefile is shorter. Keep in mind that built in rules apply silently, which can surprise a reader who does not know them, and make -r turns all of them off.

Header dependencies

The pattern rule has a gap. Its only prerequisite is the .c file, so editing util.h does not rebuild anything that includes it. The program links against stale objects and misbehaves in ways that disappear after make clean. Listing headers by hand does not scale, but GCC can write the dependency list for you.

The options -MMD -MP make the compiler produce a .d file next to each object, containing a rule that lists the headers the source included, not counting system headers.

Makefilemakefile
CC       := gcc
CFLAGS   := -Wall -Wextra -O2
DEPFLAGS := -MMD -MP

SRCS := main.c util.c parse.c
OBJS := $(SRCS:.c=.o)
DEPS := $(OBJS:.o=.d)

app: $(OBJS)
	$(CC) -o $@ $^

%.o: %.c
	$(CC) $(CFLAGS) $(DEPFLAGS) -c $< -o $@

-include $(DEPS)

clean:
	rm -f app $(OBJS) $(DEPS)

.PHONY: clean

After a build, main.d contains something like this.

Text
main.o: main.c util.h parse.h
util.h:
parse.h:

The first line is the real dependency: main.o depends on main.c, util.h and parse.h. The empty rules for each header come from -MP, which prevents an error when you delete a header, because make would otherwise complain that it has no rule to build a file listed as a prerequisite. The line -include $(DEPS) pulls these files into the Makefile. The leading hyphen means "do not fail if a file is missing", which is the case on the first build before any .d file exists. That is fine, because a missing .d file means a missing .o, which will be built anyway.

Now an edit to util.h rebuilds main.o and util.o, and nothing else.

Shell
touch util.h
make
Text
gcc -Wall -Wextra -O2 -MMD -MP -c main.c -o main.o
gcc -Wall -Wextra -O2 -MMD -MP -c util.c -o util.o
gcc -o app main.o util.o parse.o

parse.o is skipped because parse.c does not include util.h. This is the standard way to track headers, and it replaces the manual main.o: util.h lines.

Pattern rules and directories

The stem can include a directory. Compiling from src/ into build/ takes one more line and one more concept.

Makefilemakefile
SRCS := $(wildcard src/*.c)
OBJS := $(patsubst src/%.c,build/%.o,$(SRCS))

build/%.o: src/%.c
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) $(DEPFLAGS) -c $< -o $@

The stem main makes build/main.o from src/main.c. The mkdir -p inside the recipe makes sure the output directory exists. A cleaner approach, order-only prerequisites, is covered in its own post.

Two traps

Rule order and the first match. When several pattern rules could build a target, make picks the first one whose prerequisites exist or can be built. A pattern rule whose prerequisite does not exist is skipped. So %.o: %.c and %.o: %.cpp can live in the same Makefile, and the one that finds a source file wins.

A pattern rule is not a list of targets. make only uses it for a target it already needs. Writing the rule does not build anything. You still need app to depend on the object list, as above. A common mistake is expecting make to compile every .c file in the directory because a pattern rule exists. The default goal drives the build, and the rule is only the method.

Intermediate files get deleted. If a pattern rule creates a file that no one asked for by name, make treats it as intermediate and deletes it after the build. Mark files you want kept with .PRECIOUS or .SECONDARY. Plain object files named in OBJS are not intermediate, since the link rule names them.

Verifying the dependency files

After the first build, look at one of the generated files to confirm it lists what you expect, and run the build twice to check that the second run does nothing.

Shell
cat main.d
make
Text
main.o: main.c util.h parse.h
util.h:
parse.h:
make: 'app' is up to date.

If the second make rebuilds anything, a prerequisite has a timestamp in the future or a generated file is being rewritten on every run. Also check that .d files are removed by clean, since stale ones that mention a deleted header would otherwise fail the build without the empty -MP rules. Finally, remember the flag pair belongs in the compile rule only: passing -MMD to the link command is harmless but pointless, because linking has no includes to record.

One more useful trick is to keep the dependency flags in a separate variable, as the example does with DEPFLAGS, so a reader can tell which flags are about correctness of rebuilds and which are about code generation. When you later switch compilers, the dependency flags are the ones to check first, since Clang accepts the same -MMD -MP spelling and most other compilers do not.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.