Header Dependencies (-MMD)
A build graph is only as good as its edges. Source files are easy: main.o is made from main.c. Headers are the hard part, because the list of headers a file includes is hidden inside the file, changes whenever someone edits an #include, and goes several levels deep. Writing those edges by hand is hopeless. The compiler already knows them (it opened every header), so modern builds simply ask the compiler to write them down.
The bug: a stale object
First, what goes wrong without header dependencies. This Makefile knows that main.o comes from main.c, but not that main.c includes config.h:
mkdir -p hdr && cd hdr
printf '#define MAX_USERS 10\n' > config.h
printf '#include <stdio.h>\n#include "config.h"\nint main(void) { printf("max users: %%d\\n", MAX_USERS); return 0; }\n' > main.c
cat > Makefile <<'MK'
app: main.o
gcc main.o -o app
main.o: main.c
gcc -c main.c
MK
make -j1 && ./app
sleep 1
printf '#define MAX_USERS 500\n' > config.h
make -j1 && ./appgcc -c main.c
gcc main.o -o app
max users: 10
make: 'app' is up to date.
max users: 10
The header changed, Make saw nothing to do, and the program still says 10. In a real project this kind of stale build produces bugs that vanish after make clean, which is the most expensive way to debug anything.
Asking the compiler: -M and friends
The preprocessor can print the dependencies it found, in Makefile syntax:
| Flag | Effect |
|---|---|
-M |
print a rule with all headers, including system ones, then stop (no compile) |
-MM |
the same, without system headers |
-MD / -MMD |
write the rule to a .d file as a side effect of a normal compile (-MMD skips system headers) |
-MF file |
name the .d file |
-MP |
add an empty rule for each header (see below) |
-MT target |
change the target name in the rule |
mkdir -p hdr/include && cd hdr
printf '#pragma once\n#include "limits.h"\n' > include/config.h
printf '#pragma once\n#define MAX_USERS 10\n' > include/limits.h
printf '#include <stdio.h>\n#include "config.h"\nint main(void) { printf("%%d\\n", MAX_USERS); return 0; }\n' > main.c
echo "--- gcc -MM"
gcc -MM -Iinclude main.c
echo "--- gcc -M (first lines)"
gcc -M -Iinclude main.c | head -3
echo "--- gcc -c -MMD -MP"
gcc -c -MMD -MP -Iinclude main.c
ls
cat main.d--- gcc -MM
main.o: main.c include/config.h include/limits.h
--- gcc -M (first lines)
main.o: main.c /usr/include/stdc-predef.h /usr/include/stdio.h \
/usr/include/x86_64-linux-gnu/bits/libc-header-start.h \
/usr/include/features.h /usr/include/features-time64.h \
--- gcc -c -MMD -MP
include
main.c
main.d
main.o
main.o: main.c include/config.h include/limits.h
include/config.h:
include/limits.h:
-MMD is the one build systems use: the compile that produces main.o also produces main.d, at no extra cost. Note that the nested header include/limits.h is listed even though main.c never mentions it.
Wiring it into the build
The Makefile includes all .d files (the leading - ignores the ones that don't exist yet, on the first build). Now each object depends on exactly the headers it really uses:
mkdir -p hdr && cd hdr
printf '#define MAX_USERS 10\n' > config.h
printf '#include <stdio.h>\n#include "config.h"\nint main(void) { printf("max users: %%d\\n", MAX_USERS); return 0; }\n' > main.c
cat > Makefile <<'MK'
app: main.o
gcc main.o -o app
main.o: main.c
gcc -c -MMD -MP main.c
-include main.d
MK
make -j1 && ./app
sleep 1
printf '#define MAX_USERS 500\n' > config.h
make -j1 && ./app
make -j1gcc -c -MMD -MP main.c
gcc main.o -o app
max users: 10
gcc -c -MMD -MP main.c
gcc main.o -o app
max users: 500
make: 'app' is up to date.
The second make rebuilt main.o because the included main.d added config.h to its inputs. The sleep 1 only exists because file timestamps on some file systems have a one-second resolution; see Incremental Builds.
Why -MP: deleted headers
-MP adds an empty rule (config.h:) for every header. Without it, deleting or renaming a header breaks the build: the old .d file still lists the header as an input, and Make has no rule to create it.
try_refactor() { # $1 = extra compiler flags
mkdir -p "demo$1" && cd "demo$1"
printf '#define MAX_USERS 10\n' > config.h
printf '#include <stdio.h>\n#include "config.h"\nint main(void) { printf("%%d\\n", MAX_USERS); return 0; }\n' > main.c
printf 'app: main.o\n\tgcc main.o -o app\nmain.o: main.c\n\tgcc -c -MMD %s main.c\n-include main.d\n' "$1" > Makefile
make -j1 -s
# refactor: the constant moves into main.c and the header is deleted
sleep 1
printf '#include <stdio.h>\n#define MAX_USERS 10\nint main(void) { printf("%%d\\n", MAX_USERS); return 0; }\n' > main.c
rm config.h
make -j1
cd ..
}
echo "--- without -MP"
try_refactor ""
echo "--- with -MP"
try_refactor "-MP"--- without -MP
make: *** No rule to make target 'config.h', needed by 'main.o'. Stop.
--- with -MP
gcc -c -MMD -MP main.c
gcc main.o -o app
Without -MP the build fails with No rule to make target 'config.h' until someone deletes the .d files (or runs make clean). With -MP, a missing header just counts as "changed", the object is recompiled, and the new .d file no longer mentions it.
Model: reading a .d file
A .d file is ordinary Makefile text, so any build tool can parse it. Ninja does exactly that (deps = gcc), stores the result in its own database and deletes the file. This model parses one and decides whether the object is stale by comparing modification times:
d_file = """main.o: main.c include/config.h \\
include/limits.h
include/config.h:
include/limits.h:
"""
mtimes = {"main.o": 100, "main.c": 90, "include/config.h": 95, "include/limits.h": 120}
text = d_file.replace("\\\n", " ") # join continuation lines
rules = {}
for line in text.splitlines():
target, _, deps = line.partition(":")
rules[target.strip()] = deps.split()
target = "main.o"
inputs = rules[target]
print("inputs of", target, "->", inputs)
newer = [f for f in inputs if mtimes[f] > mtimes[target]]
print("stale because of:", newer if newer else "nothing, up to date")inputs of main.o -> ['main.c', 'include/config.h', 'include/limits.h']
stale because of: ['include/limits.h']
Test yourself
What does -MMD do?
- Compiles in debug mode
- Writes a
.dfile listing the non-system headers the source used, while compiling normally - Prints dependencies and stops
- Deletes stale objects
Why add -MP?
- For parallel builds
- It adds empty rules for headers, so deleting a header doesn't break the build with 'No rule to make target'
- It makes paths absolute
- It includes system headers
In the first session, why did ./app still print 10 after config.h changed?
- The compiler cached it
- The Makefile didn't list
config.has an input ofmain.o, so Make didn't rebuild it printfcaches output- The header was not saved