Make & Ninja Exercises
Six exercises: four real build files to repair or complete, and two models to implement in JavaScript. Each starter runs as it is and shows the wrong behaviour; change the code marked TODO until the output matches the expected output, then compare with the solution. On the site the bash sessions show their recorded output; copy them into a terminal with GNU Make and Ninja (or the course's Docker image) to run your changes.
Exercise 1: Repair a broken Makefile
Topics: Recipes, Tabs & the Shell, Targets, Prerequisites & Recipes
This Makefile has two bugs: a recipe indented with spaces, and a missing header dependency (editing limits.h doesn't rebuild anything). Fix both.
mkdir -p ex1 && cd ex1
printf '#define MAX 3\n' > limits.h
printf '#include <stdio.h>\n#include "limits.h"\nint main(void) { printf("max=%%d\\n", MAX); return 0; }\n' > main.c
cat > Makefile <<'MK'
app: main.o
gcc main.o -o app
main.o: main.c
gcc -c main.c -o main.o
MK
make -j1 && ./app
sleep 1 && sed -i 's/3/5/' limits.h
make -j1 && ./appMakefile:4: *** missing separator. Stop.
Makefile:4: *** missing separator. Stop.
The error appears twice because the session runs make twice. Make 4.3 adds its "did you mean TAB" hint only for lines indented with eight spaces, so with four you get the bare message.
Expected output:
gcc -c main.c -o main.o
gcc main.o -o app
max=3
gcc -c main.c -o main.o
gcc main.o -o app
max=5Show solution
The recipe line needs a TAB, and main.o must list the header (or use -MMD -MP with -include main.d, as in Automatic Header Dependencies):
app: main.o
gcc main.o -o app
main.o: main.c limits.h
gcc -c main.c -o main.oExercise 2: One rule for every object
Topics: Pattern & Static Pattern Rules, Automatic Variables, Make Functions
Built-in rules are switched off, so Make can't compile anything. Compute OBJS from SRCS with a function and add one pattern rule using automatic variables.
mkdir -p ex2 && cd ex2
for f in red green blue; do printf 'int %s(void) { return 1; }\n' $f > $f.c; done
printf 'int red(void), green(void), blue(void);\nint main(void) { return red() + green() + blue() - 3; }\n' > main.c
cat > Makefile <<'MK'
MAKEFLAGS += --no-builtin-rules
SRCS := main.c red.c green.c blue.c
OBJS := # TODO: derive from SRCS
app: $(OBJS)
gcc $^ -o $@
# TODO: a pattern rule that compiles one .c into one .o
MK
make -j1 && ./app && echo "exit 0"gcc -o app
gcc: fatal error: no input files
compilation terminated.
make: *** [Makefile:5: app] Error 1
Expected output:
gcc -c main.c -o main.o
gcc -c red.c -o red.o
gcc -c green.c -o green.o
gcc -c blue.c -o blue.o
gcc main.o red.o green.o blue.o -o app
exit 0Show solution
MAKEFLAGS += --no-builtin-rules
SRCS := main.c red.c green.c blue.c
OBJS := $(SRCS:.c=.o)
app: $(OBJS)
gcc $^ -o $@
%.o: %.c
gcc -c lt; -o $@$(patsubst %.c,%.o,$(SRCS)) works too.
Exercise 3: Stop the endless rebuild
Topics: Phony Targets & Order-only Prerequisites, Out-of-Tree Builds
This out-of-tree build recompiles on every run, even with no changes. Make the second make print make: 'out/app' is up to date. without giving up the rule that creates out/.
mkdir -p ex3 && cd ex3
printf 'int main(void) { return 0; }\n' > main.c
printf 'int part(void) { return 0; }\n' > part.c
cat > Makefile <<'MK'
out/app: out/main.o out/part.o
gcc out/main.o out/part.o -o $@
out/%.o: %.c out
gcc -c lt; -o $@
out:
mkdir -p out
MK
make -j1 >/dev/null
make -j1gcc -c main.c -o out/main.o
gcc -c part.c -o out/part.o
gcc out/main.o out/part.o -o out/app
Expected output:
make: 'out/app' is up to date.Show solution
Make the directory an order-only prerequisite, so its changing time stamp no longer counts:
out/%.o: %.c | out
gcc -c lt; -o $@Exercise 4: Complete a build.ninja
Topics: Rules, Build Statements & Variables, Header Dependencies in Ninja
The rules are written; add the three build statements (two objects, one program called hello) and a default, so that ninja builds the program and editing msg.h rebuilds only main.o and the link.
mkdir -p ex4 && cd ex4
printf '#define MSG "hi"\n' > msg.h
printf 'const char *msg(void) { return "hi"; }\n' > msg.c
printf '#include <stdio.h>\n#include "msg.h"\nconst char *msg(void);\nint main(void) { printf("%%s %%s\\n", msg(), MSG); return 0; }\n' > main.c
cat > build.ninja <<'NJ'
rule cc
command = gcc -MMD -MF $out.d -c $in -o $out
depfile = $out.d
deps = gcc
description = CC $out
rule link
command = gcc $in -o $out
description = LINK $out
# TODO: build statements for main.o, msg.o and hello, and a default
NJ
ninja -j1ninja: no work to do.
Expected output (run ninja -j1, then sleep 1 && touch msg.h && ninja -j1):
[1/3] CC main.o
[2/3] CC msg.o
[3/3] LINK hello
[1/2] CC main.o
[2/2] LINK helloShow solution
build main.o: cc main.c
build msg.o: cc msg.c
build hello: link main.o msg.o
default hellomsg.c doesn't include msg.h, so the deps log ties the header only to main.o.
Exercise 5: Build order with cycle detection
Topics: Model: A Mini Make
Write buildOrder(graph, goal): return the list of targets in an order where every target comes after its prerequisites (depth-first, prerequisites in listed order, each target once), or throw Error('cycle: a -> b -> a') when the graph has a cycle reachable from goal.
function buildOrder(graph, goal) {
// TODO: depth-first walk; track the current path to detect cycles
return [];
}
const g = { app: ['main.o', 'lib.a'], 'main.o': ['main.c'], 'lib.a': ['x.o', 'y.o'], 'x.o': ['x.c'], 'y.o': ['y.c'] };
console.log(buildOrder(g, 'app').join(' '));
console.log(buildOrder(g, 'lib.a').join(' '));
try {
buildOrder({ a: ['b'], b: ['c'], c: ['a'] }, 'a');
console.log('no error?');
} catch (e) { console.log(e.message); }
no error?
Expected output:
main.c main.o x.c x.o y.c y.o lib.a app
x.c x.o y.c y.o lib.a
cycle: a -> b -> c -> aShow solution
function buildOrder(graph, goal) {
const order = [], done = new Set();
const visit = (t, path) => {
if (path.includes(t)) throw new Error('cycle: ' + [...path.slice(path.indexOf(t)), t].join(' -> '));
if (done.has(t)) return;
for (const p of graph[t] ?? []) visit(p, [...path, t]);
done.add(t);
order.push(t);
};
visit(goal, []);
return order;
}Exercise 6: Ninja's dirty check
Topics: The Build Log & -d explain
Write dirtyReason(edge, mtime, log) that returns why Ninja would rebuild an edge, or null if it's clean. Check in this order: the output doesn't exist; the output is older than its newest input; the command differs from the one recorded in the log (or there's no log entry).
function dirtyReason(edge, mtime, log) {
// TODO: edge = { out, ins, command }, mtime = { file: time }, log = { out: command }
return null;
}
const mtime = { 'a.c': 10, 'a.o': 20, 'b.c': 30, 'b.o': 25, 'c.c': 5, 'c.o': 6 };
const log = { 'a.o': 'gcc -O2 -c a.c', 'b.o': 'gcc -O2 -c b.c', 'c.o': 'gcc -O2 -c c.c' };
const edges = [
{ out: 'a.o', ins: ['a.c'], command: 'gcc -O2 -c a.c' },
{ out: 'b.o', ins: ['b.c'], command: 'gcc -O2 -c b.c' },
{ out: 'c.o', ins: ['c.c'], command: 'gcc -O0 -g -c c.c' },
{ out: 'd.o', ins: ['d.c'], command: 'gcc -O2 -c d.c' },
];
for (const e of edges) console.log(e.out, '->', dirtyReason(e, mtime, log) ?? 'clean');a.o -> clean
b.o -> clean
c.o -> clean
d.o -> clean
Expected output:
a.o -> clean
b.o -> output b.o older than most recent input b.c
c.o -> command line changed for c.o
d.o -> output d.o doesn't existShow solution
function dirtyReason(edge, mtime, log) {
if (!(edge.out in mtime)) return `output ${edge.out} doesn't exist`;
const newest = edge.ins.reduce((a, b) => (mtime[b] > (mtime[a] ?? -1) ? b : a), edge.ins[0]);
if (mtime[newest] > mtime[edge.out]) return `output ${edge.out} older than most recent input ${newest}`;
if (log[edge.out] !== edge.command) return `command line changed for ${edge.out}`;
return null;
}Test yourself
In Exercise 3, why does out/%.o: %.c out rebuild every time?
outis phony- Creating files in
out/updates the directory's time stamp, which makes the objects look older than a prerequisite - The pattern is wrong
- gcc is too slow
In Exercise 4, why does touching msg.h not rebuild msg.o?
- Ninja ignores headers
msg.cdoesn't includemsg.h, so its deps log entry doesn't list itdefaultexcludes it- The
linkrule has no depfile