v1.12.1, May 2024
- Introduction
- Philosophical overview
- Design goals
- Comparison to Make
- Using Ninja for your project
- Running Ninja
- Environment variables
- Extra tools
- Writing your own Ninja files
- Conceptual overview
- Syntax example
- Variables
- Rules
- Build statements
- Generating Ninja files from code
- More details
- The phony rule
- Default target statements
- The Ninja log
- Version compatibility
- C/C++ header dependencies
- depfile
- deps
- Pools
- The console pool
- Ninja file reference
- Lexical syntax
- Top-level variables
- Rule variables
- Interpretation of the command variable
- Build outputs
- Build dependencies
- Validations
- Variable expansion
- Evaluation and scoping
- Dynamic Dependencies
- Dyndep file reference
- Dyndep Examples
- Fortran Modules
- Tarball Extraction
Ninja is yet another build system. It takes as input theinterdependencies of files (typically source code and outputexecutables) and orchestrates building them, quickly.
Ninja joins a sea of other build systems. Its distinguishing goal isto be fast. It is born frommywork on the Chromium browser project, which has over 30,000 sourcefiles and whose other build systems (including one built from customnon-recursive Makefiles) would take ten seconds to start buildingafter changing one file. Ninja is under a second.
Where other build systems are high-level languages, Ninja aims to bean assembler.
Build systems get slow when they need to make decisions. When you arein an edit-compile cycle you want it to be as fast as possible — youwant the build system to do the minimum work necessary to figure outwhat needs to be built immediately.
Ninja contains the barest functionality necessary to describearbitrary dependency graphs. Its lack of syntax makes it impossibleto express complex decisions.
Instead, Ninja is intended to be used with a separate programgenerating its input files. The generator program (like the./configure
found in autotools projects) can analyze systemdependencies and make as many decisions as possible up front so thatincremental builds stay fast. Going beyond autotools, even build-timedecisions like "which compiler flags should I use?" or "should Ibuild a debug or release-mode binary?" belong in the .ninja
filegenerator.
Here are the design goals of Ninja:
- very fast (i.e., instant) incremental builds, even for very large projects.
- very little policy about how code is built. Different projects and higher-level build systems have different opinions about how code should be built; for example, should built objects live alongside the sources or should all build output go into a separate directory? Is there a "package" rule that builds a distributable package of the project? Sidestep these decisions by trying to allow either to be implemented, rather than choosing, even if that results in more verbosity.
- get dependencies correct, and in particular situations that are difficult to get right with Makefiles (e.g. outputs need an implicit dependency on the command line used to generate them; to build C source code you need to use gcc’s
-M
flags for header dependencies). - when convenience and speed are in conflict, prefer speed.
Some explicit non-goals:
- convenient syntax for writing build files by hand. You should generate your ninja files using another program. This is how we can sidestep many policy decisions.
- built-in rules. Out of the box, Ninja has no rules for e.g. compiling C code.
- build-time customization of the build. Options belong in the program that generates the ninja files.
- build-time decision-making ability such as conditionals or search paths. Making decisions is slow.
To restate, Ninja is faster than other build systems because it ispainfully simple. You must tell Ninja exactly what to do when youcreate your project’s .ninja
files.
Ninja is closest in spirit and functionality to Make, relying onsimple dependencies between file timestamps.
But fundamentally, make has a lot of features: suffix rules,functions, built-in rules that e.g. search for RCS files when buildingsource. Make’s language was designed to be written by humans. Manyprojects find make alone adequate for their build problems.
In contrast, Ninja has almost no features; just those necessary to getbuilds correct while punting most complexity to generation of theninja input files. Ninja by itself is unlikely to be useful for mostprojects.
Here are some of the features Ninja adds to Make. (These sorts offeatures can often be implemented using more complicated Makefiles,but they are not part of make itself.)
- Ninja has special support for discovering extra dependencies at build time, making it easy to get header dependencies correct for C/C++ code.
- A build edge may have multiple outputs.
- Outputs implicitly depend on the command line that was used to generate them, which means that changing e.g. compilation flags will cause the outputs to rebuild.
- Output directories are always implicitly created before running the command that relies on them.
- Rules can provide shorter descriptions of the command being run, so you can print e.g.
CC foo.o
instead of a long command line while building. - Builds are always run in parallel, based by default on the number of CPUs your system has. Underspecified build dependencies will result in incorrect builds.
- Command output is always buffered. This means commands running in parallel don’t interleave their output, and when a command fails we can print its failure output next to the full command line that produced the failure.
Ninja currently works on Unix-like systems and Windows. It’s seen themost testing on Linux (and has the best performance there) but it runsfine on Mac OS X and FreeBSD.
If your project is small, Ninja’s speed impact is likely unnoticeable.(However, even for small projects it sometimes turns out that Ninja’slimited syntax forces simpler build rules that result in fasterbuilds.) Another way to say this is that if you’re happy with theedit-compile cycle time of your project already then Ninja won’t help.
There are many other build systems that are more user-friendly orfeatureful than Ninja itself. For some recommendations: the Ninjaauthor found the tup build system influentialin Ninja’s design, and thinks redo'sdesign is quite clever.
Ninja’s benefit comes from using it in conjunction with a smartermeta-build system.
- gn
- The meta-build system used togenerate build files for Google Chrome and related projects (v8,node.js), as well as Google Fuchsia. gn can generate Ninja files forall platforms supported by Chrome.
- CMake
- A widely used meta-build system thatcan generate Ninja files on Linux as of CMake version 2.8.8. Newer versionsof CMake support generating Ninja files on Windows and Mac OS X too.
- others
- Ninja ought to fit perfectly into other meta-build softwarelike premake. If you do this work,please let us know!
Run ninja
. By default, it looks for a file named build.ninja
inthe current directory and builds all out-of-date targets. You canspecify which targets (files) to build as command line arguments.
There is also a special syntax target^
for specifying a targetas the first output of some rule containing the source you put inthe command line, if one exists. For example, if you specify target asfoo.c^
then foo.o
will get built (assuming you have those targetsin your build files).
ninja -h
prints help output. Many of Ninja’s flags intentionallymatch those of Make; e.g ninja -C build -j 20
changes into thebuild
directory and runs 20 build commands in parallel. (Note thatNinja defaults to running commands in parallel anyway, so typicallyyou don’t need to pass -j
.)
Ninja supports one environment variable to control its behavior:NINJA_STATUS
, the progress status printed before the rule being run.
Several placeholders are available:
%s
- The number of started edges.
%t
- The total number of edges that must be run to complete the build.
%p
- The percentage of finished edges.
%r
- The number of currently running edges.
%u
- The number of remaining edges to start.
%f
- The number of finished edges.
%o
- Overall rate of finished edges per second
%c
- Current rate of finished edges per second (average over buildsspecified by
-j
or its default) %e
- Elapsed time in seconds. (Available since Ninja 1.2.)
%E
- Remaining time (ETA) in seconds. (Available since Ninja 1.12.)
%w
- Elapsed time in [h:]mm:ss format. (Available since Ninja 1.12.)
%W
- Remaining time (ETA) in [h:]mm:ss format. (Available since Ninja 1.12.)
%P
- The percentage (in ppp% format) of time elapsed out of predicted total runtime. (Available since Ninja 1.12.)
%%
- A plain
%
character.
The default progress status is "[%f/%t] "
(note the trailing spaceto separate from the build rule). Another example of possible progress statuscould be "[%u/%r/%f] "
.
The -t
flag on the Ninja command line runs some tools that we havefound useful during Ninja’s development. The current tools are:
| dump the inputs and outputs of a given target. |
| browse the dependency graph in a web browser. Clicking afile focuses the view on that file, showing inputs and outputs. Thisfeature requires a Python installation. By default, port 8000 is usedand a web browser will be opened. This can be changed as follows: ninja -t browse --port=8000 --no-browser mytarget |
| output a file in the syntax used by ninja -t graph mytarget | dot -Tpng -ograph.png In the Ninja source tree, |
| output a list of targets either by rule or by depth. If usedlike |
| given a list of targets, print a list of commands which, ifexecuted in order, may be used to rebuild those targets, assuming that alloutput files are out of date. |
| given a list of targets, print a list of all inputs used torebuild those targets.Available since Ninja 1.11. |
| remove built files. By default, it removes all built filesexcept for those created by the generator. Adding the If used like Files created but not referenced in the graph are not removed. Thistool takes in account the |
| remove files produced by previous builds that are no longer in thebuild file. Available since Ninja 1.10. |
| given a list of rules, each of which is expected to be aC family language compiler rule whose first input is the name of thesource file, prints on standard output a compilation database in theJSON format expectedby the Clang tooling interface.Available since Ninja 1.2. |
| show all dependencies stored in the |
| given a list of targets, look for targets that depend ona generated file, but do not have a properly (possibly transitive) dependencyon the generator. Such targets may cause build flakiness on clean builds. The broken targets can be found assuming deps log / depfile dependencyinformation is correct. Any target that depends on a generated file (outputof a generator-target) implicitly, but does not have an explicit or order-onlydependency path to the generator-target, is considered broken. The tool’s findings can be verified by trying to build the listed targets ina clean outdir without building any other targets. The build should fail foreach of them with a missing include error or equivalent pointing to thegenerated file.Available since Ninja 1.11. |
| recompact the |
| updates all recorded file modification timestamps in the |
| output the list of all rules. It can be used to know which rule nameto pass to |
| Available on Windows hosts only.Helper tool to invoke the ninja -t msvc -e ENVFILE -- cl.exe <arguments> Where This tool also supports a deprecated way of parsing the compiler’s output whenthe ninja -t msvc -o DEPFILE [-p STRING] -- cl.exe /showIncludes <arguments> When using this option, Note that Ninja supports this natively now, with the use of |
| Available on Windows hosts (since Ninja 1.11).Prints the Windows code page whose encoding is expected in the build file.The output has the form: Build file encoding: <codepage> Additional lines may be added in future versions of Ninja. The
|
The remainder of this manual is only useful if you are constructingNinja files yourself: for example, if you’re writing a meta-buildsystem or supporting a new language.
Ninja evaluates a graph of dependencies between files, and runswhichever commands are necessary to make your build target up to dateas determined by file modification times. If you are familiar withMake, Ninja is very similar.
A build file (default name: build.ninja
) provides a list of rules — short names for longer commands, like how to run the compiler — along with a list of build statements saying how to build filesusing the rules — which rule to apply to which inputs to producewhich outputs.
Conceptually, build
statements describe the dependency graph of yourproject, while rule
statements describe how to generate the filesalong a given edge of the graph.
Here’s a basic .ninja
file that demonstrates most of the syntax.It will be used as an example for the following sections.
cflags = -Wallrule cc command = gcc $cflags -c $in -o $outbuild foo.o: cc foo.c
Despite the non-goal of being convenient to write by hand, to keepbuild files readable (debuggable), Ninja supports declaring shorterreusable names for strings. A declaration like the following
cflags = -g
can be used on the right side of an equals sign, dereferencing it witha dollar sign, like this:
rule cc command = gcc $cflags -c $in -o $out
Variables can also be referenced using curly braces like ${in}
.
Variables might better be called "bindings", in that a given variablecannot be changed, only shadowed. There is more on how shadowing workslater in this document.
Rules declare a short name for a command line. They begin with a lineconsisting of the rule
keyword and a name for the rule. Thenfollows an indented set of variable = value
lines.
The basic example above declares a new rule named cc
, along with thecommand to run. In the context of a rule, the command
variabledefines the command to run, $in
expands to the list ofinput files (foo.c
), and $out
to the output files (foo.o
) for thecommand. A full list of special variables is provided inthe reference.
Build statements declare a relationship between input and outputfiles. They begin with the build
keyword, and have the formatbuild outputs: rulename inputs
. Such a declaration says thatall of the output files are derived from the input files. When theoutput files are missing or when the inputs change, Ninja will run therule to regenerate the outputs.
The basic example above describes how to build foo.o
, using the cc
rule.
In the scope of a build
block (including in the evaluation of itsassociated rule
), the variable $in
is the list of inputs and thevariable $out
is the list of outputs.
A build statement may be followed by an indented set of key = value
pairs, much like a rule. These variables will shadow any variableswhen evaluating the variables in the command. For example:
cflags = -Wall -Werrorrule cc command = gcc $cflags -c $in -o $out# If left unspecified, builds get the outer $cflags.build foo.o: cc foo.c# But you can shadow variables like cflags for a particular build.build special.o: cc special.c cflags = -Wall# The variable was only shadowed for the scope of special.o;# Subsequent build lines get the outer (original) cflags.build bar.o: cc bar.c
For more discussion of how scoping works, consult the reference.
If you need more complicated information passed from the buildstatement to the rule (for example, if the rule needs "the fileextension of the first input"), pass that through as an extravariable, like how cflags
is passed above.
If the top-level Ninja file is specified as an output of any buildstatement and it is out of date, Ninja will rebuild and reload itbefore building the targets requested by the user.
misc/ninja_syntax.py
in the Ninja distribution is a tiny Pythonmodule to facilitate generating Ninja files. It allows you to makePython calls like ninja.rule(name='foo', command='bar',depfile='$out.d')
and it will generate the appropriate syntax. Feelfree to just inline it into your project’s build system if it’suseful.
The special rule name phony
can be used to create aliases for othertargets. For example:
build foo: phony some/file/in/a/faraway/subdir/foo
This makes ninja foo
build the longer path. Semantically, thephony
rule is equivalent to a plain rule where the command
doesnothing, but phony rules are handled specially in that they aren’tprinted when run, logged (see below), nor do they contribute to thecommand count printed as part of the build process.
When a phony
target is used as an input to another build rule, theother build rule will, semantically, consider the inputs of thephony
rule as its own. Therefore, phony
rules can be used to groupinputs, e.g. header files.
phony
can also be used to create dummy targets for files whichmay not exist at build time. If a phony build statement is writtenwithout any dependencies, the target will be considered out of date ifit does not exist. Without a phony build statement, Ninja will reportan error if the file does not exist and is required by the build.
To create a rule that never rebuilds, use a build rule without any input:
rule touch command = touch $outbuild file_that_always_exists.dummy: touchbuild dummy_target_to_follow_a_pattern: phony file_that_always_exists.dummy
By default, if no targets are specified on the command line, Ninjawill build every output that is not named as an input elsewhere.You can override this behavior using a default target statement.A default target statement causes Ninja to build only a given subsetof output files if none are specified on the command line.
Default target statements begin with the default
keyword, and havethe format default targets
. A default target statement must appearafter the build statement that declares the target as an output file.They are cumulative, so multiple statements may be used to extendthe list of default targets. For example:
default foo bardefault baz
This causes Ninja to build the foo
, bar
and baz
targets bydefault.
For each built file, Ninja keeps a log of the command used to buildit. Using this log Ninja can know when an existing output was builtwith a different command line than the build files specify (i.e., thecommand line changed) and knows to rebuild the file.
The log file is kept in the build root in a file called .ninja_log
.If you provide a variable named builddir
in the outermost scope,.ninja_log
will be kept in that directory instead.
Available since Ninja 1.2.
Ninja version labels follow the standard major.minor.patch format,where the major version is increased on backwards-incompatiblesyntax/behavioral changes and the minor version is increased on newbehaviors. Your build.ninja
may declare a variable namedninja_required_version
that asserts the minimum Ninja versionrequired to use the generated file. For example,
ninja_required_version = 1.1
declares that the build file relies on some feature that wasintroduced in Ninja 1.1 (perhaps the pool
syntax), and thatNinja 1.1 or greater must be used to build. Unlike other Ninjavariables, this version requirement is checked immediately whenthe variable is encountered in parsing, so it’s best to put itat the top of the build file.
Ninja always warns if the major versions of Ninja and theninja_required_version
don’t match; a major version change hasn’tcome up yet so it’s difficult to predict what behavior might berequired.
To get C/C++ header dependencies (or any other build dependency thatworks in a similar way) correct Ninja has some extra functionality.
The problem with headers is that the full list of files that a givensource file depends on can only be discovered by the compiler:different preprocessor defines and include paths cause different filesto be used. Some compilers can emit this information while building,and Ninja can use that to get its dependencies perfect.
Consider: if the file has never been compiled, it must be built anyway,generating the header dependencies as a side effect. If any file islater modified (even in a way that changes which headers it dependson) the modification will cause a rebuild as well, keeping thedependencies up to date.
When loading these special dependencies, Ninja implicitly adds extrabuild edges such that it is not an error if the listed dependency ismissing. This allows you to delete a header file and rebuild withoutthe build aborting due to a missing input.
gcc
(and other compilers like clang
) support emitting dependencyinformation in the syntax of a Makefile. (Any command that can writedependencies in this form can be used, not just gcc
.)
To bring this information into Ninja requires cooperation. On theNinja side, the depfile
attribute on the build
must point to apath where this data is written. (Ninja only supports the limitedsubset of the Makefile syntax emitted by compilers.) Then the commandmust know to write dependencies into the depfile
path.Use it like in the following example:
rule cc depfile = $out.d command = gcc -MD -MF $out.d [other gcc flags here]
The -MD
flag to gcc
tells it to output header dependencies, andthe -MF
flag tells it where to write them.
(Available since Ninja 1.3.)
It turns out that for large projects (and particularly on Windows,where the file system is slow) loading these dependency files onstartup is slow.
Ninja 1.3 can instead process dependencies just after they’re generatedand save a compacted form of the same information in a Ninja-internaldatabase.
Ninja supports this processing in two forms.
deps = gcc
specifies that the tool outputsgcc
-style dependencies in the form of Makefiles. Adding this to the above example will cause Ninja to process thedepfile
immediately after the compilation finishes, then delete the.d
file (which is only used as a temporary).deps = msvc
specifies that the tool outputs header dependencies in the form produced by the Visual Studio compiler’s/showIncludes
flag. Briefly, this means the tool outputs specially-formatted lines to its stdout. Ninja then filters these lines from the displayed output. Nodepfile
attribute is necessary, but the localized string in front of the header file path should be globally defined. For instance,msvc_deps_prefix = Note: including file:
for an English Visual Studio (the default).msvc_deps_prefix = Note: including file:rule cc deps = msvc command = cl /showIncludes -c $in /Fo$out
If the include directory directives are using absolute paths, your depfilemay result in a mixture of relative and absolute paths. Paths used by otherbuild rules need to match exactly. Therefore, it is recommended to userelative paths in these cases.
Available since Ninja 1.1.
Pools allow you to allocate one or more rules or edges a finite numberof concurrent jobs which is more tightly restricted than the defaultparallelism.
This can be useful, for example, to restrict a particular expensive rule(like link steps for huge executables), or to restrict particular buildstatements which you know perform poorly when run concurrently.
Each pool has a depth
variable which is specified in the build file.The pool is then referred to with the pool
variable on either a ruleor a build statement.
No matter what pools you specify, ninja will never run more concurrent jobsthan the default parallelism, or the number of jobs specified on the commandline (with -j
).
# No more than 4 links at a time.pool link_pool depth = 4# No more than 1 heavy object at a time.pool heavy_object_pool depth = 1rule link ... pool = link_poolrule cc ...# The link_pool is used here. Only 4 links will run concurrently.build foo.exe: link input.obj# A build statement can be exempted from its rule's pool by setting an# empty pool. This effectively puts the build statement back into the default# pool, which has infinite depth.build other.exe: link input.obj pool =# A build statement can specify a pool directly.# Only one of these builds will run at a time.build heavy_object1.obj: cc heavy_obj1.cc pool = heavy_object_poolbuild heavy_object2.obj: cc heavy_obj2.cc pool = heavy_object_pool
Available since Ninja 1.5.
There exists a pre-defined pool named console
with a depth of 1. It hasthe special property that any task in the pool has direct access to thestandard input, output and error streams provided to Ninja, which arenormally connected to the user’s console (hence the name) but could beredirected. This can be useful for interactive tasks or long-running taskswhich produce status updates on the console (such as test suites).
While a task in the console
pool is running, Ninja’s regular output (suchas progress status and output from concurrent tasks) is buffered untilit completes.
A file is a series of declarations. A declaration can be one of:
- A rule declaration, which begins with
rule rulename
, and then has a series of indented lines defining variables. A build edge, which looks like
build output1 output2: rulename input1 input2
. Implicit dependencies may be tacked on the end with| dependency1 dependency2
. Order-only dependencies may be tacked on the end with|| dependency1 dependency2
. (See the reference on dependency types.) Validations may be taked on the end with|@ validation1 validation2
. (See the reference on validations.)Implicit outputs (available since Ninja 1.7) may be added beforethe
:
with| output1 output2
and do not appear in$out
.(See the reference on output types.)- Variable declarations, which look like
variable = value
. - Default target statements, which look like
default target1 target2
. - References to more files, which look like
subninja path
orinclude path
. The difference between these is explained below in the discussion about scoping. - A pool declaration, which looks like
pool poolname
. Pools are explained in the section on pools.
Ninja is mostly encoding agnostic, as long as the bytes Ninja caresabout (like slashes in paths) are ASCII. This means e.g. UTF-8 orISO-8859-1 input files ought to work.
Comments begin with #
and extend to the end of the line.
Newlines are significant. Statements like build foo bar
are a setof space-separated tokens that end at the newline. Newlines andspaces within a token must be escaped.
There is only one escape character, $
, and it has the followingbehaviors:
$
followed by a newline- escape the newline (continue the current lineacross a line break).
$
followed by text- a variable reference.
${varname}
- alternate syntax for
$varname
. $
followed by space- a space. (This is only necessary in lists ofpaths, where a space would otherwise separate filenames. See below.)
$:
- a colon. (This is only necessary in
build
lines, where a colonwould otherwise terminate the list of outputs.) $$
- a literal
$
.
A build
or default
statement is first parsed as a space-separatedlist of filenames and then each name is expanded. This means thatspaces within a variable will result in spaces in the expandedfilename.
spaced = foo barbuild $spaced/baz other$ file: ...# The above build line has two outputs: "foo bar/baz" and "other file".
In a name = value
statement, whitespace at the beginning of a valueis always stripped. Whitespace at the beginning of a line after aline continuation is also stripped.
two_words_with_one_space = foo $ barone_word_with_no_space = foo$ bar
Other whitespace is only significant if it’s at the beginning of aline. If a line is indented more than the previous one, it’sconsidered part of its parent’s scope; if it is indented less than theprevious one, it closes the previous scope.
Two variables are significant when declared in the outermost file scope.
builddir
- a directory for some Ninja output files. See the discussion of the build log. (You can also store other build output in this directory.)
ninja_required_version
- the minimum version of Ninja required to process the build correctly. See the discussion of versioning.
A rule
block contains a list of key = value
declarations thataffect the processing of the rule. Here is a full list of specialkeys.
command
(required)- the command line to run. Each
rule
may have only onecommand
declaration. See the next section for more details on quoting and executing multiple commands. depfile
- path to an optional
Makefile
that contains extra implicit dependencies (see the reference on dependency types). This is explicitly to support C/C++ header dependencies; see the full discussion. deps
- (Available since Ninja 1.3.) if present, must be one of
gcc
ormsvc
to specify special dependency processing. See the full discussion. The generated database is stored as.ninja_deps
in thebuilddir
, see the discussion of builddir. msvc_deps_prefix
- (Available since Ninja 1.5.) defines the string which should be stripped from msvc’s /showIncludes output. Only needed when
deps = msvc
and no English Visual Studio version is used. description
- a short description of the command, used to pretty-print the command as it’s running. The
-v
flag controls whether to print the full command or its description; if a command fails, the full command line will always be printed before the command’s output. dyndep
- (Available since Ninja 1.10.) Used only on build statements. If present, must name one of the build statement inputs. Dynamically discovered dependency information will be loaded from the file. See the dynamic dependencies section for details.
generator
- if present, specifies that this rule is used to re-invoke the generator program. Files built using
generator
rules are treated specially in two ways: firstly, they will not be rebuilt if the command line changes; and secondly, they are not cleaned by default. in
- the space-separated list of files provided as inputs to the build line referencing this
rule
, shell-quoted if it appears in commands. ($in
is provided solely for convenience; if you need some subset or variant of this list of files, just construct a new variable with that list and use that instead.) in_newline
- the same as
$in
except that multiple inputs are separated by newlines rather than spaces. (For use with$rspfile_content
; this works around a bug in the MSVC linker where it uses a fixed-size buffer for processing input.) out
- the space-separated list of files provided as outputs to the build line referencing this
rule
, shell-quoted if it appears in commands. restat
- if present, causes Ninja to re-stat the command’s outputs after execution of the command. Each output whose modification time the command did not change will be treated as though it had never needed to be built. This may cause the output’s reverse dependencies to be removed from the list of pending build actions.
rspfile
,rspfile_content
if present (both), Ninja will use a response file for the given command, i.e. write the selected string (
rspfile_content
) to the given file (rspfile
) before calling the command and delete the file after successful execution of the command.This is particularly useful on Windows OS, where the maximal length ofa command line is limited and response files must be used instead.
Use it like in the following example:
rule link command = link.exe /OUT$out [usual link flags here] @$out.rsp rspfile = $out.rsp rspfile_content = $inbuild myapp.exe: link a.obj b.obj [possibly many other .obj files]
Fundamentally, command lines behave differently on Unixes and Windows.
On Unixes, commands are arrays of arguments. The Ninja command
variable is passed directly to sh -c
, which is then responsible forinterpreting that string into an argv array. Therefore, the quotingrules are those of the shell, and you can use all the normal shelloperators, like &&
to chain multiple commands, or VAR=value cmd
toset environment variables.
On Windows, commands are strings, so Ninja passes the command
stringdirectly to CreateProcess
. (In the common case of simply executinga compiler this means there is less overhead.) Consequently, thequoting rules are determined by the called program, which on Windowsare usually provided by the C library. If you need shellinterpretation of the command (such as the use of &&
to chainmultiple commands), make the command execute the Windows shell byprefixing the command with cmd /c
. Ninja may error with "invalid parameter"which usually indicates that the command line length has been exceeded.
There are two types of build outputs which are subtly different.
Explicit outputs, as listed in a build line. These are available as the
$out
variable in the rule.This is the standard form of output to be used for e.g. theobject file of a compile command.
Implicit outputs, as listed in a build line with the syntax
| out1 out2
+ before the:
of a build line (available since Ninja 1.7). The semantics are identical to explicit outputs, the only difference is that implicit outputs don’t show up in the$out
variable.This is for expressing outputs that don’t show up on thecommand line of the command.
There are three types of build dependencies which are subtly different.
Explicit dependencies, as listed in a build line. These are available as the
$in
variable in the rule. Changes in these files cause the output to be rebuilt; if these files are missing and Ninja doesn’t know how to build them, the build is aborted.This is the standard form of dependency to be used e.g. for thesource file of a compile command.
Implicit dependencies, either as picked up from a
depfile
attribute on a rule or from the syntax| dep1 dep2
on the end of a build line. The semantics are identical to explicit dependencies, the only difference is that implicit dependencies don’t show up in the$in
variable.This is for expressing dependencies that don’t show up on thecommand line of the command; for example, for a rule that runs ascript that reads a hardcoded file, the hardcoded file shouldbe an implicit dependency, as changes to the file should causethe output to rebuild, even though it doesn’t show up in the arguments.
Note that dependencies as loaded through depfiles have slightly differentsemantics, as described in the rule reference.
Order-only dependencies, expressed with the syntax
|| dep1 dep2
on the end of a build line. When these are out of date, the output is not rebuilt until they are built, but changes in order-only dependencies alone do not cause the output to be rebuilt.Order-only dependencies can be useful for bootstrapping dependenciesthat are only discovered during build time: for example, to generate aheader file before starting a subsequent compilation step. (Once theheader is used in compilation, a generated dependency file will thenexpress the implicit dependency.)
File paths are compared as is, which means that an absolute path and arelative path, pointing to the same file, are considered different by Ninja.
Available since Ninja 1.11.
Validations listed on the build line cause the specified files to beadded to the top level of the build graph (as if they were specifiedon the Ninja command line) whenever the build line is a transitivedependency of one of the targets specified on the command line or adefault target.
Validations are added to the build graph regardless of whether the outputfiles of the build statement are dirty are not, and the dirty state ofthe build statement that outputs the file being used as a validationhas no effect on the dirty state of the build statement that requested it.
A build edge can list another build edge as a validation even if the secondedge depends on the first.
Validations are designed to handle rules that perform error checking butdon’t produce any artifacts needed by the build, for example, staticanalysis tools. Marking the static analysis rule as an implicit inputof the main build rule of the source files or of the rules that dependon the main build rule would slow down the critical path of the build,but using a validation would allow the build to proceed in parallel withthe static analysis rule once the main build rule is complete.
Variables are expanded in paths (in a build
or default
statement)and on the right side of a name = value
statement.
When a name = value
statement is evaluated, its right-hand side isexpanded immediately (according to the below scoping rules), andfrom then on $name
expands to the static string as the result of theexpansion. It is never the case that you’ll need to "double-escape" avalue to prevent it from getting expanded twice.
All variables are expanded immediately as they’re encountered in parsing,with one important exception: variables in rule
blocks are expandedwhen the rule is used, not when it is declared. In the followingexample, the demo
rule prints "this is a demo of bar".
rule demo command = echo "this is a demo of $foo"build out: demo foo = bar
Top-level variable declarations are scoped to the file they occur in.
Rule declarations are also scoped to the file they occur in.(Available since Ninja 1.6)
The subninja
keyword, used to include another .ninja
file,introduces a new scope. The included subninja
file may use thevariables and rules from the parent file, and shadow their values for the file’sscope, but it won’t affect values of the variables in the parent.
To include another .ninja
file in the current scope, much like a C#include
statement, use include
instead of subninja
.
Variable declarations indented in a build
block are scoped to thebuild
block. The full lookup order for a variable expanded in abuild
block (or the rule
is uses) is:
- Special built-in variables (
$in
,$out
). - Build-level variables from the
build
block. - Rule-level variables from the
rule
block (i.e.$command
). (Note from the above discussion on expansion that these are expanded "late", and may make use of in-scope bindings like$in
.) - File-level variables from the file that the
build
line was in. - Variables from the file that included that file using the
subninja
keyword.
Available since Ninja 1.10.
Some use cases require implicit dependency information to be dynamicallydiscovered from source file content during the build in order to buildcorrectly on the first run (e.g. Fortran module dependencies). This isunlike header dependencies which are only needed on thesecond run and later to rebuild correctly. A build statement may have adyndep
binding naming one of its inputs to specify that dynamicdependency information must be loaded from the file. For example:
build out: ... || foo dyndep = foobuild foo: ...
This specifies that file foo
is a dyndep file. Since it is an input,the build statement for out
can never be executed before foo
is built.As soon as foo
is finished Ninja will read it to load dynamicallydiscovered dependency information for out
. This may include additionalimplicit inputs and/or outputs. Ninja will update the build graphaccordingly and the build will proceed as if the information was knownoriginally.
Files specified by dyndep
bindings use the same lexical syntaxas ninja build files and have the following layout.
A version number in the form
<major>[.<minor>][<suffix>]
:ninja_dyndep_version = 1
Currently the version number must always be
1
or1.0
but may havean arbitrary suffix.One or more build statements of the form:
build out | imp-outs... : dyndep | imp-ins...
Every statement must specify exactly one explicit output and must usethe rule name
dyndep
. The| imp-outs...
and| imp-ins...
portionsare optional.- An optional
restat
variable binding on each build statement.
The build statements in a dyndep file must have a one-to-one correspondenceto build statements in the ninja build file that name thedyndep file in a dyndep
binding. No dyndep build statement may be omittedand no extra build statements may be specified.
Consider a Fortran source file foo.f90
that provides a modulefoo.mod
(an implicit output of compilation) and another source filebar.f90
that uses the module (an implicit input of compilation). Thisimplicit dependency must be discovered before we compile either sourcein order to ensure that bar.f90
never compiles before foo.f90
, andthat bar.f90
recompiles when foo.mod
changes. We can achieve thisas follows:
rule f95 command = f95 -o $out -c $inrule fscan command = fscan -o $out $inbuild foobar.dd: fscan foo.f90 bar.f90build foo.o: f95 foo.f90 || foobar.dd dyndep = foobar.ddbuild bar.o: f95 bar.f90 || foobar.dd dyndep = foobar.dd
In this example the order-only dependencies ensure that foobar.dd
isgenerated before either source compiles. The hypothetical fscan
toolscans the source files, assumes each will be compiled to a .o
of thesame name, and writes foobar.dd
with content such as:
ninja_dyndep_version = 1build foo.o | foo.mod: dyndepbuild bar.o: dyndep | foo.mod
Ninja will load this file to add foo.mod
as an implicit output offoo.o
and implicit input of bar.o
. This ensures that the Fortransources are always compiled in the proper order and recompiled whenneeded.
Consider a tarball foo.tar
that we want to extract. The extraction timecan be recorded with a foo.tar.stamp
file so that extraction repeats ifthe tarball changes, but we also would like to re-extract if any of theoutputs is missing. However, the list of outputs depends on the contentof the tarball and cannot be spelled out explicitly in the ninja build file.We can achieve this as follows:
rule untar command = tar xf $in && touch $outrule scantar command = scantar --stamp=$stamp --dd=$out $inbuild foo.tar.dd: scantar foo.tar stamp = foo.tar.stampbuild foo.tar.stamp: untar foo.tar || foo.tar.dd dyndep = foo.tar.dd
In this example the order-only dependency ensures that foo.tar.dd
isbuilt before the tarball extracts. The hypothetical scantar
toolwill read the tarball (e.g. via tar tf
) and write foo.tar.dd
withcontent such as:
ninja_dyndep_version = 1build foo.tar.stamp | file1.txt file2.txt : dyndep restat = 1
Ninja will load this file to add file1.txt
and file2.txt
as implicitoutputs of foo.tar.stamp
, and to mark the build statement for restat
.On future builds, if any implicit output is missing the tarball will beextracted again. The restat
binding tells Ninja to tolerate the factthat the implicit outputs may not have modification times newer thanthe tarball itself (avoiding re-extraction on every build).