Field Notes: Makefiles That Don't Bite
Practical rules collected from real Makefiles that broke builds, deleted the wrong files or shipped stale binaries. Each one comes with a session that shows the failure, so you'll recognise it when you meet it.
1. Start every Makefile with the same prelude
SHELL := /bin/bash # recipes use bash, not whatever /bin/sh is (dash on Debian/Ubuntu)
.SHELLFLAGS := -eu -o pipefail -c # fail on errors, unset variables and failed pipe stages
.DELETE_ON_ERROR: # see rule 2
MAKEFLAGS += --warn-undefined-variables --no-builtin-rules
.SUFFIXES:Each line removes a class of surprises: /bin/sh is dash on Debian and Ubuntu, so a recipe that works on a Fedora laptop may fail in CI; pipefail makes gen | sort > out fail when gen fails; no built-in rules means every rule in effect is one you can read. (.SHELLFLAGS and SHELL only affect recipes, not your login shell.)
2. .DELETE_ON_ERROR, or broken files live forever
If a recipe writes its target and then fails (a generator that crashes halfway, a > out redirection that creates the file before the command dies), the half-written file has a fresh time stamp. The next make believes it's up to date:
mkdir -p doe && cd doe
printf 'line 1\nline 2\n' > input.txt
cat > gen.sh <<'SH'
#!/bin/sh
head -1 "$1"
exit 1 # crash after writing part of the output
SH
chmod +x gen.sh
printf 'out.txt: input.txt gen.sh\n\t./gen.sh lt; > $@\n' > Makefile
make -j1; make -j1; cat out.txt
echo "=== with .DELETE_ON_ERROR"
rm out.txt
printf '.DELETE_ON_ERROR:\nout.txt: input.txt gen.sh\n\t./gen.sh lt; > $@\n' > Makefile
make -j1; ls out.txt 2>/dev/null || echo "out.txt was removed"./gen.sh input.txt > out.txt
make: *** [Makefile:2: out.txt] Error 1
make: 'out.txt' is up to date.
line 1
=== with .DELETE_ON_ERROR
./gen.sh input.txt > out.txt
make: *** [Makefile:3: out.txt] Error 1
make: *** Deleting file 'out.txt'
out.txt was removed
The GNU Make manual itself recommends .DELETE_ON_ERROR in every Makefile; it's off by default only for historical compatibility.
3. Never cd without &&
cd in a recipe line followed by ; keeps going even if the directory doesn't exist, and the next command runs in the wrong place. With rm, that deletes the wrong files:
mkdir -p cdtest/build && cd cdtest
touch keep-me.txt build/old.txt
cat > Makefile <<'MK'
clean-bad:
cd biuld; rm -f *.txt
clean-good:
cd biuld && rm -f *.txt
MK
make -j1 clean-good; ls
echo "---"
make -j1 clean-bad; lscd biuld && rm -f *.txt
/bin/sh: 1: cd: can't cd to biuld
make: *** [Makefile:5: clean-good] Error 2
Makefile
build
keep-me.txt
---
cd biuld; rm -f *.txt
/bin/sh: 1: cd: can't cd to biuld
Makefile
build
The typo biuld made clean-bad delete keep-me.txt from the top directory, and Make reported success because the last command succeeded. With && the build stopped instead. Even better: avoid cd entirely (rm -f build/*.txt, $(MAKE) -C dir, tool -C dir), and use .SHELLFLAGS := -e -c so that any failing command stops the line.
4. Always $(MAKE) for recursion
Calling make by name inside a recipe looks the same, but the sub-make loses the parent's options. The most visible case is make -n: lines with $(MAKE) are still executed in dry-run mode, so you can see what the sub-make would do; a plain make line is only printed:
mkdir -p rec/sub && cd rec
printf 'all:\n\techo "building sub"\n' > sub/Makefile
printf 'good:\n\t$(MAKE) --no-print-directory -C sub\nbad:\n\tmake --no-print-directory -C sub\n' > Makefile
echo "== make -n good"; make -n good
echo "== make -n bad"; make -n bad== make -n good
make --no-print-directory -C sub
echo "building sub"
== make -n bad
make --no-print-directory -C sub
The same mechanism passes -k, -j (through the jobserver), -s and command-line variables to sub-makes. With a plain make and -j8, every sub-make either runs serially or starts its own unlimited set of jobs, depending on your Make version and MAKEFLAGS. (Recursive vs Non-recursive Make)
5. Spaces in file names: just don't
Make splits every list on whitespace, so a file name with a space becomes two words. There is no reliable quoting for targets and prerequisites:
mkdir -p sp && cd sp
touch "my notes.txt" plain.txt
printf 'FILES := $(wildcard *.txt)\n$(info FILES has $(words $(FILES)) words: $(FILES))\nall: $(FILES)\n\t@echo ok\n' > Makefile
make -j1FILES has 3 words: my notes.txt plain.txt
make: *** No rule to make target 'my', needed by 'all'. Stop.
Keep spaces out of source trees and build directories. A build directory inside ~/My Projects/ is a classic CI-agent and Windows-home-folder problem, and CMake and Meson handle it much better than hand-written Makefiles. Inside recipes, which are shell commands, quote anything that could contain spaces or shell characters: cp "lt;" "$@", "$(DESTDIR)$(PREFIX)/bin".
6. Intermediate files disappear (unless you say otherwise)
When Make builds a file only as a step in a chain of implicit rules (.txt → generated .c → .o), and that file isn't mentioned as a target or prerequisite anywhere, it's an intermediate file. Make deletes it at the end of the build:
mkdir -p chain && cd chain
printf '42\n' > answer.txt
cat > Makefile <<'MK'
all: answer.o
%.c: %.txt
printf 'int answer(void) { return %s; }\n' $(cat lt;) > $@
%.o: %.c
gcc -c lt; -o $@
MK
make -j1
ls answer.c 2>/dev/null || echo "answer.c is gone"
echo "=== with .SECONDARY"
rm -f answer.o
printf '.SECONDARY:\n' >> Makefile
make -j1
ls answer.cprintf 'int answer(void) { return %s; }\n' $(cat answer.txt) > answer.c
gcc -c answer.c -o answer.o
rm answer.c
answer.c is gone
=== with .SECONDARY
printf 'int answer(void) { return %s; }\n' $(cat answer.txt) > answer.c
gcc -c answer.c -o answer.o
answer.c
That's surprising when you want to inspect generated code. Your options in GNU Make 4.3:
| Directive | Effect |
|---|---|
.SECONDARY: file… |
never delete these intermediates (with no prerequisites: none at all), and don't rebuild them just because they're missing |
.PRECIOUS: file… |
don't delete them, also not when Make is interrupted or the recipe fails |
| mention the file explicitly | e.g. SRCS_GEN := answer.c as a prerequisite somewhere: it's no longer intermediate |
(GNU Make 4.4 added .NOTINTERMEDIATE, which is clearer, but it doesn't exist in 4.3.)
7. Smaller habits
- Use
$(RM)(rm -f) andmkdir -psocleanand directory creation never fail on reruns. - Never let a real file depend on a
.PHONYtarget: it rebuilds every time. - Keep
cleanboring: delete the build directory, nothing else. Acleanthat deletes by pattern in the source tree will eventually delete a source file. - Put the default target first, and make it
all(declared.PHONY), somakewith no arguments does the obvious thing; add ahelptarget that lists the others. - Don't use
$(shell …)with=: it runs on every expansion. Use:=. - Test a clean build and a no-op build in CI. A no-op build that does work means a missing or always-changing file somewhere;
--tracefinds it.
Test yourself
What does .DELETE_ON_ERROR: do?
- Deletes all targets on any error
- Deletes the target of a recipe that fails, so a half-written file isn't mistaken for up to date
- Ignores errors
- Deletes intermediate files
Why is cd build; rm -f *.o dangerous in a recipe?
rmis slow- If
cdfails,rmstill runs, in the wrong directory ;is not allowed in recipes- It deletes the Makefile
Make deleted the generated parser.c after building parser.o. Why?
- A bug
- It was an intermediate file of an implicit-rule chain; mark it
.SECONDARYor.PRECIOUSto keep it .DELETE_ON_ERROR- The disk was full