1 # GN Language and Operation
7 This page describes many of the language details and behaviors.
9 ### Use the built-in help!
11 GN has an extensive built-in help system which provides a reference for
12 every function and built-in variable. This page is more high-level.
20 * Writing build files should not be a creative endeavour. Ideally two
21 people should produce the same buildfile given the same
22 requirements. There should be no flexibility unless it's absolutely
23 needed. As many things should be fatal errors as possible.
25 * The definition should read more like code than rules. I don't want
26 to write or debug Prolog. But everybody on our team can write and
29 * The build language should be opinionated as to how the build should
30 work. It should not necessarily be easy or even possible to express
31 arbitrary things. We should be changing source and tooling to make
32 the build simpler rather than making everything more complicated to
33 conform to external requirements (within reason).
35 * Be like Blaze when it makes sense (see "Differences and similarities
40 GN uses an extremely simple, dynamically typed language. The types are:
42 * Boolean (`true`, `false`).
43 * 64-bit signed integers.
45 * Lists (of any other types)
46 * Scopes (sort of like a dictionary, only for built-in stuff)
48 There are some built-in variables whose values depend on the current
49 environment. See `gn help` for more.
51 There are purposefully many omissions in the language. There are no
52 loops or function calls, for example. As per the above design
53 philosophy, if you need this kind of thing you're probably doing it
56 The variable `sources` has a special rule: when assigning to it, a list
57 of exclusion patterns is applied to it. This is designed to
58 automatically filter out some types of files. See `gn help
59 set_sources_assignment_filter` and `gn help patterns` for more.
63 Strings are enclosed in double-quotes and use backslash as the escape
64 character. The only escape sequences supported are
66 * `\"` (for literal quote)
67 * `\$` (for literal dollars sign)
68 * `\\` (for literal backslash) Any other use of a backslash is treated
69 as a literal backslash. So, for example, `\b` used in patterns does
70 not need to be escaped, nor do most windows paths like
73 Simple variable substitution is supported via `$`, where the word
74 following the dollars sign is replaced with the value of the variable.
75 You can optionally surround the name with `{}` if there is not a
76 non-variable-name character to terminate the variable name. More complex
77 expressions are not supported, only variable name substitution.
81 b = "$a/foo.cc" # b -> "mypath/foo.cc"
82 c = "foo${a}bar.cc" # c -> "foomypathbar.cc"
87 There is no way to get the length of a list. If you find yourself
88 wanting to do this kind of thing, you're trying to do too much work in
91 Lists support appending:
95 a += [ "second" ] # [ "first", "second" ]
96 a += [ "third", "fourth" ] # [ "first", "second", "third", "fourth" ]
97 b = a + [ "fifth" ] # [ "first", "second", "third", "fourth", "fifth" ]
100 Appending a list to another list appends the items in the second list
101 rather than appending the list as a nested member.
103 You can remove items from a list:
106 a = [ "first", "second", "third", "first" ]
107 b = a - [ "first" ] # [ "second", "third" ]
108 a -= [ "second" ] # [ "first", "third", "fourth" ]
111 The - operator on a list searches for matches and removes all matching
112 items. Subtracting a list from another list will remove each item in the
115 If no matching items are found, an error will be thrown, so you need to
116 know in advance that the item is there before removing it. Given that
117 there is no way to test for inclusion, the main use-case is to set up a
118 master list of files or flags, and to remove ones that don't apply to
119 the current build based on various conditions.
121 Lists support zero-based subscripting to extract values:
124 a = [ "first", "second", "third" ]
125 b = a[1] # -> "second"
128 The \[\] operator is read-only and can not be used to mutate the
129 list. This is of limited value absent the ability to iterate over a
130 list. The primary use-case of this is when an external script returns
131 several known values and you want to extract them.
133 There are some cases where it's easy to overwrite a list when you mean
134 to append to it instead. To help catch this case, it is an error to
135 assign a nonempty list to a variable containing an existing nonempty
136 list. If you want to get around this restriction, first assign the
137 destination variable to the empty list.
141 a = [ "two" ] # Error: overwriting nonempty list with a nonempty list.
146 Note that execution of the build script is done without intrinsic
147 knowledge of the meaning of the underlying data. This means that it
148 doesn't know that `sources` is a list of file names, for example. So if
149 you remove an item, it must match the literal string rather than
150 specifying a different name that will resolve to the same file name.
154 Conditionals look like C:
157 if (is_linux || (is_win && target_cpu == "x86")) {
158 sources -= [ "something.cc" ]
166 You can use them in most places, even around entire targets if the
167 target should only be declared in certain circumstances.
171 Simple functions look like most other languages:
174 print("hello, world")
175 assert(is_win, "This should only be executed on Windows")
178 Some functions take a block of code enclosed by `{ }` following them:
181 static_library("mylibrary") {
186 This means that the block becomes an argument to the function for the
187 function to execute. Most of the block-style functions execute the block
188 and treat the resulting scope as a dictionary of variables to read.
190 ### Scoping and execution
192 Files and `{ }` blocks introduce new scopes. Scoped are nested. When you
193 read a variable, the containing scopes will be searched in reverse order
194 until a matching name is found. Variable writes always go to the
197 There is no way to modify any enclosing scope other than the innermost
198 one. This means that when you define a target, for example, nothing you
199 do inside of the block will "leak out" into the rest of the file.
201 `if`/`else` statements, even though they use `{ }`, do not introduce a
202 new scope so changes will persist outside of the statement.
206 ### File and directory names
208 File and directory names are strings and are interpreted as relative to
209 the current build file's directory. There are three possible forms:
219 Source-tree absolute names:
226 System absolute names (rare, normally used for include directories):
229 "/usr/local/include/"
230 "/C:/Program Files/Windows Kits/Include"
235 Everything that can participate in the dependency graph (targets,
236 configs, and toolchains) are identified by labels which are strings of a
237 defined format. A common label looks like this:
240 "//base/test:test_support"
243 which consists of a source-root-absolute path, a colon, and a name. This
244 means to look for the thing named "test\_support" in
245 `src/base/test/BUILD.gn`.
247 When loading a build file, if it doesn't exist in the given location
248 relative to the source root, GN will look in the secondary tree in
249 `tools/gn/secondary`. This structure of this tree mirrors the main
250 repository and is a way to add build files for directories that may be
251 pulled from other repositories where we can't easily check in BUILD
254 A canonical label also includes the label of the toolchain being used.
255 Normally, the toolchain label is implicitly inherited, but you can
256 include it to specify cross-toolchain dependencies (see "Toolchains"
260 "//base/test:test_support(//build/toolchain/win:msvc)"
263 In this case it will look for the a toolchain definition called "msvc"
264 in the file `//build/toolchain/win` to know how to compile this target.
266 If you want to refer to something in the same buildfile, you can omit
267 the path name and just start with a colon.
273 Labels can be specified as being relative to the current directory:
276 "source/plugin:myplugin"
280 If a name is unspecified, it will inherit the directory name:
283 "//net" = "//net:net"
284 "//tools/gn" = "//tools/gn:gn"
287 ## Build configuration
289 ### Overall build flow
291 1. Look for `.gn` file in the current directory and walk up the
292 directory tree until one is found. Set this directory to be the
293 "source root" and interpret this file to find the name of the build
295 2. Execute the build config file (this is the default toolchain).
296 3. Load the `BUILD.gn` file in the root directory.
297 4. Recursively load `BUILD.gn` in other directories to resolve all
298 current dependencies. If a BUILD file isn't found in the specified
299 location, GN will look in the corresponding location inside
300 `tools/gn/secondary`.
301 5. When a target's dependencies are resolved, write out the `.ninja`
303 6. When all targets are resolved, write out the root `build.ninja`
306 ### The build config file
308 The first file executed is the build config file. The name of this file
309 is specified in the `.gn` file that marks the root of the repository. In
310 Chrome it is `src/build/config/BUILDCONFIG.gn`. There is only one build
313 This file sets up the scope in which all other build files will execute.
314 Any arguments, variables, defaults, etc. set up in this file will be
315 visible to all files in the build.
317 It is executed once for each toolchain (see "Toolchains").
321 Arguments can be passed in from the command line (and from other
322 toolchains, see "Toolchains" below). You declare which arguments you
323 accept and specify default values via `declare_args`.
325 See `gn help buildargs` for an overview of how this works. See `gn help
326 declare_args` for specifics on declaring them.
328 It is an error to declare a given argument more than once in a given
329 scope. Typically arguments would be declared in an imported file (to
330 share them among some subset of the build) or in the main build config
331 file (to make them global).
335 You can set up some default values for a given target type. This is
336 normally done in the build config file to set a list of default configs
337 that defines the build flags and other setup information for each target
340 See `gn help set_defaults`.
342 For example, when you declare a `static_library`, the target defaults
343 for a static library are applied. These values can be overwritten,
344 modified, or preserved by a target.
347 # This call is typically in the build config file (see above).
348 set_defaults("static_library") {
349 configs = [ "//build:rtti_setup", "//build:extra_warnings" ]
352 # This would be in your directory's BUILD.gn file.
353 static_library("mylib") {
354 # At this point configs is set to [ "//build:rtti_setup", "//build:extra_warnings" ]
355 # by default but may be modified.
356 configs -= "//build:extra_warnings" # Don't want these warnings.
357 configs += ":mylib_config" # Add some more configs.
361 The other use-case for setting target defaults is when you define your
362 own target type via `template` and want to specify certain default
367 A target is a node in the build graph. It usually represents some kind
368 of executable or library file that will be generated. Targets depend on
369 other targets. The built-in target types (see `gn help <targettype>` for
372 * `action`: Run a script to generate a file.
373 * `action_foreach`: Run a script once for each source file.
374 * `component`: Configurable to be another type of library.
375 * `executable`: Generates an executable file.
376 * `group`: A virtual dependency node that refers to one or more other
378 * `shared_library`: A .dll or .so.
379 * `source_set`: A lightweight virtual static library (usually
380 preferrable over a real static library since it will build faster).
381 * `static_library`: A .lib or .a file (normally you'll want a
382 source\_set instead).
383 * `test`: Generates an executable but annotates it as a test.
385 You can extend this to make custom target types using templates (see below).
389 Configs are named objects that specify sets of flags, include
390 directories, and defines. They can be applied to a target and pushed to
397 includes = [ "src/include" ]
398 defines = [ "ENABLE_DOOM_MELON" ]
402 To apply a config to a target:
405 executable("doom_melon") {
406 configs = [ ":myconfig" ]
410 It is common for the build config file to specify target defaults that
411 set a default list of configs. Targets can add or remove to this list as
412 needed. So in practice you would usually use `configs += ":myconfig"` to
413 append to the list of defaults.
415 See `gn help config` for more information about how configs are declared
420 A target can apply settings to other targets that depend on it. The most
421 common example is a third party target that requires some defines or
422 include directories for its headers to compile properly. You want these
423 settings to apply both to the compile of the third party library itself,
424 as well as all targets that use the library.
426 To do this, you write a config with the settings you want to apply:
429 config("my_external_library_config") {
431 defines = [ "DISABLE_JANK" ]
435 Then this config is added to the target as a "public" config. It will
436 apply both to the target as well as targets that directly depend on it.
439 shared_library("my_external_library") {
441 # Targets that depend on this get this config applied.
442 public_configs = [ ":my_external_library_config" ]
446 Dependent targets can in turn forward this up the dependency tree
447 another level by adding your target as a "public" dependency.
450 static_library("intermediate_library") {
452 # Targets that depend on this one also get the configs from "my external library".
453 public_deps = [ ":my_external_library" ]
457 A target can forward a config to all dependents until a link boundary is
458 reached by setting it as an `all_dependent_config`. This is strongly
463 A toolchain is a set of build commands to run for different types of
464 input files and link tasks.
466 You can have multiple toolchains in the build. It's easiest to think
467 about each one as completely separate builds that can additionally have
468 dependencies between them. This means, for example, that the 32-bit
469 Windows build might depend on a 64-bit helper target. Each of them can
470 depend on `"//base:base"` which will be the 32-bit base in the context
471 of the 32-bit toolchain, and the 64-bit base in the context of the
474 When a target specifies a dependency on another target, the current
475 toolchain is inherited unless it is explicitly overridden (see "Labels"
478 ### Toolchains and the build configuration
480 When you have a simple build with only one toolchain, the build config
481 file is loaded only once at the beginning of the build. It must call
482 `set_default_toolchain` to tell GN the label of the toolchain definition
483 to use. This toolchain definition has the commands to use for the
484 compiler and linker. The `toolchain_args` section of the toolchain
485 definition is ignored.
487 When a target has a dependency on a target using different toolchain, GN
488 will start a build using that secondary toolchain to resolve the target.
489 GN will load the build config file with the arguments specified in the
490 toolchain definition. Since the toolchain is already known, calls to
491 `set_default_toolchain` are ignored.
493 So the toolchain configuration is two-way. In the default toolchain
494 (i.e. the main build target) the configuration flows from the build
495 config file to the toolchain: the build config file looks at the state
496 of the build (OS type, CPU architecture, etc.) and decides which
497 toolchain to use (via `set_default_toolchain`). In secondary toolchains,
498 the configuration flows from the toolchain to the build config file: the
499 `toolchain_args` in the toolchain definition specifies the arguments to
502 ### Toolchain example
504 Say the default build is a 64-bit build. Either this is the default CPU
505 architecture based on the current system, or the user has passed
506 `target_cpu="x64"` on the command line. The build config file might look
507 like this to set up the default toolchain:
510 # Set default toolchain only has an effect when run in the context of
511 # the default toolchain. Pick the right one according to the current CPU
513 if (target_cpu == "x64") {
514 set_default_toolchain("//toolchains:64")
515 } else if (target_cpu == "x86") {
516 set_default_toolchain("//toolchains:32")
520 If a 64-bit target wants to depend on a 32-bit binary, it would specify
521 a dependency using `datadeps` (data deps are like deps that are only
522 needed at runtime and aren't linked, since you can't link a 32-bit and a
526 executable("my_program") {
528 if (target_cpu == "x64") {
529 # The 64-bit build needs this 32-bit helper.
530 datadeps = [ ":helper(//toolchains:32)" ]
534 if (target_cpu == "x86") {
535 # Our helper library is only compiled in 32-bits.
536 shared_library("helper") {
542 The toolchain file referenced above (`toolchains/BUILD.gn`) would define
552 # Arguments to the build when re-invoking as a secondary toolchain.
554 toolchain_cpu = "x86"
564 # Arguments to the build when re-invoking as a secondary toolchain.
566 toolchain_cpu = "x64"
571 The toolchain args specifies the CPU architecture explicitly, so if a
572 target depends on something using that toolchain, that cpu architecture
573 will be set when re-invoking the build. These args are ignored for the
574 default toolchain since by the time they're known the build config has
575 already been run. In general, the toolchain args and the conditions used
576 to set the default toolchain should agree.
578 The nice thing about the multiple-build setup is that you can write
579 conditionals in your targets referencing the current toolchain state.
580 The build files will be re-run with different state for each toolchain.
581 For the `my_program` example above, you can see it queries the CPU
582 architecture, adding a dependency only for the 64-bit build of the
583 program. The 32-bit build would not get this dependency.
585 ### Declaring a toolchain
587 Toolchains are declared with the `toolchain` command, which sets the
588 commands to use for each compile and link operation. The toolchain also
589 specifies a set of arguments to pass to the build config file when
590 executing. This allows you to pass configuration information to the
595 Templates are GN's primary way to re-use code. Typically, a template
596 would expand to one or more other target types.
599 # Declares static library consisting of rules to build all of the IDL files into
602 source_set(target_name) {
608 Typically your template definition would go in a `.gni` file and users
609 would import that file to see the template definition:
612 import("//tools/idl_compiler.gni")
614 idl("my_interfaces") {
615 sources = [ "a.idl", "b.idl" ]
619 Declaring a template creates a closure around the variables in scope at
620 that time. When the template is invoked, the magic variable `invoker` is
621 used to read variables out of the invoking scope. The template would
622 generally copy the values its interested in into its own scope:
626 source_set(target_name) {
627 sources = invoker.sources
632 The current directory when a template executes will be that of the
633 invoking build file rather than the template source file. This is so
634 files passed in from the template invoker will be correct (this
635 generally accounts for most file handling in a template). However, if
636 the template has files itself (perhaps it generates an action that runs
637 a script), you will want to use absolute paths ("//foo/...") to refer to
638 these files to account for the fact that the current directory will be
639 unpredictable during invocation. See `gn help template` for more
640 information and more complete examples.
646 You can import `.gni` files into the current scope with the `import`
647 function. This is _not_ an include. The imported file is executed
648 independently and the resulting scope is copied into the current file.
649 This allows the results of the import to be cached, and also prevents
650 some of the more "creative" uses of includes.
652 Typically, a `.gni` would define build arguments and templates. See `gn
653 help import` for more.
657 Often you will want to make a file name or a list of file names relative
658 to a different directory. This is especially common when running
659 scripts, which are executed with the build output directory as the
660 current directory, while build files usually refer to files relative to
661 their containing directory.
663 You can use `rebase_path` to convert directories. See `gn help
664 rebase_path` for more help and examples. Typical usage to convert a file
665 name relative to the current directory to be relative to the root build
666 directory would be: ``` new_paths = rebase_path("myfile.c",
671 Patterns are used to generate the output file names for a given set of
672 inputs for custom target types, and to automatically remove files from
673 the `sources` variable (see `gn help set_sources_assignment_filter`).
675 They are like simple regular expressions. See `gn help patterns` for more.
677 ### Executing scripts
679 There are two ways to execute scripts. All external scripts in GN are in
680 Python. The first way is as a build step. Such a script would take some
681 input and generate some output as part of the build. Targets that invoke
682 scripts are declared with the "action" target type (see `gn help
685 The second way to execute scripts is synchronously during build file
686 execution. This is necessary in some cases to determine the set of files
687 to compile, or to get certain system configurations that the build file
688 might depend on. The build file can read the stdout of the script and
689 act on it in different ways.
691 Synchronous script execution is done by the `exec_script` function (see
692 `gn help exec_script` for details and examples). Because synchronously
693 executing a script requires that the current buildfile execution be
694 suspended until a Python process completes execution, relying on
695 external scripts is slow and should be minimized.
697 You can synchronously read and write files which is occasionally
698 necessary when synchronously running scripts. The typical use-case would
699 be to pass a list of file names longer than the command-line limits of
700 the current platform. See `gn help read_file` and `gn help write_file`
701 for how to read and write files. These functions should be avoided if at
704 # Differences and similarities to Blaze
706 [Blaze](http://google-engtools.blogspot.com/2011/08/build-in-cloud-how-build-system-works.html)
707 is Google's internal build system. It has inspired a number of other
709 [Pants](https://github.com/twitter/commons/tree/master/src/python/twitter/pants)
710 and [Buck](http://facebook.github.io/buck/).
712 In Google's homogeneous environment, the need for conditionals is very
713 low and they can get by with a few hacks (`abi_deps`). Chrome uses
714 conditionals all over the place and the need to add these is the main
715 reason for the files looking different.
717 GN also adds the concept of "configs" to manage some of the trickier
718 dependency and configuration problems which likewise don't arise on the
719 server. Blaze has a concept of a "configuration" which is like a GN
720 toolchain, but built into the tool itself. The way that toolchains work
721 in GN is a result of trying to separate this concept out into the build
722 files in a clean way.
724 GN keeps some GYP concept like "all dependent" and "direct dependent"
725 settings which work a bit differently in Blaze. This is partially to
726 make conversion from the existing GYP code easier, and the GYP
727 constructs generally offer more fine-grained control (which is either
728 good or bad, depending on the situation).
730 GN also uses GYP names like "sources" instead of "srcs" since
731 abbreviating this seems needlessly obscure, although it uses Blaze's
732 "deps" since "dependencies" is so hard to type. Chromium also compiles
733 multiple languages in one target so specifying the language type on the
734 target name prefix was dropped (e.g. from `cc_library`).