TExcelTAD
Home › GNU Make & Ninja › Rules, Build Statements & Variables

Rules, Build Statements & Variables

Ninja's whole language fits on one page. This lesson covers all of it that you'll meet in generated files.

The pieces

ninja
ninja_required_version = 1.10      # top-level variable (this one is checked by Ninja)
cflags = -O2                       # top-level variable

rule cc                            # a named command template
  command = gcc $cflags -c $in -o $out
  description = CC $out

build out.o: cc in.c | gen.h || stamp
#     ^outputs ^rule ^explicit ^implicit ^order-only inputs
  cflags = -O0 -g                  # build-level variable: overrides for this edge only

build all: phony out.o             # a name for a group of outputs
default all                        # what plain `ninja` builds
Syntax Meaning
build OUT: RULE IN explicit inputs: appear in $in, and changes trigger a rebuild
… | IMPLICIT implicit inputs: trigger a rebuild but are not in $in (a script the rule runs, a generated header)
… || ORDER order-only inputs: must be built first, never trigger a rebuild (like Make's |)
build OUT | EXTRA: … implicit outputs: also produced by the command, not in $out (an import library, a .d file)
phony built-in rule that does nothing: an alias, or a way to say "this file may not exist"
default T… the targets plain ninja builds
include file / subninja file read another file; subninja gives it its own variable scope
pool NAME + depth = N limit how many commands of some rules run at once; the built-in console pool (depth 1) gives a command direct terminal access

Indentation is with spaces (any number), and only variable bindings may be indented. Special characters are escaped with $: $ is a dollar sign, $ a space in a path, $: a colon, and a $ at the end of a line continues it.

Variable scoping

Variables are looked up from the narrowest scope outwards: the build statement, then the rule, then the file (top level). Rule variables are expanded late, in the context of each build statement, so a build statement can override a variable that the rule's command uses:

bash · try it yourself
mkdir -p scope && cd scope
for f in fast safe main; do printf 'int %s_f(void) { return 0; }\n' $f > $f.c; done
sed -i 's/int main_f(void)/int main(void)/' main.c
cat > build.ninja <<'NJ'
cflags = -O2

rule cc
  command = gcc $cflags -c $in -o $out
  description = CC $out [$cflags]

rule link
  command = gcc $in -o $out
  description = LINK $out

build fast.o: cc fast.c
  cflags = -O3 -funroll-loops
build safe.o: cc safe.c
  cflags = $cflags -fstack-protector-strong
build main.o: cc main.c
build app: link main.o fast.o safe.o
NJ
ninja -j1
[1/4] CC fast.o [-O3 -funroll-loops]
[2/4] CC safe.o [-O2 -fstack-protector-strong]
[3/4] CC main.o [-O2]
[4/4] LINK app

safe.o extended the outer value with $cflags on its right-hand side; fast.o replaced it. Ninja started with fast.o because it was the first build statement whose inputs were ready; the order of independent statements is up to the scheduler.

Implicit inputs, phony and default

A common need: a code generator script produces a source file. If the script changes, the output must be regenerated, but the script shouldn't appear in $in. That's an implicit input:

bash · try it yourself
mkdir -p gen && cd gen
cat > mktable.sh <<'SH'
#!/bin/sh
echo "int table[] = { $(seq -s ', ' 1 $1) };"
SH
chmod +x mktable.sh
printf '10\n' > size.txt
printf '#include <stdio.h>\nextern int table[];\nint main(void) { printf("last = %%d\\n", table[9]); return 0; }\n' > main.c
cat > build.ninja <<'NJ'
rule gen
  command = ./mktable.sh $(cat $in) > $out
  description = GEN $out
rule cc
  command = gcc -c $in -o $out
  description = CC $out
rule link
  command = gcc $in -o $out
  description = LINK $out

build table.c: gen size.txt | mktable.sh
build table.o: cc table.c
build main.o: cc main.c
build app: link main.o table.o
build tidy: phony app
default tidy
NJ
ninja -j1 && ./app
echo "--- the script changed:"
sleep 1 && touch mktable.sh
ninja -j1
echo "--- targets by name:"
ninja -j1 main.o
ninja -t targets all | sort
[1/4] GEN table.c
[2/4] CC table.o
[3/4] CC main.o
[4/4] LINK app
last = 10
--- the script changed:
[1/3] GEN table.c
[2/3] CC table.o
[3/3] LINK app
--- targets by name:
ninja: no work to do.
app: link
main.o: cc
table.c: gen
table.o: cc
tidy: phony

Two details: $(cat $in) reaches the shell as $(cat size.txt), because $ is Ninja's escape for $. On Unix Ninja runs every command with /bin/sh -c, which is why redirection (>) and $(…) work here; on Windows it starts the program directly, so shell syntax there needs an explicit cmd /c.

Pools: limiting expensive steps

Linking a big C++ program can use gigabytes of memory, and running 32 links at once can exhaust a machine that compiles fine with -j32. A pool caps a group of commands without slowing the rest:

ninja
pool link_pool
  depth = 2

rule link
  command = g++ $in -o $out
  pool = link_pool          # at most 2 links at once, whatever -j says

CMake exposes this as the JOB_POOLS property; the built-in console pool (depth 1) lets a long-running command such as a test runner print straight to the terminal.

Mistakes Ninja reports

Ninja's parser is strict and its errors point at the exact spot:

bash · try it yourself
mkdir -p broken && cd broken
printf 'rule cc\n  command = gcc -c $in -o $out\nbuild a.o: cc a.c\nbuild a.o: cc b.c\n' > build.ninja
ninja -j1
echo "exit status: $?"
printf 'build a.o: compile a.c\n' > build.ninja
ninja -j1
printf 'rule cp\n  command = cp $in $out\nbuild a: cp b\nbuild b: cp a\n' > build.ninja
ninja -j1
ninja -j1 a
ninja: error: build.ninja:5: multiple rules generate a.o

exit status: 1
ninja: error: build.ninja:1: unknown build rule 'compile'
build a.o: compile a.c
           ^ near here
ninja: error: could not determine root nodes of build graph
ninja: error: dependency cycle: a -> b -> a

Each output may be produced by exactly one build statement, every rule must be defined before use, and cycles are errors, not warnings. The cycle shows up twice: a plain ninja can't even find a starting point (every node is an input of another, so there are no roots), and asking for a names the loop.

Test yourself

In build gen.c: gen spec.txt | tool.py, what is $in for the gen rule?

  1. spec.txt tool.py
  2. spec.txt
  3. tool.py
  4. empty

A rule's command uses $cflags. A build statement sets cflags = -O0. Which value is used for that statement?

  1. The top-level value
  2. -O0, because build-statement variables shadow rule and file variables
  3. Both, concatenated
  4. Ninja reports an error

What does pool = link_pool with depth = 2 do?

  1. Runs links twice
  2. Allows at most two commands from that pool at once, independent of -j
  3. Pins links to two CPU cores
  4. Disables parallelism