Mini Project: One Project, Two Build Files
Time to put the course together. You'll build calc, a small multi-directory C project (a static library, a command-line program and a test program) twice: first with a non-recursive Makefile that has automatic header dependencies, an out-of-tree build directory, debug and release configurations, a test target and an install target honouring PREFIX and DESTDIR; then with an equivalent hand-written build.ninja. Both builds below were run for real.
The project
calc/
├── include/calc/calc.h public API, installed
├── lib/calc/internal.h private header of the library
├── lib/calc/ops.c calc_add, calc_mul
├── lib/calc/eval.c calc_eval("2+3*4")
├── app/main.c the calc program
├── tests/test_calc.c a tiny test program
├── Makefile top level (part 1)
├── lib/calc/module.mk one fragment per directory (part 1)
├── app/module.mk
├── tests/module.mk
└── build.ninja the Ninja version (part 2)| Requirement | Make | Ninja |
|---|---|---|
| one dependency graph for all directories | include of module.mk fragments |
a single file |
| header dependencies | -MMD -MP + -include $(ALL_OBJS:.o=.d) |
depfile + deps = gcc |
| out-of-tree | build/$(CONFIG)/… mirrors the source tree |
builddir = build/ninja |
| configurations | CONFIG=release / CONFIG=debug |
one file per configuration (generators write one per build directory) |
| tests | phony test, runs every time |
tests.passed stamp, re-runs only when the test binary changes |
| install | PREFIX, DESTDIR (command-line variables) |
prefix variable, $DESTDIR from the environment |
Both sessions below start by creating the same sources with heredocs; the build files follow after them.
Part 1: the non-recursive Makefile
The top-level Makefile sets the configuration, includes one fragment per directory, and owns the single pattern rule that compiles any .c into $(BUILD)/….o. Each fragment only adds targets and appends its objects to ALL_OBJS, so the dependency files of every directory are included. Variable names carry the directory's prefix (LIB_, APP_, TEST_) because all fragments share one namespace.
mkdir -p calc/include/calc calc/lib/calc calc/app calc/tests && cd calc
cat > include/calc/calc.h <<'SRC'
#ifndef CALC_H
#define CALC_H
/* Evaluates "2+3*4" (non-negative integers, + and *). Returns 0 on success. */
int calc_eval(const char *expr, int *result);
#endif
SRC
cat > lib/calc/internal.h <<'SRC'
int calc_add(int a, int b);
int calc_mul(int a, int b);
SRC
cat > lib/calc/ops.c <<'SRC'
#include "internal.h"
int calc_add(int a, int b) { return a + b; }
int calc_mul(int a, int b) { return a * b; }
SRC
cat > lib/calc/eval.c <<'SRC'
#include "calc/calc.h"
#include "internal.h"
int calc_eval(const char *s, int *out) {
int sum = 0, prod = 1, num = 0, have = 0;
for (;; s++) {
if (*s >= '0' && *s <= '9') { num = num * 10 + (*s - '0'); have = 1; continue; }
if (!have) return -1;
prod = calc_mul(prod, num); num = 0; have = 0;
if (*s == '*') continue;
sum = calc_add(sum, prod); prod = 1;
if (*s == '+') continue;
if (*s == '\0') { *out = sum; return 0; }
return -1;
}
}
SRC
cat > app/main.c <<'SRC'
#include <stdio.h>
#include "calc/calc.h"
int main(int argc, char **argv) {
const char *expr = argc > 1 ? argv[1] : "1+2*3";
int r;
if (calc_eval(expr, &r) != 0) { fprintf(stderr, "bad expression: %s\n", expr); return 1; }
printf("%s = %d\n", expr, r);
return 0;
}
SRC
cat > tests/test_calc.c <<'SRC'
#include <stdio.h>
#include "calc/calc.h"
static int failures, count;
static void check(const char *e, int want_rc, int want) {
int r = 0, rc = calc_eval(e, &r);
count++;
if (rc != want_rc || (rc == 0 && r != want)) { printf("FAIL %s\n", e); failures++; }
}
int main(void) {
check("7", 0, 7); check("2+3*4", 0, 14); check("10*10+1", 0, 101); check("2+", -1, 0);
printf("%d/%d tests passed\n", count - failures, count);
return failures != 0;
}
SRC
cat > Makefile <<'MK'
# calc: non-recursive build. make [CONFIG=release|debug] [all|test|install|clean]
SHELL := /bin/bash
.DELETE_ON_ERROR:
MAKEFLAGS += --no-builtin-rules
.SUFFIXES:
CONFIG ?= release
BUILD := build/$(CONFIG)
PREFIX ?= /usr/local
DESTDIR ?=
CC := gcc
CPPFLAGS := -Iinclude
ifeq ($(CONFIG),release)
CFLAGS := -O2 -DNDEBUG
else ifeq ($(CONFIG),debug)
CFLAGS := -O0 -g
else
$(error CONFIG must be release or debug, not '$(CONFIG)')
endif
CFLAGS += -Wall -Wextra -std=c17
.PHONY: all test install clean
all:
ALL_OBJS :=
include lib/calc/module.mk app/module.mk tests/module.mk
$(BUILD)/%.o: %.c
@mkdir -p $(@D)
$(CC) $(CPPFLAGS) $(CFLAGS) -MMD -MP -c lt; -o $@
-include $(ALL_OBJS:.o=.d)
install: all
install -D -m 755 $(APP) "$(DESTDIR)$(PREFIX)/bin/calc"
install -D -m 644 $(LIB) "$(DESTDIR)$(PREFIX)/lib/libcalc.a"
install -D -m 644 include/calc/calc.h "$(DESTDIR)$(PREFIX)/include/calc/calc.h"
clean:
rm -rf build
MK
cat > lib/calc/module.mk <<'MK'
LIB := $(BUILD)/lib/libcalc.a
LIB_OBJS := $(BUILD)/lib/calc/ops.o $(BUILD)/lib/calc/eval.o
ALL_OBJS += $(LIB_OBJS)
$(LIB): $(LIB_OBJS)
rm -f $@ && ar rcs $@ $^
MK
cat > app/module.mk <<'MK'
APP := $(BUILD)/bin/calc
APP_OBJS := $(BUILD)/app/main.o
ALL_OBJS += $(APP_OBJS)
all: $(APP)
$(APP): $(APP_OBJS) $(LIB)
@mkdir -p $(@D)
$(CC) $^ -o $@
MK
cat > tests/module.mk <<'MK'
TEST := $(BUILD)/bin/test_calc
TEST_OBJS := $(BUILD)/tests/test_calc.o
ALL_OBJS += $(TEST_OBJS)
$(TEST): $(TEST_OBJS) $(LIB)
@mkdir -p $(@D)
$(CC) $^ -o $@
test: $(TEST)
$(TEST)
MK
make -j1
build/release/bin/calc '2+3*4'
make -j1 test
echo "--- no-op:"; make -j1
echo "--- touch the private header:"
sleep 1 && touch lib/calc/internal.h
make -j1
echo "--- touch the public header:"
sleep 1 && touch include/calc/calc.h
make -j1 test
echo "--- install:"
make -j1 install PREFIX=/usr DESTDIR=$PWD/stage >/dev/null
find stage -type f | sort
find build -type f -name '*.d' | sortgcc -Iinclude -O2 -DNDEBUG -Wall -Wextra -std=c17 -MMD -MP -c app/main.c -o build/release/app/main.o
gcc -Iinclude -O2 -DNDEBUG -Wall -Wextra -std=c17 -MMD -MP -c lib/calc/ops.c -o build/release/lib/calc/ops.o
gcc -Iinclude -O2 -DNDEBUG -Wall -Wextra -std=c17 -MMD -MP -c lib/calc/eval.c -o build/release/lib/calc/eval.o
rm -f build/release/lib/libcalc.a && ar rcs build/release/lib/libcalc.a build/release/lib/calc/ops.o build/release/lib/calc/eval.o
gcc build/release/app/main.o build/release/lib/libcalc.a -o build/release/bin/calc
2+3*4 = 14
gcc -Iinclude -O2 -DNDEBUG -Wall -Wextra -std=c17 -MMD -MP -c tests/test_calc.c -o build/release/tests/test_calc.o
gcc build/release/tests/test_calc.o build/release/lib/libcalc.a -o build/release/bin/test_calc
build/release/bin/test_calc
4/4 tests passed
--- no-op:
make: Nothing to be done for 'all'.
--- touch the private header:
gcc -Iinclude -O2 -DNDEBUG -Wall -Wextra -std=c17 -MMD -MP -c lib/calc/ops.c -o build/release/lib/calc/ops.o
gcc -Iinclude -O2 -DNDEBUG -Wall -Wextra -std=c17 -MMD -MP -c lib/calc/eval.c -o build/release/lib/calc/eval.o
rm -f build/release/lib/libcalc.a && ar rcs build/release/lib/libcalc.a build/release/lib/calc/ops.o build/release/lib/calc/eval.o
gcc build/release/app/main.o build/release/lib/libcalc.a -o build/release/bin/calc
--- touch the public header:
gcc -Iinclude -O2 -DNDEBUG -Wall -Wextra -std=c17 -MMD -MP -c tests/test_calc.c -o build/release/tests/test_calc.o
gcc -Iinclude -O2 -DNDEBUG -Wall -Wextra -std=c17 -MMD -MP -c lib/calc/eval.c -o build/release/lib/calc/eval.o
rm -f build/release/lib/libcalc.a && ar rcs build/release/lib/libcalc.a build/release/lib/calc/ops.o build/release/lib/calc/eval.o
gcc build/release/tests/test_calc.o build/release/lib/libcalc.a -o build/release/bin/test_calc
build/release/bin/test_calc
4/4 tests passed
--- install:
stage/usr/bin/calc
stage/usr/include/calc/calc.h
stage/usr/lib/libcalc.a
build/release/app/main.d
build/release/lib/calc/eval.d
build/release/lib/calc/ops.d
build/release/tests/test_calc.d
Check the result against the requirements:
- No-op build:
Nothing to be done for 'all', with one Make process reading four small files. - Private header: touching
lib/calc/internal.hrebuilt the two library objects, the archive and the program, and notmain.o(which only includes the public header). The test program wasn't rebuilt because nothing asked for it. - Public header:
make testrebuilt exactly the objects that includecalc/calc.hand are needed by the tests (test_calc.o,eval.o);main.owaits until something needs the program. - Install: three files staged under
stage/usr, ready to be packaged;.dfiles sit next to their objects inbuild/release/.
Try make CONFIG=debug next: it builds into build/debug/ without touching the release objects (Out-of-Tree Builds). make CONFIG=fast stops with the $(error) message.
Part 2: the same build in build.ninja
The Ninja version spells out every edge. It needs no mkdir: Ninja creates the parent directories of every output before running a command. builddir is a special variable: Ninja puts .ninja_log and .ninja_deps there instead of next to build.ninja. Ninja has no command-line variables, so DESTDIR comes from the environment ($DESTDIR reaches the shell as $DESTDIR).
mkdir -p calc/include/calc calc/lib/calc calc/app calc/tests && cd calc
cat > include/calc/calc.h <<'SRC'
#ifndef CALC_H
#define CALC_H
/* Evaluates "2+3*4" (non-negative integers, + and *). Returns 0 on success. */
int calc_eval(const char *expr, int *result);
#endif
SRC
cat > lib/calc/internal.h <<'SRC'
int calc_add(int a, int b);
int calc_mul(int a, int b);
SRC
cat > lib/calc/ops.c <<'SRC'
#include "internal.h"
int calc_add(int a, int b) { return a + b; }
int calc_mul(int a, int b) { return a * b; }
SRC
cat > lib/calc/eval.c <<'SRC'
#include "calc/calc.h"
#include "internal.h"
int calc_eval(const char *s, int *out) {
int sum = 0, prod = 1, num = 0, have = 0;
for (;; s++) {
if (*s >= '0' && *s <= '9') { num = num * 10 + (*s - '0'); have = 1; continue; }
if (!have) return -1;
prod = calc_mul(prod, num); num = 0; have = 0;
if (*s == '*') continue;
sum = calc_add(sum, prod); prod = 1;
if (*s == '+') continue;
if (*s == '\0') { *out = sum; return 0; }
return -1;
}
}
SRC
cat > app/main.c <<'SRC'
#include <stdio.h>
#include "calc/calc.h"
int main(int argc, char **argv) {
const char *expr = argc > 1 ? argv[1] : "1+2*3";
int r;
if (calc_eval(expr, &r) != 0) { fprintf(stderr, "bad expression: %s\n", expr); return 1; }
printf("%s = %d\n", expr, r);
return 0;
}
SRC
cat > tests/test_calc.c <<'SRC'
#include <stdio.h>
#include "calc/calc.h"
static int failures, count;
static void check(const char *e, int want_rc, int want) {
int r = 0, rc = calc_eval(e, &r);
count++;
if (rc != want_rc || (rc == 0 && r != want)) { printf("FAIL %s\n", e); failures++; }
}
int main(void) {
check("7", 0, 7); check("2+3*4", 0, 14); check("10*10+1", 0, 101); check("2+", -1, 0);
printf("%d/%d tests passed\n", count - failures, count);
return failures != 0;
}
SRC
cat > build.ninja <<'NJ'
# calc: hand-written equivalent of the Makefile's release configuration
ninja_required_version = 1.10
builddir = build/ninja
cppflags = -Iinclude
cflags = -O2 -DNDEBUG -Wall -Wextra -std=c17
prefix = /usr/local
rule cc
command = gcc $cppflags $cflags -MMD -MF $out.d -c $in -o $out
depfile = $out.d
deps = gcc
description = CC $out
rule ar
command = rm -f $out && ar rcs $out $in
description = AR $out
rule link
command = gcc $in -o $out
description = LINK $out
rule run_test
command = ./$in && touch $out
description = TEST $in
rule install
command = install -D -m 755 $builddir/bin/calc "$DESTDIR$prefix/bin/calc" && $
install -D -m 644 $builddir/lib/libcalc.a "$DESTDIR$prefix/lib/libcalc.a" && $
install -D -m 644 include/calc/calc.h "$DESTDIR$prefix/include/calc/calc.h"
description = INSTALL to $prefix (plus $DESTDIR)
build $builddir/lib/calc/ops.o: cc lib/calc/ops.c
build $builddir/lib/calc/eval.o: cc lib/calc/eval.c
build $builddir/app/main.o: cc app/main.c
build $builddir/tests/test_calc.o: cc tests/test_calc.c
build $builddir/lib/libcalc.a: ar $builddir/lib/calc/ops.o $builddir/lib/calc/eval.o
build $builddir/bin/calc: link $builddir/app/main.o $builddir/lib/libcalc.a
build $builddir/bin/test_calc: link $builddir/tests/test_calc.o $builddir/lib/libcalc.a
build $builddir/tests.passed: run_test $builddir/bin/test_calc
build all: phony $builddir/bin/calc
build test: phony $builddir/tests.passed
build install: install | all
default all
NJ
ninja -j1
build/ninja/bin/calc '2+3*4'
ninja -j1 test
ninja -j1 test
echo "--- touch the private header:"
sleep 1 && touch lib/calc/internal.h
ninja -j1 test
echo "--- install:"
DESTDIR=$PWD/stage ninja -j1 install
find stage -type f | sort
ls -A build/ninja
ninja -t targets depth 1 | sort[1/5] CC build/ninja/lib/calc/ops.o
[2/5] CC build/ninja/lib/calc/eval.o
[3/5] CC build/ninja/app/main.o
[4/5] AR build/ninja/lib/libcalc.a
[5/5] LINK build/ninja/bin/calc
2+3*4 = 14
[1/3] CC build/ninja/tests/test_calc.o
[2/3] LINK build/ninja/bin/test_calc
[3/3] TEST build/ninja/bin/test_calc
4/4 tests passed
ninja: no work to do.
--- touch the private header:
[1/5] CC build/ninja/lib/calc/ops.o
[2/5] CC build/ninja/lib/calc/eval.o
[3/5] AR build/ninja/lib/libcalc.a
[4/5] LINK build/ninja/bin/test_calc
[5/5] TEST build/ninja/bin/test_calc
4/4 tests passed
--- install:
[1/2] LINK build/ninja/bin/calc
[2/2] INSTALL to /usr/local (plus $DESTDIR)
stage/usr/local/bin/calc
stage/usr/local/include/calc/calc.h
stage/usr/local/lib/libcalc.a
.ninja_deps
.ninja_log
app
bin
lib
tests
tests.passed
install: install
test: phony
Differences worth noticing:
- Tests as a stamp file:
tests.passedis touched only when the test program succeeds, soninja testis a no-op until the library or the tests change. Make's phonytestruns the tests every time. (If the tests fail, the stamp isn't written and they run again next time.) - Touching the private header rebuilt the library and, because we asked for
test, relinked and re-ran the tests;bin/calcwas relinked only later, byinstall, which needsall. installis an edge whose output never exists, so it always runs, after its order-only inputallis up to date.ninja -t targets depth 1lists the roots:installandtest(allisn't a root becauseinstalluses it).
Extensions
- Add a
debugconfiguration to the Ninja version: a second filedebug.ninjawith othercflagsandbuilddir, built withninja -f debug.ninja. That's how generators handle configurations: one build directory, onebuild.ninjaeach. - Generate
build.ninjafrom a 30-line Python or shell script that globslib/**/*.c, then compare it with the hand-written one. - Add a
compile_commands.json:ninja -t compdb ccfor Ninja, the script from Toolkit: compile_commands.json & Editors for Make. - Rewrite the project in CMake (
add_library,add_executable,install()) and compare its generatedbuild.ninjawith yours. The Modern CMake course starts exactly there.
Test yourself
Why does each module.mk prefix its variables (LIB_OBJS, APP_OBJS)?
- Make requires it
- All fragments are included into one Make process and share one variable namespace
- To speed up parsing
- Because of
-MMD
Why does the Ninja version have no mkdir -p anywhere?
- Ninja creates the parent directories of outputs automatically
- gcc creates them
builddircreates all directories- The directories are committed to git
How does the Ninja build get DESTDIR, given that Ninja has no command-line variables?
ninja DESTDIR=...- From the environment: the command uses
$DESTDIR, which the shell expands - From
.ninja_log - It can't