TExcelTAD
Home › GNU Make & Ninja › Make & Ninja Exercises

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.

bash · try it yourself
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 && ./app
Makefile: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:

text
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=5
Show 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):

make
app: main.o
	gcc main.o -o app
main.o: main.c limits.h
	gcc -c main.c -o main.o

Exercise 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.

bash · try it yourself
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:

text
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 0
Show solution
make
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/.

bash · try it yourself
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 -j1
gcc -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:

text
make: 'out/app' is up to date.
Show solution

Make the directory an order-only prerequisite, so its changing time stamp no longer counts:

make
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.

bash · try it yourself
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 -j1
ninja: no work to do.

Expected output (run ninja -j1, then sleep 1 && touch msg.h && ninja -j1):

text
[1/3] CC main.o
[2/3] CC msg.o
[3/3] LINK hello
[1/2] CC main.o
[2/2] LINK hello
Show solution
ninja
build main.o: cc main.c
build msg.o: cc msg.c
build hello: link main.o msg.o
default hello

msg.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.

js · try it yourself
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:

text
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 -> a
Show solution
js
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).

js · try it yourself
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:

text
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 exist
Show solution
js
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?

  1. out is phony
  2. Creating files in out/ updates the directory's time stamp, which makes the objects look older than a prerequisite
  3. The pattern is wrong
  4. gcc is too slow

In Exercise 4, why does touching msg.h not rebuild msg.o?

  1. Ninja ignores headers
  2. msg.c doesn't include msg.h, so its deps log entry doesn't list it
  3. default excludes it
  4. The link rule has no depfile