A Tiny Make Engine
You now have every ingredient of a build tool: a graph of rules, a topological walk, and an up-to-date check. This lesson puts them together into a working mini-Make of about 60 lines, then runs the same Makefile through real GNU Make to compare. Once you've written one, every build tool is easier to read: CMake, Meson and Bazel are front ends that produce graphs; Make and Ninja are engines that execute them.
The Makefile we will interpret
A deliberately small subset of Make's language: explicit rules, one pattern rule (%.o: %.c), and the automatic variables $@ (the target), lt; (the first prerequisite) and $^ (all prerequisites):
mkdir -p tiny && cd tiny
cat > Makefile <<'MK'
app: main.o util.o
gcc $^ -o $@
%.o: %.c util.h
gcc -c lt; -o $@
MK
printf 'int twice(int);\n' > util.h
printf '#include "util.h"\nint twice(int x) { return 2 * x; }\n' > util.c
printf '#include <stdio.h>\n#include "util.h"\nint main(void) { printf("%%d\\n", twice(21)); return 0; }\n' > main.c
echo "--- first build"
make -j1
echo "--- second build"
make -j1
echo "--- after editing util.h"
sleep 1 && touch util.h
make -j1
./app--- first build
gcc -c main.c -o main.o
gcc -c util.c -o util.o
gcc main.o util.o -o app
--- second build
make: 'app' is up to date.
--- after editing util.h
gcc -c main.c -o main.o
gcc -c util.c -o util.o
gcc main.o util.o -o app
42
The engine
The model reads the same text, keeps a fake file system of modification times, and "runs" a recipe by printing it and giving the target a new time. The algorithm is Make's:
- Find the rule for a target: an explicit rule, or a pattern rule whose
%matches and whose expanded prerequisites can be made. - Update the prerequisites first (depth-first, left to right).
- Run the recipe if the target doesn't exist or any prerequisite is newer.
const makefile = `
app: main.o util.o
\tgcc $^ -o $@
%.o: %.c util.h
\tgcc -c lt; -o $@
`;
// --- parse: "target: prereqs" lines followed by tab-indented recipe lines
function parse(text) {
const rules = [];
for (const line of text.split("\n")) {
if (line.startsWith("\t")) rules.at(-1).recipe.push(line.slice(1));
else if (line.includes(":")) {
const [t, p] = line.split(":");
rules.push({ target: t.trim(), prereqs: p.trim().split(/\s+/).filter(Boolean), recipe: [] });
}
}
return rules;
}
// --- the engine
let clock = 100;
const files = { "main.c": 1, "util.c": 1, "util.h": 1 }; // name -> mtime
function findRule(rules, target) {
const exact = rules.find((r) => r.target === target);
if (exact) return exact;
for (const r of rules.filter((r) => r.target.includes("%"))) {
const [pre, post] = r.target.split("%");
if (!target.startsWith(pre) || !target.endsWith(post)) continue;
const stem = target.slice(pre.length, target.length - post.length);
const prereqs = r.prereqs.map((p) => p.replace("%", stem));
if (prereqs.every((p) => p in files || rules.some((x) => x.target === p)))
return { target, prereqs, recipe: r.recipe };
}
return null;
}
function make(rules, target, log) {
const rule = findRule(rules, target);
if (!rule) {
if (target in files) return; // a source file: nothing to do
throw new Error(`No rule to make target '${target}'`);
}
for (const p of rule.prereqs) make(rules, p, log); // 1. prerequisites first
const stale = !(target in files) || rule.prereqs.some((p) => files[p] > files[target]);
if (!stale) return;
for (const cmd of rule.recipe) { // 2. run the recipe with $@ lt; $^ expanded
log.push(cmd.replaceAll("$@", target).replaceAll("lt;", rule.prereqs[0]).replaceAll("$^", rule.prereqs.join(" ")));
}
files[target] = ++clock; // 3. the output is now newer than its inputs
}
function run(title) {
const log = [];
make(parse(makefile), "app", log);
console.log(`--- ${title}`);
console.log(log.length ? log.join("\n") : "make: 'app' is up to date.");
}
run("first build");
run("second build");
files["util.h"] = ++clock; // touch util.h
run("after editing util.h");
files["main.c"] = ++clock; // edit main.c
run("after editing main.c");
try { make(parse(makefile), "missing.o", []); } catch (e) { console.log("error:", e.message); }--- first build
gcc -c main.c -o main.o
gcc -c util.c -o util.o
gcc main.o util.o -o app
--- second build
make: 'app' is up to date.
--- after editing util.h
gcc -c main.c -o main.o
gcc -c util.c -o util.o
gcc main.o util.o -o app
--- after editing main.c
gcc -c main.c -o main.o
gcc main.o util.o -o app
error: No rule to make target 'missing.o'
The first three runs print the same commands as GNU Make above. The fourth shows the payoff of an incremental build: editing main.c recompiles one object and relinks. The last line shows why a pattern rule doesn't apply when its prerequisites can't be found or made (missing.c doesn't exist).
What real Make adds
The model is honest about the core, but GNU Make has much more:
| Feature | Real Make |
|---|---|
| Variables | CC = gcc, CFLAGS += -O2, recursive = vs simple :=, ?= defaults |
| Phony targets | .PHONY: clean test for names that are not files |
| Built-in rules | it already knows %.o: %.c (try make -p), which is why a Makefile with only a link rule still knows how to compile .c files |
| Error handling | stops at the first failing command (exit status ≠ 0) and deletes the half-written target if marked .DELETE_ON_ERROR |
| Parallelism | -j N runs independent recipes at once (next lesson) |
| Dry runs and debugging | -n prints commands, --trace says why each target is rebuilt, -d prints everything |
The model also shares Make's blind spots: it compares timestamps only, and it doesn't notice when a recipe changes. Edit the gcc -c lt; -o $@ line to add -O2 and neither tool rebuilds anything. Ninja fixes that by storing each output's command line; GNU Make & Ninja covers both tools in depth.
Test yourself
In %.o: %.c util.h, what is lt; when building main.o?
main.omain.cmain.c util.hutil.h
In the model, what makes a target stale?
- It is older than one day
- It doesn't exist, or a prerequisite has a newer modification time
- Its recipe changed
- It was built by another user
Why does the engine update prerequisites before checking the target?
- For speed
- A prerequisite may itself be rebuilt and become newer than the target
- Alphabetical order
- To print fewer lines