3 Evan Martin <martine@danga.com>
9 Ninja is yet another build system. It takes as input the
10 interdependencies of files (typically source code and output
11 executables) and orchestrates building them, _quickly_.
13 Ninja joins a sea of other build systems. Its distinguishing goal is
14 to be fast. It is born from
15 http://neugierig.org/software/chromium/notes/2011/02/ninja.html[my
16 work on the Chromium browser project], which has over 30,000 source
17 files and whose other build systems (including one built from custom
18 non-recursive Makefiles) can take ten seconds to start building after
19 changing one file. Ninja is under a second.
21 Philosophical overview
22 ~~~~~~~~~~~~~~~~~~~~~~
24 Where other build systems are high-level languages, Ninja aims to be
27 Build systems get slow when they need to make decisions. When you are
28 in a edit-compile cycle you want it to be as fast as possible -- you
29 want the build system to do the minimum work necessary to figure out
30 what needs to be built immediately.
32 Ninja contains the barest functionality necessary to describe
33 arbitrary dependency graphs. Its lack of syntax makes it impossible
34 to express complex decisions.
36 Instead, Ninja is intended to be used with a separate program
37 generating its input files. The generator program (like the
38 `./configure` found in autotools projects) can analyze system
39 dependencies and make as many decisions as possible up front so that
40 incremental builds stay fast. Going beyond autotools, even build-time
41 decisions like "which compiler flags should I use?" or "should I
42 build a debug or release-mode binary?" belong in the `.ninja` file
48 Here are the design goals of Ninja:
50 * very fast (i.e., instant) incremental builds, even for very large
53 * very little policy about how code is built; "explicit is better than
56 * get dependencies correct, and in particular situations that are
57 difficult to get right with Makefiles (e.g. outputs need an implicit
58 dependency on the command line used to generate them; to build C
59 source code you need to use gcc's `-M` flags for header
62 * when convenience and speed are in conflict, prefer speed.
64 Some explicit _non-goals_:
66 * convenient syntax for writing build files by hand. _You should
67 generate your ninja files using another program_. This is how we
68 can sidestep many policy decisions.
70 * built-in rules. _Out of the box, Ninja has no rules for
71 e.g. compiling C code._
73 * build-time customization of the build. _Options belong in
74 the program that generates the ninja files_.
76 * build-time decision-making ability such as conditionals or search
77 paths. _Making decisions is slow._
79 To restate, Ninja is faster than other build systems because it is
80 painfully simple. You must tell Ninja exactly what to do when you
81 create your project's `.ninja` files.
86 Ninja is closest in spirit and functionality to make, relying on
87 simple dependencies between file timestamps.
89 But fundamentally, make has a lot of _features_: suffix rules,
90 functions, built-in rules that e.g. search for RCS files when building
91 source. Make's language was designed to be written by humans. Many
92 projects find make alone adequate for their build problems.
94 In contrast, Ninja has almost no features; just those necessary to get
95 builds correct while punting most complexity to generation of the
96 ninja input files. Ninja by itself is unlikely to be useful for most
99 Here are some of the features Ninja adds to make. (These sorts of
100 features can often be implemented using more complicated Makefiles,
101 but they are not part of make itself.)
103 * A Ninja rule may point at a path for extra implicit dependency
104 information. This makes it easy to get header dependencies correct
107 * A build edge may have multiple outputs.
109 * Outputs implicitly depend on the command line that was used to generate
110 them, which means that changing e.g. compilation flags will cause
111 the outputs to rebuild.
113 * Output directories are always implicitly created before running the
114 command that relies on them.
116 * Rules can provide shorter descriptions of the command being run, so
117 you can print e.g. `CC foo.o` instead of a long command line while
120 * Builds are always run in parallel, based by defaulton the number of
121 CPUs your system has. Underspecified build dependencies will result
124 * Command output is always buffered. This means commands running in
125 parallel don't interleave their output, and when a command fails we
126 can print its failure output next to the full command line that
127 produced the failure.
130 Using Ninja for your project
131 ----------------------------
133 If your project is small, Ninja's speed impact is likely unnoticable.
134 Some build timing numbers are included below. (However, even for
135 small projects it sometimes turns out that Ninja's limited syntax
136 forces simpler build rules that result in faster builds.) Another way
137 to say this is that if you're happy with the edit-compile cycle time
138 of your project already then Ninja won't help.
140 There are many other build systems that are more user-friendly or
141 featureful than Ninja itself. For some recomendations: the Ninja
142 author found http://gittup.org/tup/[the tup build system] influential
143 in Ninja's design, and thinks https://github.com/apenwarr/redo[redo]'s
144 design is quite clever.
146 Ninja's benefit comes from using it in conjunction with a smarter
149 http://code.google.com/p/gyp/[gyp]:: The meta-build system used to
150 generate build files for Google Chrome. gyp can generate Ninja files
151 for Linux and Mac and is used by many Chrome developers. See the
152 http://code.google.com/p/chromium/wiki/NinjaBuild[Chromium Ninja
153 documentation for more details]. gyp is relatively unpopular outside
154 of the Chrome and v8 world.
156 * For Chrome (~30k source files), Ninja reduced no-op builds from
157 around 15 seconds to under one second.
158 * https://plus.google.com/108996039294665965197/posts/SfhrFAhRyyd[A
159 Mozilla developer compares build systems]: "While chromium's full
160 build is 2.15x slower than firefox's, a nop build is 78.2x faster!
161 That is really noticeable during development. No incremental build
162 of firefox can be faster than 57.9s, which means that in practice
163 almost all of them will be over a minute."
165 http://www.cmake.org/[CMake]:: A widely used meta-build system that
166 can generate Ninja files as of version 2.8.8.
168 * For building Blender, one user reported "Single file rebuild is 0.97
169 sec, same on makefiles was 3.7sec."
170 * For building LLVM on Windows, one user reported no-op build times:
171 "ninja: 0.4s / MSBuild: 11s / jom: 53s".
173 others:: Ninja ought to fit perfectly into other meta-build software
174 like http://industriousone.com/premake[premake]. If you do this work,
181 Run `ninja`. By default, it looks for a file named `build.ninja` in
182 the current directory and builds all out-of-date targets. You can
183 specify which targets (files) to build as command line arguments.
185 `ninja -h` prints help output. Many of Ninja's flags intentionally
186 match those of Make; e.g `ninja -C build -j 20` changes into the
187 `build` directory and runs 20 build commands in parallel. (Note that
188 Ninja defaults to running commands in parallel anyway, so typically
189 you don't need to pass `-j`.)
192 Environment variables
193 ~~~~~~~~~~~~~~~~~~~~~
195 Ninja supports one environment variable to control its behavior.
197 `NINJA_STATUS`:: The progress status printed before the rule being run.
198 Several placeholders are available:
199 * `%s`: The number of started edges.
200 * `%t`: The total number of edges that must be run to complete the build.
201 * `%r`: The number of currently running edges.
202 * `%u`: The number of remaining edges to start.
203 * `%f`: The number of finished edges.
204 * `%%`: A plain `%` character.
205 * The default progress status is `"[%s/%t] "` (note the trailing space
206 to separate from the build rule). Another example of possible progress status
207 could be `"[%u/%r/%f] "`.
212 The `-t` flag on the Ninja command line runs some tools that we have
213 found useful during Ninja's development. The current tools are:
216 `query`:: dump the inputs and outputs of a given target.
218 `browse`:: browse the dependency graph in a web browser. Clicking a
219 file focuses the view on that file, showing inputs and outputs. This
220 feature requires a Python installation.
222 `graph`:: output a file in the syntax used by `graphviz`, a automatic
223 graph layout tool. Use it like:
226 ninja -t graph mytarget | dot -Tpng -ograph.png
229 In the Ninja source tree, `ninja graph.png`
230 generates an image for Ninja itself. If no target is given generate a
231 graph for all root targets.
233 `targets`:: output a list of targets either by rule or by depth. If used
234 like +ninja -t targets rule _name_+ it prints the list of targets
235 using the given rule to be built. If no rule is given, it prints the source
236 files (the leaves of the graph). If used like
237 +ninja -t targets depth _digit_+ it
238 prints the list of targets in a depth-first manner starting by the root
239 targets (the ones with no outputs). Indentation is used to mark dependencies.
240 If the depth is zero it prints all targets. If no arguments are provided
241 +ninja -t targets depth 1+ is assumed. In this mode targets may be listed
242 several times. If used like this +ninja -t targets all+ it
243 prints all the targets available without indentation and it is faster
244 than the _depth_ mode.
246 `rules`:: output the list of all rules with their description if they have
247 one. It can be used to know which rule name to pass to
248 +ninja -t targets rule _name_+.
250 `commands`:: given a list of targets, print a list of commands which, if
251 executed in order, may be used to rebuild those targets, assuming that all
252 output files are out of date.
254 `clean`:: remove built files. By default it removes all built files
255 except for those created by the generator. Adding the `-g` flag also
256 removes built files created by the generator (see <<ref_rule,the rule
257 reference for the +generator+ attribute>>). Additional arguments are
258 targets, which removes the given targets and recursively all files
261 If used like +ninja -t clean -r _rules_+ it removes all files built using
264 depfiles are not removed. Files created but not referenced in the
265 graph are not removed. This tool takes in account the +-v+ and the
266 +-n+ options (note that +-n+ implies +-v+).
270 Writing your own Ninja files
271 ----------------------------
273 The remainder of this manual is only useful if you are constructing
274 Ninja files yourself: for example, if you're writing a meta-build
275 system or supporting a new language.
280 Ninja evaluates a graph of dependencies between files, and runs
281 whichever commands are necessary to make your build target up to date.
282 If you are familiar with Make, Ninja is very similar.
284 A build file (default name: `build.ninja`) provides a list of _rules_
285 -- short names for longer commands, like how to run the compiler --
286 along with a list of _build_ statements saying how to build files
287 using the rules -- which rule to apply to which inputs to produce
290 Conceptually, `build` statements describe the dependency graph of your
291 project, while `rule` statements describe how to generate the files
292 along a given edge of the graph.
297 Here's a basic `.ninja` file that demonstrates most of the syntax.
298 It will be used as an example for the following sections.
300 ---------------------------------
304 command = gcc $cflags -c $in -o $out
306 build foo.o: cc foo.c
307 ---------------------------------
311 Despite the non-goal of being convenient to write by hand, to keep
312 build files readable (debuggable), Ninja supports declaring shorter
313 reusable names for strings. A declaration like the following
319 can be used on the right side of an equals sign, dereferencing it with
320 a dollar sign, like this:
324 command = gcc $cflags -c $in -o $out
327 Variables can also be referenced using curly braces like `${in}`.
329 Variables might better be called "bindings", in that a given variable
330 cannot be changed, only shadowed. There is more on how shadowing works
331 later in this document.
336 Rules declare a short name for a command line. They begin with a line
337 consisting of the `rule` keyword and a name for the rule. Then
338 follows an indented set of `variable = value` lines.
340 The basic example above declares a new rule named `cc`, along with the
341 command to run. (In the context of a rule, the `command` variable is
342 special and defines the command to run. A full list of special
343 variables is provided in <<ref_rule,the reference>>.)
345 Within the context of a rule, two additional special variables are
346 available: `$in` expands to the list of input files (`foo.c`) and
347 `$out` to the output file (`foo.o`) for the command.
353 Build statements declare a relationship between input and output
354 files. They begin with the `build` keyword, and have the format
355 +build _outputs_: _rulename_ _inputs_+. Such a declaration says that
356 all of the output files are derived from the input files. When the
357 output files are missing or when the inputs change, Ninja will run the
358 rule to regenerate the outputs.
360 The basic example above describes how to build `foo.o`, using the `cc`
363 In the scope of a `build` block (including in the evaluation of its
364 associated `rule`), the variable `$in` is the list of inputs and the
365 variable `$out` is the list of outputs.
367 A build statement may be followed by an indented set of `key = value`
368 pairs, much like a rule. These variables will shadow any variables
369 when evaluating the variables in the command. For example:
372 cflags = -Wall -Werror
374 command = gcc $cflags -c $in -o $out
376 # If left unspecified, builds get the outer $cflags.
377 build foo.o: cc foo.c
379 # But you can can shadow variables like cflags for a particular build.
380 build special.o: cc special.c
383 # The variable was only shadowed for the scope of special.o;
384 # Subsequent build lines get the outer (original) cflags.
385 build bar.o: cc bar.c
389 For more discussion of how scoping works, consult <<ref_scope,the
392 If you need more complicated information passed from the build
393 statement to the rule (for example, if the rule needs "the file
394 extension of the first input"), pass that through as an extra
395 variable, like how `cflags` is passed above.
397 If the top-level Ninja file is specified as an output of any build
398 statement and it is out of date, Ninja will rebuild and reload it
399 before building the targets requested by the user.
402 Generating Ninja files from code
403 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
405 `misc/ninja_syntax.py` in the Ninja distribution is a tiny Python
406 module to facilitate generating Ninja files. It allows you to make
407 Python calls like `ninja.rule(name='foo', command='bar',
408 depfile='$out.d')` and it will generate the appropriate syntax. Feel
409 free to just inline it into your project's build system if it's
419 The special rule name `phony` can be used to create aliases for other
420 targets. For example:
423 build foo: phony some/file/in/a/faraway/subdir/foo
426 This makes `ninja foo` build the longer path. Semantically, the
427 `phony` rule is equivalent to a plain rule where the `command` does
428 nothing, but phony rules are handled specially in that they aren't
429 printed when run, logged (see below), nor do they contribute to the
430 command count printed as part of the build process.
432 `phony` can also be used to create dummy targets for files which
433 may not exist at build time. If a phony build statement is written
434 without any dependencies, the target will be considered out of date if
435 it does not exist. Without a phony build statement, Ninja will report
436 an error if the file does not exist and is required by the build.
439 Default target statements
440 ~~~~~~~~~~~~~~~~~~~~~~~~~
442 By default, if no targets are specified on the command line, Ninja
443 will build every output that is not named as an input elsewhere.
444 You can override this behavior using a default target statement.
445 A default target statement causes Ninja to build only a given subset
446 of output files if none are specified on the command line.
448 Default target statements begin with the `default` keyword, and have
449 the format +default _targets_+. A default target statement must appear
450 after the build statement that declares the target as an output file.
451 They are cumulative, so multiple statements may be used to extend
452 the list of default targets. For example:
459 This causes Ninja to build the `foo`, `bar` and `baz` targets by
466 For each built file, Ninja keeps a log of the command used to build
467 it. Using this log Ninja can know when an existing output was built
468 with a different command line than the build files specify (i.e., the
469 command line changed) and knows to rebuild the file.
471 The log file is kept in the build root in a file called `.ninja_log`.
472 If you provide a variable named `builddir` in the outermost scope,
473 `.ninja_log` will be kept in that directory instead.
479 A file is a series of declarations. A declaration can be one of:
481 1. A rule declaration, which begins with +rule _rulename_+, and
482 then has a series of indented lines defining variables.
484 2. A build edge, which looks like +build _output1_ _output2_:
485 _rulename_ _input1_ _input2_+. +
486 Implicit dependencies may be tacked on the end with +|
487 _dependency1_ _dependency2_+. +
488 Order-only dependencies may be tacked on the end with +||
489 _dependency1_ _dependency2_+. (See <<ref_dependencies,the reference on
492 3. Variable declarations, which look like +_variable_ = _value_+.
494 4. Default target statements, which look like +default _target1_ _target2_+.
496 5. References to more files, which look like +subninja _path_+ or
497 +include _path_+. The difference between these is explained below
498 <<ref_scope,in the discussion about scoping>>.
503 Ninja is mostly encoding agnostic, as long as the bytes Ninja cares
504 about (like slashes in paths) are ASCII. This means e.g. UTF-8 or
505 ISO-8859-1 input files ought to work.
507 Comments begin with `#` and extend to the end of the line.
509 Newlines are significant. Statements like `build foo bar` are a set
510 of space-separated tokens that end at the newline. Newlines and
511 spaces within a token must be escaped.
513 There is only one escape character, `$`, and it has the following
517 `$` followed by a newline:: escape the newline (continue the current line
518 across a line break).
520 `$` followed by text:: a variable reference.
522 `${varname}`:: alternate syntax for `$varname`.
524 `$` followed by space:: a space.
526 `$$`:: a literal `$`.
528 A `build` or `default` statement is first parsed as a space-separated
529 list of filenames and then each name is expanded. This means that
530 spaces within a variable will result in spaces in the expanded
535 build $spaced/baz other$ file: ...
536 # The above build line has two outputs: "foo bar/baz" and "other file".
539 In a `name = value` statement, whitespace at the beginning of a value
540 is always stripped. Whitespace at the beginning of a line after a
541 line continuation is also stripped.
544 two_words_with_one_space = foo $
546 one_word_with_no_space = foo$
550 Other whitespace is only significant if it's at the beginning of a
551 line. If a line is indented more than the previous one, it's
552 considered part of its parent's scope; if it is indented less than the
553 previous one, it closes the previous scope.
559 A `rule` block contains a list of `key = value` declarations that
560 affect the processing of the rule. Here is a full list of special
563 `command` (_required_):: the command line to run. This string (after
564 $variables are expanded) is passed directly to `sh -c` without
565 interpretation by Ninja. Each `rule` may have only one `command`
566 declaration. To specify multiple commands use `&&` (or similar) to
567 concatenate operations.
569 `depfile`:: path to an optional `Makefile` that contains extra
570 _implicit dependencies_ (see <<ref_dependencies,the reference on
571 dependency types>>). This is explicitly to support `gcc` and its `-M`
572 family of flags, which output the list of headers a given `.c` file
575 Use it like in the following example:
580 command = gcc -MMD -MF $out.d [other gcc flags here]
583 When loading a `depfile`, Ninja implicitly adds edges such that it is
584 not an error if the listed dependency is missing. This allows you to
585 delete a depfile-discovered header file and rebuild, without the build
586 aborting due to a missing input.
588 `description`:: a short description of the command, used to pretty-print
589 the command as it's running. The `-v` flag controls whether to print
590 the full command or its description; if a command fails, the full command
591 line will always be printed before the command's output.
593 `generator`:: if present, specifies that this rule is used to
594 re-invoke the generator program. Files built using `generator`
595 rules are treated specially in two ways: firstly, they will not be
596 rebuilt if the command line changes; and secondly, they are not
599 `restat`:: if present, causes Ninja to re-stat the command's outputs
600 after execution of the command. Each output whose modification time
601 the command did not change will be treated as though it had never
602 needed to be built. This may cause the output's reverse
603 dependencies to be removed from the list of pending build actions.
605 `rspfile`, `rspfile_content`:: if present (both), Ninja will use a
606 response file for the given command, i.e. write the selected string
607 (`rspfile_content`) to the given file (`rspfile`) before calling the
608 command and delete the file after successful execution of the
611 This is particularly useful on Windows OS, where the maximal length of
612 a command line is limited and response files must be used instead.
614 Use it like in the following example:
618 command = link.exe /OUT$out [usual link flags here] @$out.rsp
620 rspfile_content = $in
622 build myapp.exe: link a.obj b.obj [possibly many other .obj files]
625 Finally, the special `$in` and `$out` variables expand to the
626 shell-quoted space-separated list of files provided to the `build`
627 line referencing this `rule`.
633 There are three types of build dependencies which are subtly different.
635 1. _Explicit dependencies_, as listed in a build line. These are
636 available as the `$in` variable in the rule. Changes in these files
637 cause the output to be rebuilt; if these file are missing and
638 Ninja doesn't know how to build them, the build is aborted.
640 This is the standard form of dependency to be used for e.g. the
641 source file of a compile command.
643 2. _Implicit dependencies_, either as picked up from
644 a `depfile` attribute on a rule or from the syntax +| _dep1_
645 _dep2_+ on the end of a build line. The semantics are identical to
646 explicit dependencies, the only difference is that implicit dependencies
647 don't show up in the `$in` variable.
649 This is for expressing dependencies that don't show up on the
650 command line of the command; for example, for a rule that runs a
651 script, the script itself should be an implicit dependency, as
652 changes to the script should cause the output to rebuild.
654 Note that dependencies as loaded through depfiles have slightly different
655 semantics, as described in the <<ref_rule,rule reference>>.
657 3. _Order-only dependencies_, expressed with the syntax +|| _dep1_
658 _dep2_+ on the end of a build line. When these are out of date, the
659 output is not rebuilt until they are built, but changes in order-only
660 dependencies alone do not cause the output to be rebuilt.
662 Order-only dependencies can be useful for bootstrapping dependencies
663 that are only discovered during build time: for example, to generate a
664 header file before starting a subsequent compilation step. (Once the
665 header is used in compilation, a generated dependency file will then
666 express the implicit dependency.)
668 Evaluation and scoping
669 ~~~~~~~~~~~~~~~~~~~~~~
672 Top-level variable declarations are scoped to the file they occur in.
674 The `subninja` keyword, used to include another `.ninja` file,
675 introduces a new scope. The included `subninja` file may use the
676 variables from the parent file, and shadow their values for the file's
677 scope, but it won't affect values of the variables in the parent.
679 To include another `.ninja` file in the current scope, much like a C
680 `#include` statement, use `include` instead of `subninja`.
682 Variable declarations indented in a `build` block are scoped to the
683 `build` block. This scope is inherited by the `rule`. The full
684 lookup order for a variable referenced in a rule is:
686 1. Rule-level variables (i.e. `$in`, `$command`).
688 2. Build-level variables from the `build` that references this rule.
690 3. File-level variables from the file that the `build` line was in.
692 4. Variables from the file that included that file using the
698 Variables are expanded in paths (in a `build` or `default` statement)
699 and on the right side of a `name = value` statement.
701 When a `name = value` statement is evaluated, its right-hand side is
702 expanded once (according to the above scoping rules) immediately, and
703 from then on `$name` expands to the static string as the result of the
704 expansion. It is never the case that you'll need to "double-escape" a
705 value to prevent it from getting expanded twice.