Pattern Rules and Automatic Variables
Replace repetitive rules with % pattern rules, read automatic variables like $@, $< and $^, understand Make's built-in rules, and build into separate output directories.
By The Dark DebuggerUpdated 20 min read
So far every file in our Makefiles has had its own hand-written rule. This article replaces
them with pattern rules, one rule that covers every .c file, and the automatic
variables ($@, $<, $^ and friends) that make such rules possible. We'll also look
at the rules Make has built in, static pattern rules, deriving object lists from the source
tree, keeping build output in its own directory, and vpath. It builds on
Variables and How Make Expands Them and continues
the logstat project.
The repetition problem
At the end of the last article, logstat's Makefile had three object rules that differ only
in the file name:
main.o: main.c parse.h report.h
$(CC) $(CPPFLAGS) $(WARNINGS) $(CFLAGS) -c main.c
parse.o: parse.c parse.h
$(CC) $(CPPFLAGS) $(WARNINGS) $(CFLAGS) -c parse.c
report.o: report.c report.h parse.h
$(CC) $(CPPFLAGS) $(WARNINGS) $(CFLAGS) -c report.cAdding a source file means copying a rule and editing the name in two places. Get one wrong
and you compile the wrong file into the wrong object. And everything still lives in one flat
directory, so *.o files sit next to the sources and debug and release builds overwrite each
other. Let's fix both. First, the project gets a conventional layout:
.
├── access.log
├── include
│ ├── parse.h
│ └── report.h
└── src
├── main.c
├── parse.c
└── report.cAutomatic variables
A recipe that works for many targets can't hard-code the file names. Instead, Make sets a handful of automatic variables fresh for every rule it runs. To see them, here's a Makefile whose recipes print them instead of compiling anything (the source files are empty placeholders):
bin/logstat: obj/main.o obj/parse.o obj/report.o obj/parse.o | bin
@echo '$$@ = $@'
@echo '$$< = $<'
@echo '$$^ = $^'
@echo '$$+ = $+'
@echo '$$? = $?'
@echo '$$| = $|'
@echo '$$(@D) = $(@D) $$(@F) = $(@F)'
@touch $@
obj/%.o: src/%.c
@echo '$$* = $* $$< = $< $$(<D) = $(<D) $$(<F) = $(<F)'
@mkdir -p $(@D) && touch $@
bin:
mkdir -p $@Each '$$@' reaches the shell as the literal text $@ inside single quotes, so the label
prints as-is, while the bare $@ after it is expanded by Make. obj/parse.o is listed twice
on purpose.
make -f autovars.mk$* = main $< = src/main.c $(<D) = src $(<F) = main.c
$* = parse $< = src/parse.c $(<D) = src $(<F) = parse.c
$* = report $< = src/report.c $(<D) = src $(<F) = report.c
mkdir -p bin
$@ = bin/logstat
$< = obj/main.o
$^ = obj/main.o obj/parse.o obj/report.o
$+ = obj/main.o obj/parse.o obj/report.o obj/parse.o
$? = obj/main.o obj/parse.o obj/report.o
$| = bin
$(@D) = bin $(@F) = logstatNow touch one source and run it again. Watch $?:
touch src/parse.c
make -f autovars.mk$* = parse $< = src/parse.c $(<D) = src $(<F) = parse.c
$@ = bin/logstat
$< = obj/main.o
$^ = obj/main.o obj/parse.o obj/report.o
$+ = obj/main.o obj/parse.o obj/report.o obj/parse.o
$? = obj/parse.o
$| = bin
$(@D) = bin $(@F) = logstat| Variable | Value | Typical use |
|---|---|---|
$@ | The target being built | -o $@ |
$< | The first prerequisite | The source file in a compile rule |
$^ | All prerequisites, duplicates removed | The object list in a link rule |
$+ | All prerequisites, duplicates kept, in order | Link lines where library order and repetition matter |
$? | Prerequisites newer than the target | Updating only changed members of an archive |
$| | Order-only prerequisites (after the |) | Rarely used directly |
$* | The stem: what % matched | Naming related files, like $*.d |
$(@D), $(@F) | Directory and file part of $@ | mkdir -p $(@D) |
$(<D), $(<F) | Directory and file part of $< | Running a tool from the source's directory |
Two rules about them. They only have values inside recipes: in a prerequisite list,
$@ is empty. And $< is the first prerequisite as written, so in a compile rule the
.c file must come first, before any headers.
Pattern rules
A pattern rule uses % in the target and prerequisites. % matches any non-empty string
(the stem), and the same stem is substituted into the prerequisites:
obj/%.o: src/%.c | obj
$(CC) $(CPPFLAGS) $(WARNINGS) $(CFLAGS) -c -o $@ $<Read it as: "any file obj/X.o can be made from src/X.c by this recipe". Here's the whole
Makefile with it:
CFLAGS ?= -O2
WARNINGS := -Wall -Wextra
CPPFLAGS := -Iinclude
LDLIBS := -lm
OBJS := obj/main.o obj/parse.o obj/report.o
.PHONY: all clean
all: bin/logstat
bin/logstat: $(OBJS) | bin
$(CC) $(LDFLAGS) -o $@ $^ $(LDLIBS)
obj/%.o: src/%.c | obj
$(CC) $(CPPFLAGS) $(WARNINGS) $(CFLAGS) -c -o $@ $<
obj/main.o: include/parse.h include/report.h
obj/parse.o: include/parse.h
obj/report.o: include/report.h include/parse.h
bin obj:
mkdir -p $@
clean:
rm -rf bin objThree things to notice:
- The header lines have no recipe. A rule without a recipe just adds prerequisites to
a target. Make merges them with the pattern rule, so
obj/report.odepends onsrc/report.c(from the pattern) and on its two headers (from the extra line). -IincludeinCPPFLAGStells the compiler where to find headers, so the sources can still say#include "parse.h".| binand| objare order-only prerequisites, explained further down.
make
make
touch include/report.h
makemkdir -p obj
cc -Iinclude -Wall -Wextra -O2 -c -o obj/main.o src/main.c
cc -Iinclude -Wall -Wextra -O2 -c -o obj/parse.o src/parse.c
cc -Iinclude -Wall -Wextra -O2 -c -o obj/report.o src/report.c
mkdir -p bin
cc -o bin/logstat obj/main.o obj/parse.o obj/report.o -lm
make: Nothing to be done for 'all'.
cc -Iinclude -Wall -Wextra -O2 -c -o obj/main.o src/main.c
cc -Iinclude -Wall -Wextra -O2 -c -o obj/report.o src/report.c
cc -o bin/logstat obj/main.o obj/parse.o obj/report.o -lmOne rule, three objects, and header changes still rebuild exactly the right ones.
Make's built-in rules
Make ships with dozens of implicit rules, which is why some Makefiles build things they never
mention. In a directory containing only hello.c and no Makefile at all:
ls
make hello
./hellohello.c
cc hello.c -o hello
hello from a Makefile-less buildMake looked for a way to create hello, found its built-in rule "a program can be made from
the .c file of the same name", and ran it. The odd spacing is from empty variables
(CFLAGS, CPPFLAGS, LDFLAGS and others) in the built-in recipe. You can read any built-in
rule from Make's database:
make -p -f /dev/null 2>/dev/null | grep -A3 '^%.o: %.c$'%.o: %.c
# recipe to execute (built-in):
$(COMPILE.c) $(OUTPUT_OPTION) $<COMPILE.c is $(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c and OUTPUT_OPTION is
-o $@. That's why your .o files can build without any rule. This flat-directory
Makefile only says how to link:
LDLIBS := -lm
logstat: main.o parse.o report.o
$(CC) $(LDFLAGS) -o $@ $^ $(LDLIBS)makecc -c -o main.o main.c
cc -c -o parse.o parse.c
cc -c -o report.o report.c
cc -o logstat main.o parse.o report.o -lmHandy for tiny projects. The cost is magic: the objects were built with no warnings, and
nothing in the file tells a reader how. For real projects I turn the built-ins off, with
make -r on the command line or, better, in the Makefile itself:
MAKEFLAGS += --no-builtin-rulesmake: *** No rule to make target 'main.o', needed by 'logstat'. Stop.Now every rule must be written down, and a missing one is an error instead of a silent
surprise. You'll also see the older idiom .SUFFIXES: (an empty list) in Makefiles. It
clears the old-style suffix rules like .c.o:, which is a subset of what -r does.
--no-builtin-variables (-R) goes further and also removes the default values of CC,
CFLAGS and the rest.
Static pattern rules
A normal pattern rule applies to any target that matches. A static pattern rule applies a pattern to an explicit list of targets only:
CPPFLAGS := -Iinclude
SRCS := $(wildcard src/*.c)
OBJS := $(patsubst src/%.c,obj/%.o,$(SRCS))
$(info SRCS = $(SRCS))
$(info OBJS = $(OBJS))
$(info same = $(SRCS:src/%.c=obj/%.o))
all: $(OBJS)
$(OBJS): obj/%.o: src/%.c
@mkdir -p $(@D)
$(CC) $(CPPFLAGS) -Wall -c -o $@ $<The syntax is targets: target-pattern: prerequisite-patterns. This file also shows the
standard way to build the object list from whatever is in src/. $(wildcard src/*.c) lists
the sources, and $(patsubst src/%.c,obj/%.o,...) rewrites each name. The substitution
reference $(SRCS:src/%.c=obj/%.o) is shorthand for the same thing. $(info) prints while
the Makefile is read. Built-in Functions covers all three in
detail.
makeSRCS = src/main.c src/parse.c src/report.c
OBJS = obj/main.o obj/parse.o obj/report.o
same = obj/main.o obj/parse.o obj/report.o
cc -Iinclude -Wall -c -o obj/main.o src/main.c
cc -Iinclude -Wall -c -o obj/parse.o src/parse.c
cc -Iinclude -Wall -c -o obj/report.o src/report.cWhy choose a static pattern rule? Because it's explicit. A general pattern rule is a candidate for every file Make ever needs, and Make silently ignores it when the prerequisite can't be found, then falls back to another rule or reports "No rule to make target". A static pattern rule says exactly which targets it covers and complains when one doesn't fit (see Common mistakes). Use them when one group of files needs different treatment, for example test sources built with extra flags.
Build directories and order-only prerequisites
Keeping build output in its own directory needs the directory to exist before the compiler writes into it. The obvious way is to make the directory a prerequisite:
CPPFLAGS := -Iinclude
OBJS := obj/main.o obj/parse.o obj/report.o
all: $(OBJS)
obj/%.o: src/%.c obj
$(CC) $(CPPFLAGS) -c -o $@ $<
obj:
mkdir -p $@make
make
makemkdir -p obj
cc -Iinclude -c -o obj/main.o src/main.c
cc -Iinclude -c -o obj/parse.o src/parse.c
cc -Iinclude -c -o obj/report.o src/report.c
cc -Iinclude -c -o obj/main.o src/main.c
cc -Iinclude -c -o obj/parse.o src/parse.c
cc -Iinclude -c -o obj/main.o src/main.c
cc -Iinclude -c -o obj/report.o src/report.cIt never settles. A directory's modification time changes whenever an entry inside it is
created, and GCC writes each object as a new file. So writing report.o makes obj newer
than main.o and parse.o, and the next run rebuilds them, which bumps the directory again.
The fix is an order-only prerequisite, listed after a |. It means "this must exist
before the recipe runs, but its timestamp doesn't matter":
obj/%.o: src/%.c | objThat's the form used in the pattern-rule Makefile above, which was up to date on its second
run. Use | for every output directory. The other common approach is @mkdir -p $(@D) as
the first recipe line, which needs no directory rule at all; we'll use that in
Built-in Functions.
vpath: searching for prerequisites
vpath tells Make which directories to search for prerequisites matching a pattern. It lets
you keep simple rules like %.o: %.c while the sources live elsewhere:
vpath %.c src
vpath %.h include
CPPFLAGS := -Iinclude
LDLIBS := -lm
logstat: main.o parse.o report.o
$(CC) $(LDFLAGS) -o $@ $^ $(LDLIBS)
%.o: %.c
$(CC) $(CPPFLAGS) -Wall -c -o $@ $<
main.o: parse.h report.h
parse.o: parse.h
report.o: report.h parse.hmakecc -Iinclude -Wall -c -o main.o src/main.c
cc -Iinclude -Wall -c -o parse.o src/parse.c
cc -Iinclude -Wall -c -o report.o src/report.c
cc -o logstat main.o parse.o report.o -lmThe rule asked for main.c; Make found src/main.c and put the found path into $<. That's
why the recipe must always use $< and $^ rather than spelling the names out.
Two cautions. Use vpath for source files only. If a generated file or a target can be found
through vpath, Make may decide an old copy elsewhere is good enough. And notice the objects
landed in the project root. vpath helps Make find inputs; it doesn't tidy up outputs. For
most new projects, explicit src/ and obj/ paths in the pattern, as above, are clearer.
vpath earns its keep in older projects with sources spread over several directories.
Where you'll use this
Debug and release builds side by side
In the last article, make debug silently reused release objects. With pattern rules we can
give each build type its own directory, so objects never mix:
BUILD ?= release
CFLAGS_release := -O2
CFLAGS_debug := -O0 -g -DDEBUG
CFLAGS ?= $(CFLAGS_$(BUILD))
WARNINGS := -Wall -Wextra
CPPFLAGS := -Iinclude
LDLIBS := -lm
OUT := build/$(BUILD)
SRCS := $(wildcard src/*.c)
OBJS := $(patsubst src/%.c,$(OUT)/obj/%.o,$(SRCS))
BIN := $(OUT)/logstat
.PHONY: all clean
all: $(BIN)
$(BIN): $(OBJS)
$(CC) $(LDFLAGS) -o $@ $^ $(LDLIBS)
$(OUT)/obj/%.o: src/%.c | $(OUT)/obj
$(CC) $(CPPFLAGS) $(WARNINGS) $(CFLAGS) -c -o $@ $<
$(OUT)/obj:
mkdir -p $@
$(OUT)/obj/main.o: include/parse.h include/report.h
$(OUT)/obj/parse.o: include/parse.h
$(OUT)/obj/report.o: include/report.h include/parse.h
clean:
rm -rf build$(CFLAGS_$(BUILD)) is a computed variable name: with BUILD=debug it reads CFLAGS_debug.
Adding a source file to src/ needs no Makefile change at all.
make
make BUILD=debug
make
make BUILD=debugmkdir -p build/release/obj
cc -Iinclude -Wall -Wextra -O2 -c -o build/release/obj/main.o src/main.c
cc -Iinclude -Wall -Wextra -O2 -c -o build/release/obj/parse.o src/parse.c
cc -Iinclude -Wall -Wextra -O2 -c -o build/release/obj/report.o src/report.c
cc -o build/release/logstat build/release/obj/main.o build/release/obj/parse.o build/release/obj/report.o -lm
mkdir -p build/debug/obj
cc -Iinclude -Wall -Wextra -O0 -g -DDEBUG -c -o build/debug/obj/main.o src/main.c
cc -Iinclude -Wall -Wextra -O0 -g -DDEBUG -c -o build/debug/obj/parse.o src/parse.c
cc -Iinclude -Wall -Wextra -O0 -g -DDEBUG -c -o build/debug/obj/report.o src/report.c
cc -o build/debug/logstat build/debug/obj/main.o build/debug/obj/parse.o build/debug/obj/report.o -lm
make: Nothing to be done for 'all'.
make: Nothing to be done for 'all'.Switching between the two costs nothing once both exist. file confirms they're different
programs (the sed just removes a long build hash from its output):
file build/release/logstat build/debug/logstat | sed 's/, BuildID[^,]*//'build/release/logstat: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, not stripped
build/debug/logstat: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, with debug_info, not strippedCI pipelines use exactly this to build a release artifact and an instrumented test build from the same checkout without one clobbering the other.
Pre-compressing a static site's assets
Pattern rules aren't only for compilers. Web servers like nginx can serve a pre-compressed
app.css.gz instead of compressing app.css on every request (nginx's gzip_static
option). A two-line pattern rule keeps the .gz files in step with their sources:
ASSETS := $(wildcard public/*.css public/*.js public/*.svg)
GZ := $(ASSETS:%=%.gz)
.PHONY: compress clean
compress: $(GZ)
%.gz: %
gzip -9 -n -c $< > $@
clean:
rm -f $(GZ)make
make
echo '.footer { color: #6b7280; }' >> public/app.css
makegzip -9 -n -c public/app.css > public/app.css.gz
gzip -9 -n -c public/app.js > public/app.js.gz
gzip -9 -n -c public/logo.svg > public/logo.svg.gz
make: Nothing to be done for 'compress'.
gzip -9 -n -c public/app.css > public/app.css.gz%.gz: % matches any file name with .gz added. -n leaves the original name and timestamp
out of the archive, so unchanged input gives byte-identical output, which matters if the
results are cached or committed. Only the edited stylesheet was recompressed. The sizes
show one more thing worth knowing:
ls -l public | sed 1d | awk '{print $5, $9}'5119 app.css
281 app.css.gz
3911 app.js
226 app.js.gz
117 logo.svg
128 logo.svg.gzCompression made the tiny SVG bigger. Real setups usually skip files under a size threshold.
Common mistakes
$< in a link rule
$< is only the first prerequisite. Use it in a link rule and the program is linked from one
object:
grep -n -- '-o \$@ \$<' Makefile
make13: $(CC) $(LDFLAGS) -o $@ $< $(LDLIBS)
16: $(CC) $(CPPFLAGS) $(WARNINGS) $(CFLAGS) -c -o $@ $<
mkdir -p obj
cc -Iinclude -Wall -Wextra -O2 -c -o obj/main.o src/main.c
cc -Iinclude -Wall -Wextra -O2 -c -o obj/parse.o src/parse.c
cc -Iinclude -Wall -Wextra -O2 -c -o obj/report.o src/report.c
mkdir -p bin
cc -o bin/logstat obj/main.o -lm
[…]
main.c:(.text.startup+0x9f): undefined reference to `parse_line'
[…]
collect2: error: ld returned 1 exit status
make: *** [Makefile:13: bin/logstat] Error 1(I've trimmed the linker's own path from three lines.) The echoed link command gives it
away: only obj/main.o. Compile rules use $<, link rules use $^.
A pattern that doesn't match where the files are
The objects live in obj/ and the sources in src/, but the pattern rule assumes both are
in the same directory:
CPPFLAGS := -Iinclude
LDLIBS := -lm
OBJS := obj/main.o obj/parse.o obj/report.o
bin/logstat: $(OBJS)
mkdir -p bin
$(CC) -o $@ $^ $(LDLIBS)
%.o: %.c
$(CC) $(CPPFLAGS) -c -o $@ $<make: *** No rule to make target 'obj/main.o', needed by 'bin/logstat'. Stop.For obj/main.o, the stem is obj/main, so Make looked for obj/main.c, didn't find it,
and quietly discarded the rule. The error never mentions the pattern rule, which is what makes
this confusing. Write the directories into the pattern (obj/%.o: src/%.c), or add vpath
for the sources.
A target that doesn't fit a static pattern
CPPFLAGS := -Iinclude
OBJS := obj/main.o obj/parse.o obj/report.o legacy/compat.o
all: $(OBJS)
$(OBJS): obj/%.o: src/%.c
@mkdir -p $(@D)
$(CC) $(CPPFLAGS) -Wall -c -o $@ $<Makefile:6: target 'legacy/compat.o' doesn't match the target pattern
cc -Iinclude -Wall -c -o obj/main.o src/main.c
cc -Iinclude -Wall -c -o obj/parse.o src/parse.c
cc -Iinclude -Wall -c -o obj/report.o src/report.c
cc -Iinclude -Wall -c -o legacy/compat.o
x86_64-linux-gnu-gcc-13: fatal error: no input files
compilation terminated.
make: *** [Makefile:8: legacy/compat.o] Error 1At least Make warns, unlike the previous case. It still ran the recipe with an empty $<, so
the real failure comes a moment later from the compiler. (x86_64-linux-gnu-gcc-13 is the
real name of the GCC binary behind cc in my test environment.) Read warnings above an error,
not just the last line.
A phony target with the same name as a directory
I wrote this for the docs exercise below, naming the phony "build the site" target after the output directory:
.PHONY: site clean
site: $(PAGES)
site/%.html: docs/%.md md2html.sh | site
./md2html.sh $< > $@
site:
mkdir -p $@make: Circular site/changelog.html <- site dependency dropped.
./md2html.sh docs/changelog.md > site/changelog.html
/bin/sh: 1: cannot create site/changelog.html: Directory nonexistent
make: *** [Makefile:7: site/changelog.html] Error 2The two site: rules merge into one target that depends on the pages, while each page depends
on site, a loop. Make dropped the loop, so the directory was never created. Give action
targets and directories different names: html for the action, site for the directory.
Summary
- Automatic variables exist only in recipes:
$@target,$<first prerequisite,$^all prerequisites (deduplicated),$?the newer ones,$*the stem, and$(@D)/$(@F)for directory and file parts. - A pattern rule (
obj/%.o: src/%.c) replaces a rule per file. Extra recipe-less lines likeobj/main.o: include/parse.hadd header prerequisites to it. - If a pattern's prerequisite can't be found, Make silently skips the rule, and you get "No rule to make target" naming the target, not the rule.
- Make has built-in rules (
make -pshows them). They're why a.obuilds without a rule.MAKEFLAGS += --no-builtin-rules(ormake -r) turns them off. - Static pattern rules (
$(OBJS): obj/%.o: src/%.c) apply a pattern to a fixed list and warn about targets that don't match. $(wildcard src/*.c)plus$(patsubst src/%.c,obj/%.o,...)derives the object list from the source tree.- Make output directories order-only prerequisites (
| obj). As normal prerequisites, their changing timestamps cause endless rebuilds. vpath %.c srcmakes Make search for sources; recipes must then use$</$^, never hard-coded names.
Exercises
For this rule, write down the values of $@, $<, $^, $|, $(@D) and $(@F), then
check with a recipe that prints them.
dist/app.tar.gz: build/app README.md LICENSE | distShow Solution
dist/app.tar.gz: build/app README.md LICENSE | dist
@echo '$$@=$@ $$<=$< $$^=$^ $$|=$| $$(@D)=$(@D) $$(@F)=$(@F)'With build/app, README.md, LICENSE and the dist/ directory created first:
make$@=dist/app.tar.gz $<=build/app $^=build/app README.md LICENSE $|=dist $(@D)=dist $(@F)=app.tar.gzThe order-only dist appears in $| but not in $^.
A project keeps Markdown pages in docs/ and has a small converter, md2html.sh:
#!/bin/sh
# Usage: ./md2html.sh page.md > page.html
# Minimal converter: the first "# " line becomes the title, other lines become paragraphs.
title=$(sed -n 's/^# //p' "$1" | head -n 1)
printf '<!doctype html>\n<title>%s</title>\n<h1>%s</h1>\n' "$title" "$title"
sed -e '/^# /d' -e '/^$/d' -e 's/.*/<p>&<\/p>/' "$1"Write a Makefile whose html target builds site/X.html for every docs/X.md. Editing one
page should rebuild only that page. Editing the converter should rebuild all of them.
Hint
Derive the list of pages with wildcard and patsubst. The converter belongs in the pattern
rule's prerequisites. The output directory should be order-only, and must not share its name
with the phony target.
Show Solution
PAGES := $(patsubst docs/%.md,site/%.html,$(wildcard docs/*.md))
.PHONY: html clean
html: $(PAGES)
site/%.html: docs/%.md md2html.sh | site
./md2html.sh $< > $@
site:
mkdir -p $@
clean:
rm -rf sitemake
cat site/install.html
make
touch docs/usage.md
make
touch md2html.sh
makemkdir -p site
./md2html.sh docs/changelog.md > site/changelog.html
./md2html.sh docs/install.md > site/install.html
./md2html.sh docs/usage.md > site/usage.html
<!doctype html>
<title>Installing logstat</title>
<h1>Installing logstat</h1>
<p>Download the tarball and run make install.</p>
<p>Use PREFIX to choose the install location.</p>
make: Nothing to be done for 'html'.
./md2html.sh docs/usage.md > site/usage.html
./md2html.sh docs/changelog.md > site/changelog.html
./md2html.sh docs/install.md > site/install.html
./md2html.sh docs/usage.md > site/usage.html$< is the Markdown file because it's the first prerequisite; md2html.sh is listed second
only so that changing it rebuilds every page. In a real project the converter would be pandoc
or a static-site generator, and the Makefile wouldn't change.
Using the debug/release Makefile from "Where you'll use this", show that touching one source file and building both variants recompiles that file once per variant and nothing else.
Show Solution
touch src/parse.c
make
make BUILD=debugEach build recompiles parse.o in its own directory and relinks its own binary:
cc -Iinclude -Wall -Wextra -O2 -c -o build/release/obj/parse.o src/parse.c
cc -o build/release/logstat build/release/obj/main.o build/release/obj/parse.o build/release/obj/report.o -lm
cc -Iinclude -Wall -Wextra -O0 -g -DDEBUG -c -o build/debug/obj/parse.o src/parse.c
cc -o build/debug/logstat build/debug/obj/main.o build/debug/obj/parse.o build/debug/obj/report.o -lmBecause OUT depends on BUILD, the two variants have entirely separate targets, and Make
judges each against its own timestamps.
The sales-report Makefile from Introduction to Make had
one hand-written rule per region. Rewrite it so that dropping a new data/REGION.csv into
the project adds that region to report.txt with no Makefile change.
Show Solution
REGIONS := $(patsubst data/%.csv,%,$(wildcard data/*.csv))
SUMMARIES := $(patsubst %,build/%.txt,$(REGIONS))
report.txt: $(SUMMARIES)
cat $^ > $@
build/%.txt: data/%.csv summarize.sh | build
./summarize.sh $< > $@
build:
mkdir -p $@make
make
printf 'date,sku,units,unit_price\n2026-11-04,KB-104,2,49.00\n' > data/west.csv
makemkdir -p build
./summarize.sh data/east.csv > build/east.txt
./summarize.sh data/north.csv > build/north.txt
./summarize.sh data/south.csv > build/south.txt
cat build/east.txt build/north.txt build/south.txt > report.txt
make: 'report.txt' is up to date.
./summarize.sh data/west.csv > build/west.txt
cat build/east.txt build/north.txt build/south.txt build/west.txt > report.txtThe new region was picked up because $(wildcard) runs every time Make reads the Makefile.
report.txt was rebuilt because it gained a prerequisite that was newer than it. The
regions now appear in alphabetical order, since wildcard results are sorted.
Tested with: GNU Make 4.3 and GCC 13.3 on Ubuntu 24.04 (WSL2), November 2026. Every
Makefile and output above was run as shown. The trims are linker lines containing the
toolchain's install path in the $< mistake, and the BuildID hash removed by the sed in
the file example. The nginx gzip_static setup itself wasn't configured; only the
compression step ran.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every Makefile tutorial here is tested end to end before publishing.