1# GN Reference 2 3*This page is automatically generated from* `gn help --markdown all`. 4 5## Contents 6 7* [Commands](#commands) 8 * [analyze: Analyze which targets are affected by a list of files.](#cmd_analyze) 9 * [args: Display or configure arguments declared by the build.](#cmd_args) 10 * [check: Check header dependencies.](#cmd_check) 11 * [clean: Cleans the output directory.](#cmd_clean) 12 * [clean_stale: Cleans the stale output files from the output directory.](#cmd_clean_stale) 13 * [desc: Show lots of insightful information about a target or config.](#cmd_desc) 14 * [format: Format .gn files.](#cmd_format) 15 * [gen: Generate ninja files.](#cmd_gen) 16 * [help: Does what you think.](#cmd_help) 17 * [ls: List matching targets.](#cmd_ls) 18 * [meta: List target metadata collection results.](#cmd_meta) 19 * [outputs: Which files a source/target make.](#cmd_outputs) 20 * [path: Find paths between two targets.](#cmd_path) 21 * [refs: Find stuff referencing a target or file.](#cmd_refs) 22* [Target declarations](#targets) 23 * [action: Declare a target that runs a script a single time.](#func_action) 24 * [action_foreach: Declare a target that runs a script over a set of files.](#func_action_foreach) 25 * [bundle_data: [iOS/macOS] Declare a target without output.](#func_bundle_data) 26 * [copy: Declare a target that copies files.](#func_copy) 27 * [create_bundle: [iOS/macOS] Build an iOS or macOS bundle.](#func_create_bundle) 28 * [executable: Declare an executable target.](#func_executable) 29 * [generated_file: Declare a generated_file target.](#func_generated_file) 30 * [group: Declare a named group of targets.](#func_group) 31 * [loadable_module: Declare a loadable module target.](#func_loadable_module) 32 * [rust_library: Declare a Rust library target.](#func_rust_library) 33 * [rust_proc_macro: Declare a Rust procedural macro target.](#func_rust_proc_macro) 34 * [shared_library: Declare a shared library target.](#func_shared_library) 35 * [source_set: Declare a source set target.](#func_source_set) 36 * [static_library: Declare a static library target.](#func_static_library) 37 * [target: Declare an target with the given programmatic type.](#func_target) 38* [Buildfile functions](#functions) 39 * [assert: Assert an expression is true at generation time.](#func_assert) 40 * [config: Defines a configuration object.](#func_config) 41 * [declare_args: Declare build arguments.](#func_declare_args) 42 * [defined: Returns whether an identifier is defined.](#func_defined) 43 * [exec_script: Synchronously run a script and return the output.](#func_exec_script) 44 * [filter_exclude: Remove values that match a set of patterns.](#func_filter_exclude) 45 * [filter_include: Remove values that do not match a set of patterns.](#func_filter_include) 46 * [foreach: Iterate over a list.](#func_foreach) 47 * [forward_variables_from: Copies variables from a different scope.](#func_forward_variables_from) 48 * [get_label_info: Get an attribute from a target's label.](#func_get_label_info) 49 * [get_path_info: Extract parts of a file or directory name.](#func_get_path_info) 50 * [get_target_outputs: [file list] Get the list of outputs from a target.](#func_get_target_outputs) 51 * [getenv: Get an environment variable.](#func_getenv) 52 * [import: Import a file into the current scope.](#func_import) 53 * [not_needed: Mark variables from scope as not needed.](#func_not_needed) 54 * [pool: Defines a pool object.](#func_pool) 55 * [print: Prints to the console.](#func_print) 56 * [process_file_template: Do template expansion over a list of files.](#func_process_file_template) 57 * [read_file: Read a file into a variable.](#func_read_file) 58 * [rebase_path: Rebase a file or directory to another location.](#func_rebase_path) 59 * [set_default_toolchain: Sets the default toolchain name.](#func_set_default_toolchain) 60 * [set_defaults: Set default values for a target type.](#func_set_defaults) 61 * [split_list: Splits a list into N different sub-lists.](#func_split_list) 62 * [string_join: Concatenates a list of strings with a separator.](#func_string_join) 63 * [string_replace: Replaces substring in the given string.](#func_string_replace) 64 * [string_split: Split string into a list of strings.](#func_string_split) 65 * [template: Define a template rule.](#func_template) 66 * [tool: Specify arguments to a toolchain tool.](#func_tool) 67 * [toolchain: Defines a toolchain.](#func_toolchain) 68 * [write_file: Write a file to disk.](#func_write_file) 69* [Built-in predefined variables](#predefined_variables) 70 * [current_cpu: [string] The processor architecture of the current toolchain.](#var_current_cpu) 71 * [current_os: [string] The operating system of the current toolchain.](#var_current_os) 72 * [current_toolchain: [string] Label of the current toolchain.](#var_current_toolchain) 73 * [default_toolchain: [string] Label of the default toolchain.](#var_default_toolchain) 74 * [gn_version: [number] The version of gn.](#var_gn_version) 75 * [host_cpu: [string] The processor architecture that GN is running on.](#var_host_cpu) 76 * [host_os: [string] The operating system that GN is running on.](#var_host_os) 77 * [invoker: [string] The invoking scope inside a template.](#var_invoker) 78 * [python_path: [string] Absolute path of Python.](#var_python_path) 79 * [root_build_dir: [string] Directory where build commands are run.](#var_root_build_dir) 80 * [root_gen_dir: [string] Directory for the toolchain's generated files.](#var_root_gen_dir) 81 * [root_out_dir: [string] Root directory for toolchain output files.](#var_root_out_dir) 82 * [target_cpu: [string] The desired cpu architecture for the build.](#var_target_cpu) 83 * [target_gen_dir: [string] Directory for a target's generated files.](#var_target_gen_dir) 84 * [target_name: [string] The name of the current target.](#var_target_name) 85 * [target_os: [string] The desired operating system for the build.](#var_target_os) 86 * [target_out_dir: [string] Directory for target output files.](#var_target_out_dir) 87* [Variables you set in targets](#target_variables) 88 * [aliased_deps: [scope] Set of crate-dependency pairs.](#var_aliased_deps) 89 * [all_dependent_configs: [label list] Configs to be forced on dependents.](#var_all_dependent_configs) 90 * [allow_circular_includes_from: [label list] Permit includes from deps.](#var_allow_circular_includes_from) 91 * [arflags: [string list] Arguments passed to static_library archiver.](#var_arflags) 92 * [args: [string list] Arguments passed to an action.](#var_args) 93 * [asmflags: [string list] Flags passed to the assembler.](#var_asmflags) 94 * [assert_no_deps: [label pattern list] Ensure no deps on these targets.](#var_assert_no_deps) 95 * [bridge_header: [string] Path to C/Objective-C compatibility header.](#var_bridge_header) 96 * [bundle_contents_dir: Expansion of {{bundle_contents_dir}} in create_bundle.](#var_bundle_contents_dir) 97 * [bundle_deps_filter: [label list] A list of labels that are filtered out.](#var_bundle_deps_filter) 98 * [bundle_executable_dir: Expansion of {{bundle_executable_dir}} in create_bundle](#var_bundle_executable_dir) 99 * [bundle_resources_dir: Expansion of {{bundle_resources_dir}} in create_bundle.](#var_bundle_resources_dir) 100 * [bundle_root_dir: Expansion of {{bundle_root_dir}} in create_bundle.](#var_bundle_root_dir) 101 * [cflags: [string list] Flags passed to all C compiler variants.](#var_cflags) 102 * [cflags_c: [string list] Flags passed to the C compiler.](#var_cflags_c) 103 * [cflags_cc: [string list] Flags passed to the C++ compiler.](#var_cflags_cc) 104 * [cflags_objc: [string list] Flags passed to the Objective C compiler.](#var_cflags_objc) 105 * [cflags_objcc: [string list] Flags passed to the Objective C++ compiler.](#var_cflags_objcc) 106 * [check_includes: [boolean] Controls whether a target's files are checked.](#var_check_includes) 107 * [code_signing_args: [string list] Arguments passed to code signing script.](#var_code_signing_args) 108 * [code_signing_outputs: [file list] Output files for code signing step.](#var_code_signing_outputs) 109 * [code_signing_script: [file name] Script for code signing.](#var_code_signing_script) 110 * [code_signing_sources: [file list] Sources for code signing step.](#var_code_signing_sources) 111 * [complete_static_lib: [boolean] Links all deps into a static library.](#var_complete_static_lib) 112 * [configs: [label list] Configs applying to this target or config.](#var_configs) 113 * [contents: Contents to write to file.](#var_contents) 114 * [crate_name: [string] The name for the compiled crate.](#var_crate_name) 115 * [crate_root: [string] The root source file for a binary or library.](#var_crate_root) 116 * [crate_type: [string] The type of linkage to use on a shared_library.](#var_crate_type) 117 * [data: [file list] Runtime data file dependencies.](#var_data) 118 * [data_deps: [label list] Non-linked dependencies.](#var_data_deps) 119 * [data_keys: [string list] Keys from which to collect metadata.](#var_data_keys) 120 * [defines: [string list] C preprocessor defines.](#var_defines) 121 * [depfile: [string] File name for input dependencies for actions.](#var_depfile) 122 * [deps: [label list] Private linked dependencies.](#var_deps) 123 * [externs: [scope] Set of Rust crate-dependency pairs.](#var_externs) 124 * [framework_dirs: [directory list] Additional framework search directories.](#var_framework_dirs) 125 * [frameworks: [name list] Name of frameworks that must be linked.](#var_frameworks) 126 * [friend: [label pattern list] Allow targets to include private headers.](#var_friend) 127 * [include_dirs: [directory list] Additional include directories.](#var_include_dirs) 128 * [inputs: [file list] Additional compile-time dependencies.](#var_inputs) 129 * [ldflags: [string list] Flags passed to the linker.](#var_ldflags) 130 * [lib_dirs: [directory list] Additional library directories.](#var_lib_dirs) 131 * [libs: [string list] Additional libraries to link.](#var_libs) 132 * [metadata: [scope] Metadata of this target.](#var_metadata) 133 * [module_name: [string] The name for the compiled module.](#var_module_name) 134 * [output_conversion: Data format for generated_file targets.](#var_output_conversion) 135 * [output_dir: [directory] Directory to put output file in.](#var_output_dir) 136 * [output_extension: [string] Value to use for the output's file extension.](#var_output_extension) 137 * [output_name: [string] Name for the output file other than the default.](#var_output_name) 138 * [output_prefix_override: [boolean] Don't use prefix for output name.](#var_output_prefix_override) 139 * [outputs: [file list] Output files for actions and copy targets.](#var_outputs) 140 * [partial_info_plist: [filename] Path plist from asset catalog compiler.](#var_partial_info_plist) 141 * [pool: [string] Label of the pool used by the action.](#var_pool) 142 * [precompiled_header: [string] Header file to precompile.](#var_precompiled_header) 143 * [precompiled_header_type: [string] "gcc" or "msvc".](#var_precompiled_header_type) 144 * [precompiled_source: [file name] Source file to precompile.](#var_precompiled_source) 145 * [product_type: [string] Product type for Xcode projects.](#var_product_type) 146 * [public: [file list] Declare public header files for a target.](#var_public) 147 * [public_configs: [label list] Configs applied to dependents.](#var_public_configs) 148 * [public_deps: [label list] Declare public dependencies.](#var_public_deps) 149 * [rebase: [boolean] Rebase collected metadata as files.](#var_rebase) 150 * [response_file_contents: [string list] Contents of .rsp file for actions.](#var_response_file_contents) 151 * [script: [file name] Script file for actions.](#var_script) 152 * [sources: [file list] Source files for a target.](#var_sources) 153 * [swiftflags: [string list] Flags passed to the swift compiler.](#var_swiftflags) 154 * [testonly: [boolean] Declares a target must only be used for testing.](#var_testonly) 155 * [visibility: [label list] A list of labels that can depend on a target.](#var_visibility) 156 * [walk_keys: [string list] Key(s) for managing the metadata collection walk.](#var_walk_keys) 157 * [weak_frameworks: [name list] Name of frameworks that must be weak linked.](#var_weak_frameworks) 158 * [write_runtime_deps: Writes the target's runtime_deps to the given path.](#var_write_runtime_deps) 159 * [xcasset_compiler_flags: [string list] Flags passed to xcassets compiler](#var_xcasset_compiler_flags) 160 * [xcode_extra_attributes: [scope] Extra attributes for Xcode projects.](#var_xcode_extra_attributes) 161 * [xcode_test_application_name: [string] Name for Xcode test target.](#var_xcode_test_application_name) 162* [Other help topics](#other) 163 * all: Print all the help at once 164 * [buildargs: How build arguments work.](#buildargs) 165 * [dotfile: Info about the toplevel .gn file.](#dotfile) 166 * [execution: Build graph and execution overview.](#execution) 167 * [grammar: Language and grammar for GN build files.](#grammar) 168 * [input_conversion: Processing input from exec_script and read_file.](#io_conversion) 169 * [file_pattern: Matching more than one file.](#file_pattern) 170 * [label_pattern: Matching more than one label.](#label_pattern) 171 * [labels: About labels.](#labels) 172 * [metadata_collection: About metadata and its collection.](#metadata_collection) 173 * [ninja_rules: How Ninja build rules are named.](#ninja_rules) 174 * [nogncheck: Annotating includes for checking.](#nogncheck) 175 * [output_conversion: Specifies how to transform a value to output.](#io_conversion) 176 * [runtime_deps: How runtime dependency computation works.](#runtime_deps) 177 * [source_expansion: Map sources to outputs for scripts.](#source_expansion) 178 * [switches: Show available command-line switches.](#switch_list) 179 180## <a name="commands"></a>Commands 181 182### <a name="cmd_analyze"></a>**gn analyze <out_dir> <input_path> <output_path>** 183 184``` 185 Analyze which targets are affected by a list of files. 186 187 This command takes three arguments: 188 189 out_dir is the path to the build directory. 190 191 input_path is a path to a file containing a JSON object with three fields: 192 193 - "files": A list of the filenames to check. 194 195 - "test_targets": A list of the labels for targets that are needed to run 196 the tests we wish to run. 197 198 - "additional_compile_targets" (optional): A list of the labels for targets 199 that we wish to rebuild, but aren't necessarily needed for testing. The 200 important difference between this field and "test_targets" is that if an 201 item in the additional_compile_targets list refers to a group, then any 202 dependencies of that group will be returned if they are out of date, but 203 the group itself does not need to be. If the dependencies themselves are 204 groups, the same filtering is repeated. This filtering can be used to 205 avoid rebuilding dependencies of a group that are unaffected by the input 206 files. The list may also contain the string "all" to refer to a 207 pseudo-group that contains every root target in the build graph. 208 209 This filtering behavior is also known as "pruning" the list of compile 210 targets. 211 212 If "additional_compile_targets" is absent, it defaults to the empty list. 213 214 If input_path is -, input is read from stdin. 215 216 output_path is a path indicating where the results of the command are to be 217 written. The results will be a file containing a JSON object with one or more 218 of following fields: 219 220 - "compile_targets": A list of the labels derived from the input 221 compile_targets list that are affected by the input files. Due to the way 222 the filtering works for compile targets as described above, this list may 223 contain targets that do not appear in the input list. 224 225 - "test_targets": A list of the labels from the input test_targets list that 226 are affected by the input files. This list will be a proper subset of the 227 input list. 228 229 - "invalid_targets": A list of any names from the input that do not exist in 230 the build graph. If this list is non-empty, the "error" field will also be 231 set to "Invalid targets". 232 233 - "status": A string containing one of three values: 234 235 - "Found dependency" 236 - "No dependency" 237 - "Found dependency (all)" 238 239 In the first case, the lists returned in compile_targets and test_targets 240 should be passed to ninja to build. In the second case, nothing was 241 affected and no build is necessary. In the third case, GN could not 242 determine the correct answer and returned the input as the output in order 243 to be safe. 244 245 - "error": This will only be present if an error occurred, and will contain 246 a string describing the error. This includes cases where the input file is 247 not in the right format, or contains invalid targets. 248 249 If output_path is -, output is written to stdout. 250 251 The command returns 1 if it is unable to read the input file or write the 252 output file, or if there is something wrong with the build such that gen 253 would also fail, and 0 otherwise. In particular, it returns 0 even if the 254 "error" key is non-empty and a non-fatal error occurred. In other words, it 255 tries really hard to always write something to the output JSON and convey 256 errors that way rather than via return codes. 257``` 258### <a name="cmd_args"></a>**gn args**: (command-line tool) 259 260``` 261 Display or configure arguments declared by the build. 262 263 gn args <out_dir> [--list] [--short] [--args] [--overrides-only] 264 265 See also "gn help buildargs" for a more high-level overview of how 266 build arguments work. 267``` 268 269#### **Usage** 270 271``` 272 gn args <out_dir> 273 Open the arguments for the given build directory in an editor. If the 274 given build directory doesn't exist, it will be created and an empty args 275 file will be opened in the editor. You would type something like this 276 into that file: 277 enable_doom_melon=false 278 os="android" 279 280 To find your editor on Posix, GN will search the environment variables in 281 order: GN_EDITOR, VISUAL, and EDITOR. On Windows GN will open the command 282 associated with .txt files. 283 284 Note: you can edit the build args manually by editing the file "args.gn" 285 in the build directory and then running "gn gen <out_dir>". 286 287 gn args <out_dir> --list[=<exact_arg>] [--short] [--overrides-only] [--json] 288 Lists all build arguments available in the current configuration, or, if 289 an exact_arg is specified for the list flag, just that one build 290 argument. 291 292 The output will list the declaration location, current value for the 293 build, default value (if different than the current value), and comment 294 preceding the declaration. 295 296 If --short is specified, only the names and current values will be 297 printed. 298 299 If --overrides-only is specified, only the names and current values of 300 arguments that have been overridden (i.e. non-default arguments) will 301 be printed. Overrides come from the <out_dir>/args.gn file and //.gn 302 303 If --json is specified, the output will be emitted in json format. 304 JSON schema for output: 305 [ 306 { 307 "name": variable_name, 308 "current": { 309 "value": overridden_value, 310 "file": file_name, 311 "line": line_no 312 }, 313 "default": { 314 "value": default_value, 315 "file": file_name, 316 "line": line_no 317 }, 318 "comment": comment_string 319 }, 320 ... 321 ] 322``` 323 324#### **Examples** 325 326``` 327 gn args out/Debug 328 Opens an editor with the args for out/Debug. 329 330 gn args out/Debug --list --short 331 Prints all arguments with their default values for the out/Debug 332 build. 333 334 gn args out/Debug --list --short --overrides-only 335 Prints overridden arguments for the out/Debug build. 336 337 gn args out/Debug --list=target_cpu 338 Prints information about the "target_cpu" argument for the " 339 "out/Debug 340 build. 341 342 gn args --list --args="os=\"android\" enable_doom_melon=true" 343 Prints all arguments with the default values for a build with the 344 given arguments set (which may affect the values of other 345 arguments). 346``` 347### <a name="cmd_check"></a>**gn check <out_dir> [<label_pattern>] [\--force] [\--check-generated]** 348 349``` 350 GN's include header checker validates that the includes for C-like source 351 files match the build dependency graph. 352 353 "gn check" is the same thing as "gn gen" with the "--check" flag except that 354 this command does not write out any build files. It's intended to be an easy 355 way to manually trigger include file checking. 356 357 The <label_pattern> can take exact labels or patterns that match more than 358 one (although not general regular expressions). If specified, only those 359 matching targets will be checked. See "gn help label_pattern" for details. 360``` 361 362#### **Command-specific switches** 363 364``` 365 --check-generated 366 Generated files are normally not checked since they do not exist 367 until after a build. With this flag, those generated files that 368 can be found on disk are also checked. 369 370 --check-system 371 Check system style includes (using <angle brackets>) in addition to 372 "double quote" includes. 373 374 --default-toolchain 375 Normally wildcard targets are matched in all toolchains. This 376 switch makes wildcard labels with no explicit toolchain reference 377 only match targets in the default toolchain. 378 379 Non-wildcard inputs with no explicit toolchain specification will 380 always match only a target in the default toolchain if one exists. 381 382 --force 383 Ignores specifications of "check_includes = false" and checks all 384 target's files that match the target label. 385``` 386 387#### **What gets checked** 388 389``` 390 The .gn file may specify a list of targets to be checked in the list 391 check_targets (see "gn help dotfile"). Alternatively, the .gn file may 392 specify a list of targets not to be checked in no_check_targets. If a label 393 pattern is specified on the command line, neither check_targets or 394 no_check_targets is used. 395 396 Targets can opt-out from checking with "check_includes = false" (see 397 "gn help check_includes"). 398 399 For targets being checked: 400 401 - GN opens all C-like source files in the targets to be checked and scans 402 the top for includes. 403 404 - Generated files (that might not exist yet) are ignored unless 405 the --check-generated flag is provided. 406 407 - Includes with a "nogncheck" annotation are skipped (see 408 "gn help nogncheck"). 409 410 - Includes using "quotes" are always checked. 411 If system style checking is enabled, includes using <angle brackets> 412 are also checked. 413 414 - Include paths are assumed to be relative to any of the "include_dirs" for 415 the target (including the implicit current dir). 416 417 - GN does not run the preprocessor so will not understand conditional 418 includes. 419 420 - Only includes matching known files in the build are checked: includes 421 matching unknown paths are ignored. 422 423 For an include to be valid: 424 425 - The included file must be in the current target, or there must be a path 426 following only public dependencies to a target with the file in it 427 ("gn path" is a good way to diagnose problems). 428 429 - There can be multiple targets with an included file: only one needs to be 430 valid for the include to be allowed. 431 432 - If there are only "sources" in a target, all are considered to be public 433 and can be included by other targets with a valid public dependency path. 434 435 - If a target lists files as "public", only those files are able to be 436 included by other targets. Anything in the sources will be considered 437 private and will not be includable regardless of dependency paths. 438 439 - Outputs from actions are treated like public sources on that target. 440 441 - A target can include headers from a target that depends on it if the 442 other target is annotated accordingly. See "gn help 443 allow_circular_includes_from". 444``` 445 446#### **Advice on fixing problems** 447 448``` 449 If you have a third party project that is difficult to fix or doesn't care 450 about include checks it's generally best to exclude that target from checking 451 altogether via "check_includes = false". 452 453 If you have conditional includes, make sure the build conditions and the 454 preprocessor conditions match, and annotate the line with "nogncheck" (see 455 "gn help nogncheck" for an example). 456 457 If two targets are hopelessly intertwined, use the 458 "allow_circular_includes_from" annotation. Ideally each should have identical 459 dependencies so configs inherited from those dependencies are consistent (see 460 "gn help allow_circular_includes_from"). 461 462 If you have a standalone header file or files that need to be shared between 463 a few targets, you can consider making a source_set listing only those 464 headers as public sources. With only header files, the source set will be a 465 no-op from a build perspective, but will give a central place to refer to 466 those headers. That source set's files will still need to pass "gn check" in 467 isolation. 468 469 In rare cases it makes sense to list a header in more than one target if it 470 could be considered conceptually a member of both. 471``` 472 473#### **Examples** 474 475``` 476 gn check out/Debug 477 Check everything. 478 479 gn check out/Default //foo:bar 480 Check only the files in the //foo:bar target. 481 482 gn check out/Default "//foo/* 483 Check only the files in targets in the //foo directory tree. 484``` 485### <a name="cmd_clean"></a>**gn clean <out_dir>...** 486 487``` 488 Deletes the contents of the output directory except for args.gn and 489 creates a Ninja build environment sufficient to regenerate the build. 490``` 491### <a name="cmd_clean_stale"></a>**gn clean_stale [\--ninja-executable=...] <out_dir>...** 492 493``` 494 Removes the no longer needed output files from the build directory and prunes 495 their records from the ninja build log and dependency database. These are 496 output files that were generated from previous builds, but the current build 497 graph no longer references them. 498 499 This command requires a ninja executable of at least version 1.10.0. The 500 executable must be provided by the --ninja-executable switch. 501``` 502 503#### **Options** 504 505``` 506 --ninja-executable=<string> 507 Can be used to specify the ninja executable to use. 508``` 509### <a name="cmd_desc"></a>**gn desc** 510 511``` 512 gn desc <out_dir> <label or pattern> [<what to show>] [--blame] 513 [--format=json] 514 515 Displays information about a given target or config. The build parameters 516 will be taken for the build in the given <out_dir>. 517 518 The <label or pattern> can be a target label, a config label, or a label 519 pattern (see "gn help label_pattern"). A label pattern will only match 520 targets. 521``` 522 523#### **Possibilities for <what to show>** 524 525``` 526 (If unspecified an overall summary will be displayed.) 527 528 all_dependent_configs 529 allow_circular_includes_from 530 arflags [--blame] 531 args 532 cflags [--blame] 533 cflags_c [--blame] 534 cflags_cc [--blame] 535 check_includes 536 configs [--tree] (see below) 537 data_keys 538 defines [--blame] 539 depfile 540 deps [--all] [--tree] (see below) 541 framework_dirs 542 frameworks 543 include_dirs [--blame] 544 inputs 545 ldflags [--blame] 546 lib_dirs 547 libs 548 metadata 549 output_conversion 550 outputs 551 public_configs 552 public 553 rebase 554 script 555 sources 556 testonly 557 visibility 558 walk_keys 559 weak_frameworks 560 561 runtime_deps 562 Compute all runtime deps for the given target. This is a computed list 563 and does not correspond to any GN variable, unlike most other values 564 here. 565 566 The output is a list of file names relative to the build directory. See 567 "gn help runtime_deps" for how this is computed. This also works with 568 "--blame" to see the source of the dependency. 569``` 570 571#### **Shared flags** 572 573``` 574 --default-toolchain 575 Normally wildcard targets are matched in all toolchains. This 576 switch makes wildcard labels with no explicit toolchain reference 577 only match targets in the default toolchain. 578 579 Non-wildcard inputs with no explicit toolchain specification will 580 always match only a target in the default toolchain if one exists. 581 582 --format=json 583 Format the output as JSON instead of text. 584``` 585 586#### **Target flags** 587 588``` 589 --blame 590 Used with any value specified on a config, this will name the config that 591 causes that target to get the flag. This doesn't currently work for libs, 592 lib_dirs, frameworks, weak_frameworks and framework_dirs because those are 593 inherited and are more complicated to figure out the blame (patches 594 welcome). 595``` 596 597#### **Configs** 598 599``` 600 The "configs" section will list all configs that apply. For targets this will 601 include configs specified in the "configs" variable of the target, and also 602 configs pushed onto this target via public or "all dependent" configs. 603 604 Configs can have child configs. Specifying --tree will show the hierarchy. 605``` 606 607#### **Printing outputs** 608 609``` 610 The "outputs" section will list all outputs that apply, including the outputs 611 computed from the tool definition (eg for "executable", "static_library", ... 612 targets). 613``` 614 615#### **Printing deps** 616 617``` 618 Deps will include all public, private, and data deps (TODO this could be 619 clarified and enhanced) sorted in order applying. The following may be used: 620 621 --all 622 Collects all recursive dependencies and prints a sorted flat list. Also 623 usable with --tree (see below). 624 625 --as=(buildfile|label|output) 626 How to print targets. 627 628 buildfile 629 Prints the build files where the given target was declared as 630 file names. 631 label (default) 632 Prints the label of the target. 633 output 634 Prints the first output file for the target relative to the 635 root build directory. 636 637 --testonly=(true|false) 638 Restrict outputs to targets with the testonly flag set 639 accordingly. When unspecified, the target's testonly flags are 640 ignored. 641 642 --tree 643 Print a dependency tree. By default, duplicates will be elided with "..." 644 but when --all and -tree are used together, no eliding will be performed. 645 646 The "deps", "public_deps", and "data_deps" will all be included in the 647 tree. 648 649 Tree output can not be used with the filtering or output flags: --as, 650 --type, --testonly. 651 652 --type=(action|copy|executable|group|loadable_module|shared_library| 653 source_set|static_library) 654 Restrict outputs to targets matching the given type. If 655 unspecified, no filtering will be performed. 656``` 657 658#### **Note** 659 660``` 661 This command will show the full name of directories and source files, but 662 when directories and source paths are written to the build file, they will be 663 adjusted to be relative to the build directory. So the values for paths 664 displayed by this command won't match (but should mean the same thing). 665``` 666 667#### **Examples** 668 669``` 670 gn desc out/Debug //base:base 671 Summarizes the given target. 672 673 gn desc out/Foo :base_unittests deps --tree 674 Shows a dependency tree of the "base_unittests" project in 675 the current directory. 676 677 gn desc out/Debug //base defines --blame 678 Shows defines set for the //base:base target, annotated by where 679 each one was set from. 680``` 681### <a name="cmd_format"></a>**gn format [\--dump-tree] (\--stdin | <list of build_files...>)** 682 683``` 684 Formats .gn file to a standard format. 685 686 The contents of some lists ('sources', 'deps', etc.) will be sorted to a 687 canonical order. To suppress this, you can add a comment of the form "# 688 NOSORT" immediately preceding the assignment. e.g. 689 690 # NOSORT 691 sources = [ 692 "z.cc", 693 "a.cc", 694 ] 695``` 696 697#### **Arguments** 698 699``` 700 --dry-run 701 Prints the list of files that would be reformatted but does not write 702 anything to disk. This is useful for presubmit/lint-type checks. 703 - Exit code 0: successful format, matches on disk. 704 - Exit code 1: general failure (parse error, etc.) 705 - Exit code 2: successful format, but differs from on disk. 706 707 --dump-tree[=( text | json )] 708 Dumps the parse tree to stdout and does not update the file or print 709 formatted output. If no format is specified, text format will be used. 710 711 --stdin 712 Read input from stdin and write to stdout rather than update a file 713 in-place. 714 715 --read-tree=json 716 Reads an AST from stdin in the format output by --dump-tree=json and 717 uses that as the parse tree. (The only read-tree format currently 718 supported is json.) The given .gn file will be overwritten. This can be 719 used to programmatically transform .gn files. 720``` 721 722#### **Examples** 723``` 724 gn format //some/BUILD.gn //some/other/BUILD.gn //and/another/BUILD.gn 725 gn format some\\BUILD.gn 726 gn format /abspath/some/BUILD.gn 727 gn format --stdin 728 gn format --read-tree=json //rewritten/BUILD.gn 729``` 730### <a name="cmd_gen"></a>**gn gen [\--check] [<ide options>] <out_dir>** 731 732``` 733 Generates ninja files from the current tree and puts them in the given output 734 directory. 735 736 The output directory can be a source-repo-absolute path name such as: 737 //out/foo 738 Or it can be a directory relative to the current directory such as: 739 out/foo 740 741 "gn gen --check" is the same as running "gn check". "gn gen --check=system" is 742 the same as running "gn check --check-system". See "gn help check" for 743 documentation on that mode. 744 745 See "gn help switches" for the common command-line switches. 746``` 747 748#### **General options** 749 750``` 751 --ninja-executable=<string> 752 Can be used to specify the ninja executable to use. This executable will 753 be used as an IDE option to indicate which ninja to use for building. This 754 executable will also be used as part of the gen process for triggering a 755 restat on generated ninja files and for use with --clean-stale. 756 757 --clean-stale 758 This option will cause no longer needed output files to be removed from 759 the build directory, and their records pruned from the ninja build log and 760 dependency database after the ninja build graph has been generated. This 761 option requires a ninja executable of at least version 1.10.0. It can be 762 provided by the --ninja-executable switch. Also see "gn help clean_stale". 763``` 764 765#### **IDE options** 766 767``` 768 GN optionally generates files for IDE. Files won't be overwritten if their 769 contents don't change. Possibilities for <ide options> 770 771 --ide=<ide_name> 772 Generate files for an IDE. Currently supported values: 773 "eclipse" - Eclipse CDT settings file. 774 "vs" - Visual Studio project/solution files. 775 (default Visual Studio version: 2019) 776 "vs2013" - Visual Studio 2013 project/solution files. 777 "vs2015" - Visual Studio 2015 project/solution files. 778 "vs2017" - Visual Studio 2017 project/solution files. 779 "vs2019" - Visual Studio 2019 project/solution files. 780 "xcode" - Xcode workspace/solution files. 781 "qtcreator" - QtCreator project files. 782 "json" - JSON file containing target information 783 784 --filters=<path_prefixes> 785 Semicolon-separated list of label patterns used to limit the set of 786 generated projects (see "gn help label_pattern"). Only matching targets 787 and their dependencies will be included in the solution. Only used for 788 Visual Studio, Xcode and JSON. 789``` 790 791#### **Visual Studio Flags** 792 793``` 794 --sln=<file_name> 795 Override default sln file name ("all"). Solution file is written to the 796 root build directory. 797 798 --no-deps 799 Don't include targets dependencies to the solution. Changes the way how 800 --filters option works. Only directly matching targets are included. 801 802 --winsdk=<sdk_version> 803 Use the specified Windows 10 SDK version to generate project files. 804 As an example, "10.0.15063.0" can be specified to use Creators Update SDK 805 instead of the default one. 806 807 --ninja-executable=<string> 808 Can be used to specify the ninja executable to use when building. 809 810 --ninja-extra-args=<string> 811 This string is passed without any quoting to the ninja invocation 812 command-line. Can be used to configure ninja flags, like "-j". 813``` 814 815#### **Xcode Flags** 816 817``` 818 --xcode-project=<file_name> 819 Override default Xcode project file name ("all"). The project file is 820 written to the root build directory. 821 822 --xcode-build-system=<value> 823 Configure the build system to use for the Xcode project. Supported 824 values are (default to "legacy"): 825 "legacy" - Legacy Build system 826 "new" - New Build System 827 828 --ninja-executable=<string> 829 Can be used to specify the ninja executable to use when building. 830 831 --ninja-extra-args=<string> 832 This string is passed without any quoting to the ninja invocation 833 command-line. Can be used to configure ninja flags, like "-j". 834 835 --ide-root-target=<target_name> 836 Name of the target corresponding to "All" target in Xcode. If unset, 837 "All" invokes ninja without any target and builds everything. 838``` 839 840#### **QtCreator Flags** 841 842``` 843 --ide-root-target=<target_name> 844 Name of the root target for which the QtCreator project will be generated 845 to contain files of it and its dependencies. If unset, the whole build 846 graph will be emitted. 847``` 848 849#### **Eclipse IDE Support** 850 851``` 852 GN DOES NOT generate Eclipse CDT projects. Instead, it generates a settings 853 file which can be imported into an Eclipse CDT project. The XML file contains 854 a list of include paths and defines. Because GN does not generate a full 855 .cproject definition, it is not possible to properly define includes/defines 856 for each file individually. Instead, one set of includes/defines is generated 857 for the entire project. This works fairly well but may still result in a few 858 indexer issues here and there. 859``` 860 861#### **Generic JSON Output** 862 863``` 864 Dumps target information to a JSON file and optionally invokes a 865 python script on the generated file. See the comments at the beginning 866 of json_project_writer.cc and desc_builder.cc for an overview of the JSON 867 file format. 868 869 --json-file-name=<json_file_name> 870 Overrides default file name (project.json) of generated JSON file. 871 872 --json-ide-script=<path_to_python_script> 873 Executes python script after the JSON file is generated or updated with 874 new content. Path can be project absolute (//), system absolute (/) or 875 relative, in which case the output directory will be base. Path to 876 generated JSON file will be first argument when invoking script. 877 878 --json-ide-script-args=<argument> 879 Optional second argument that will passed to executed script. 880``` 881 882#### **Compilation Database** 883 884``` 885 --export-rust-project 886 Produces a rust-project.json file in the root of the build directory 887 This is used for various tools in the Rust ecosystem allowing for the 888 replay of individual compilations independent of the build system. 889 This is an unstable format and likely to change without warning. 890 891 --export-compile-commands[=<target_name1,target_name2...>] 892 Produces a compile_commands.json file in the root of the build directory 893 containing an array of “command objects”, where each command object 894 specifies one way a translation unit is compiled in the project. If a list 895 of target_name is supplied, only targets that are reachable from any 896 target in any build file whose name is target_name will be used for 897 “command objects” generation, otherwise all available targets will be used. 898 This is used for various Clang-based tooling, allowing for the replay of 899 individual compilations independent of the build system. 900 e.g. "foo" will match: 901 - "//path/to/src:foo" 902 - "//other/path:foo" 903 - "//foo:foo" 904 and not match: 905 - "//foo:bar" 906``` 907### <a name="cmd_help"></a>**gn help <anything>** 908 909``` 910 Yo dawg, I heard you like help on your help so I put help on the help in the 911 help. 912 913 You can also use "all" as the parameter to get all help at once. 914``` 915 916#### **Switches** 917 918``` 919 --markdown 920 Format output in markdown syntax. 921``` 922 923#### **Example** 924 925``` 926 gn help --markdown all 927 Dump all help to stdout in markdown format. 928``` 929### <a name="cmd_ls"></a>**gn ls <out_dir> [<label_pattern>] [\--default-toolchain] [\--as=...]** 930``` 931 [--type=...] [--testonly=...] 932 933 Lists all targets matching the given pattern for the given build directory. 934 By default, only targets in the default toolchain will be matched unless a 935 toolchain is explicitly supplied. 936 937 If the label pattern is unspecified, list all targets. The label pattern is 938 not a general regular expression (see "gn help label_pattern"). If you need 939 more complex expressions, pipe the result through grep. 940``` 941 942#### **Options** 943 944``` 945 --as=(buildfile|label|output) 946 How to print targets. 947 948 buildfile 949 Prints the build files where the given target was declared as 950 file names. 951 label (default) 952 Prints the label of the target. 953 output 954 Prints the first output file for the target relative to the 955 root build directory. 956 957 --default-toolchain 958 Normally wildcard targets are matched in all toolchains. This 959 switch makes wildcard labels with no explicit toolchain reference 960 only match targets in the default toolchain. 961 962 Non-wildcard inputs with no explicit toolchain specification will 963 always match only a target in the default toolchain if one exists. 964 965 --testonly=(true|false) 966 Restrict outputs to targets with the testonly flag set 967 accordingly. When unspecified, the target's testonly flags are 968 ignored. 969 970 --type=(action|copy|executable|group|loadable_module|shared_library| 971 source_set|static_library) 972 Restrict outputs to targets matching the given type. If 973 unspecified, no filtering will be performed. 974``` 975 976#### **Examples** 977 978``` 979 gn ls out/Debug 980 Lists all targets in the default toolchain. 981 982 gn ls out/Debug "//base/*" 983 Lists all targets in the directory base and all subdirectories. 984 985 gn ls out/Debug "//base:*" 986 Lists all targets defined in //base/BUILD.gn. 987 988 gn ls out/Debug //base --as=output 989 Lists the build output file for //base:base 990 991 gn ls out/Debug --type=executable 992 Lists all executables produced by the build. 993 994 gn ls out/Debug "//base/*" --as=output | xargs ninja -C out/Debug 995 Builds all targets in //base and all subdirectories. 996``` 997### <a name="cmd_meta"></a>**gn meta** 998 999``` 1000 gn meta <out_dir> <target>* --data=<key>[,<key>*]* [--walk=<key>[,<key>*]*] 1001 [--rebase=<dest dir>] 1002 1003 Lists collected metaresults of all given targets for the given data key(s), 1004 collecting metadata dependencies as specified by the given walk key(s). 1005 1006 See `gn help generated_file` for more information on the walk. 1007``` 1008 1009#### **Arguments** 1010 1011``` 1012 <target(s)> 1013 A list of target labels from which to initiate the walk. 1014 1015 --data 1016 A list of keys from which to extract data. In each target walked, its metadata 1017 scope is checked for the presence of these keys. If present, the contents of 1018 those variable in the scope are appended to the results list. 1019 1020 --walk (optional) 1021 A list of keys from which to control the walk. In each target walked, its 1022 metadata scope is checked for the presence of any of these keys. If present, 1023 the contents of those variables is checked to ensure that it is a label of 1024 a valid dependency of the target and then added to the set of targets to walk. 1025 If the empty string ("") is present in any of these keys, all deps and data_deps 1026 are added to the walk set. 1027 1028 --rebase (optional) 1029 A destination directory onto which to rebase any paths found. If set, all 1030 collected metadata will be rebased onto this path. This option will throw errors 1031 if collected metadata is not a list of strings. 1032``` 1033 1034#### **Examples** 1035 1036``` 1037 gn meta out/Debug "//base/foo" --data=files 1038 Lists collected metaresults for the `files` key in the //base/foo:foo 1039 target and all of its dependency tree. 1040 1041 gn meta out/Debug "//base/foo" --data=files --data=other 1042 Lists collected metaresults for the `files` and `other` keys in the 1043 //base/foo:foo target and all of its dependency tree. 1044 1045 gn meta out/Debug "//base/foo" --data=files --walk=stop 1046 Lists collected metaresults for the `files` key in the //base/foo:foo 1047 target and all of the dependencies listed in the `stop` key (and so on). 1048 1049 gn meta out/Debug "//base/foo" --data=files --rebase="/" 1050 Lists collected metaresults for the `files` key in the //base/foo:foo 1051 target and all of its dependency tree, rebasing the strings in the `files` 1052 key onto the source directory of the target's declaration relative to "/". 1053``` 1054### <a name="cmd_outputs"></a>**gn outputs <out_dir> <list of target or file names...>** 1055 1056``` 1057 Lists the output files corresponding to the given target(s) or file name(s). 1058 There can be multiple outputs because there can be more than one output 1059 generated by a build step, and there can be more than one toolchain matched. 1060 You can also list multiple inputs which will generate a union of all the 1061 outputs from those inputs. 1062 1063 - The input target/file names are relative to the current directory. 1064 1065 - The output file names are relative to the root build directory. 1066 1067 This command is useful for finding a ninja command that will build only a 1068 portion of the build. 1069``` 1070 1071#### **Target outputs** 1072 1073``` 1074 If the parameter is a target name that includes a toolchain, it will match 1075 only that target in that toolchain. If no toolchain is specified, it will 1076 match all targets with that name in any toolchain. 1077 1078 The result will be the outputs specified by that target which could be a 1079 library, executable, output of an action, a stamp file, etc. 1080``` 1081 1082#### **File outputs** 1083 1084``` 1085 If the parameter is a file name it will compute the output for that compile 1086 step for all targets in all toolchains that contain that file as a source 1087 file. 1088 1089 If the source is not compiled (e.g. a header or text file), the command will 1090 produce no output. 1091 1092 If the source is listed as an "input" to a binary target or action will 1093 resolve to that target's outputs. 1094``` 1095 1096#### **Example** 1097 1098``` 1099 gn outputs out/debug some/directory:some_target 1100 Find the outputs of a given target. 1101 1102 gn outputs out/debug src/project/my_file.cc | xargs ninja -C out/debug 1103 Compiles just the given source file in all toolchains it's referenced in. 1104 1105 git diff --name-only | xargs gn outputs out/x64 | xargs ninja -C out/x64 1106 Compiles all files changed in git. 1107``` 1108### <a name="cmd_path"></a>**gn path <out_dir> <target_one> <target_two>** 1109 1110``` 1111 Finds paths of dependencies between two targets. Each unique path will be 1112 printed in one group, and groups will be separate by newlines. The two 1113 targets can appear in either order (paths will be found going in either 1114 direction). 1115 1116 By default, a single path will be printed. If there is a path with only 1117 public dependencies, the shortest public path will be printed. Otherwise, the 1118 shortest path using either public or private dependencies will be printed. If 1119 --with-data is specified, data deps will also be considered. If there are 1120 multiple shortest paths, an arbitrary one will be selected. 1121``` 1122 1123#### **Interesting paths** 1124 1125``` 1126 In a large project, there can be 100's of millions of unique paths between a 1127 very high level and a common low-level target. To make the output more useful 1128 (and terminate in a reasonable time), GN will not revisit sub-paths 1129 previously known to lead to the target. 1130``` 1131 1132#### **Options** 1133 1134``` 1135 --all 1136 Prints all "interesting" paths found rather than just the first one. 1137 Public paths will be printed first in order of increasing length, followed 1138 by non-public paths in order of increasing length. 1139 1140 --public 1141 Considers only public paths. Can't be used with --with-data. 1142 1143 --with-data 1144 Additionally follows data deps. Without this flag, only public and private 1145 linked deps will be followed. Can't be used with --public. 1146``` 1147 1148#### **Example** 1149 1150``` 1151 gn path out/Default //base //gn 1152``` 1153### <a name="cmd_refs"></a>**gn refs** 1154 1155``` 1156 gn refs <out_dir> (<label_pattern>|<label>|<file>|@<response_file>)* [--all] 1157 [--default-toolchain] [--as=...] [--testonly=...] [--type=...] 1158 1159 Finds reverse dependencies (which targets reference something). The input is 1160 a list containing: 1161 1162 - Target label: The result will be which targets depend on it. 1163 1164 - Config label: The result will be which targets list the given config in 1165 its "configs" or "public_configs" list. 1166 1167 - Label pattern: The result will be which targets depend on any target 1168 matching the given pattern. Patterns will not match configs. These are not 1169 general regular expressions, see "gn help label_pattern" for details. 1170 1171 - File name: The result will be which targets list the given file in its 1172 "inputs", "sources", "public", "data", or "outputs". Any input that does 1173 not contain wildcards and does not match a target or a config will be 1174 treated as a file. 1175 1176 - Response file: If the input starts with an "@", it will be interpreted as 1177 a path to a file containing a list of labels or file names, one per line. 1178 This allows us to handle long lists of inputs without worrying about 1179 command line limits. 1180``` 1181 1182#### **Options** 1183 1184``` 1185 --all 1186 When used without --tree, will recurse and display all unique 1187 dependencies of the given targets. For example, if the input is a target, 1188 this will output all targets that depend directly or indirectly on the 1189 input. If the input is a file, this will output all targets that depend 1190 directly or indirectly on that file. 1191 1192 When used with --tree, turns off eliding to show a complete tree. 1193 1194 --as=(buildfile|label|output) 1195 How to print targets. 1196 1197 buildfile 1198 Prints the build files where the given target was declared as 1199 file names. 1200 label (default) 1201 Prints the label of the target. 1202 output 1203 Prints the first output file for the target relative to the 1204 root build directory. 1205 1206 --default-toolchain 1207 Normally wildcard targets are matched in all toolchains. This 1208 switch makes wildcard labels with no explicit toolchain reference 1209 only match targets in the default toolchain. 1210 1211 Non-wildcard inputs with no explicit toolchain specification will 1212 always match only a target in the default toolchain if one exists. 1213 1214 -q 1215 Quiet. If nothing matches, don't print any output. Without this option, if 1216 there are no matches there will be an informational message printed which 1217 might interfere with scripts processing the output. 1218 1219 --testonly=(true|false) 1220 Restrict outputs to targets with the testonly flag set 1221 accordingly. When unspecified, the target's testonly flags are 1222 ignored. 1223 1224 --tree 1225 Outputs a reverse dependency tree from the given target. Duplicates will 1226 be elided. Combine with --all to see a full dependency tree. 1227 1228 Tree output can not be used with the filtering or output flags: --as, 1229 --type, --testonly. 1230 1231 --type=(action|copy|executable|group|loadable_module|shared_library| 1232 source_set|static_library) 1233 Restrict outputs to targets matching the given type. If 1234 unspecified, no filtering will be performed. 1235``` 1236 1237#### **Examples (target input)** 1238 1239``` 1240 gn refs out/Debug //gn:gn 1241 Find all targets depending on the given exact target name. 1242 1243 gn refs out/Debug //base:i18n --as=buildfiles | xargs gvim 1244 Edit all .gn files containing references to //base:i18n 1245 1246 gn refs out/Debug //base --all 1247 List all targets depending directly or indirectly on //base:base. 1248 1249 gn refs out/Debug "//base/*" 1250 List all targets depending directly on any target in //base or 1251 its subdirectories. 1252 1253 gn refs out/Debug "//base:*" 1254 List all targets depending directly on any target in 1255 //base/BUILD.gn. 1256 1257 gn refs out/Debug //base --tree 1258 Print a reverse dependency tree of //base:base 1259``` 1260 1261#### **Examples (file input)** 1262 1263``` 1264 gn refs out/Debug //base/macros.h 1265 Print target(s) listing //base/macros.h as a source. 1266 1267 gn refs out/Debug //base/macros.h --tree 1268 Display a reverse dependency tree to get to the given file. This 1269 will show how dependencies will reference that file. 1270 1271 gn refs out/Debug //base/macros.h //base/at_exit.h --all 1272 Display all unique targets with some dependency path to a target 1273 containing either of the given files as a source. 1274 1275 gn refs out/Debug //base/macros.h --testonly=true --type=executable 1276 --all --as=output 1277 Display the executable file names of all test executables 1278 potentially affected by a change to the given file. 1279``` 1280## <a name="targets"></a>Target declarations 1281 1282### <a name="func_action"></a>**action**: Declare a target that runs a script a single time. 1283 1284``` 1285 This target type allows you to run a script a single time to produce one or 1286 more output files. If you want to run a script once for each of a set of 1287 input files, see "gn help action_foreach". 1288``` 1289 1290#### **Inputs** 1291 1292``` 1293 In an action the "sources" and "inputs" are treated the same: they're both 1294 input dependencies on script execution with no special handling. If you want 1295 to pass the sources to your script, you must do so explicitly by including 1296 them in the "args". Note also that this means there is no special handling of 1297 paths since GN doesn't know which of the args are paths and not. You will 1298 want to use rebase_path() to convert paths to be relative to the 1299 root_build_dir. 1300 1301 You can dynamically write input dependencies (for incremental rebuilds if an 1302 input file changes) by writing a depfile when the script is run (see "gn help 1303 depfile"). This is more flexible than "inputs". 1304 1305 If the command line length is very long, you can use response files to pass 1306 args to your script. See "gn help response_file_contents". 1307 1308 It is recommended you put inputs to your script in the "sources" variable, 1309 and stuff like other Python files required to run your script in the "inputs" 1310 variable. 1311 1312 The "deps" and "public_deps" for an action will always be 1313 completed before any part of the action is run so it can depend on 1314 the output of previous steps. The "data_deps" will be built if the 1315 action is built, but may not have completed before all steps of the 1316 action are started. This can give additional parallelism in the build 1317 for runtime-only dependencies. 1318``` 1319 1320#### **Outputs** 1321 1322``` 1323 You should specify files created by your script by specifying them in the 1324 "outputs". 1325 1326 The script will be executed with the given arguments with the current 1327 directory being that of the root build directory. If you pass files 1328 to your script, see "gn help rebase_path" for how to convert 1329 file names to be relative to the build directory (file names in the 1330 sources, outputs, and inputs will be all treated as relative to the 1331 current build file and converted as needed automatically). 1332 1333 GN sets Ninja's flag 'restat = 1` for all action commands. This means 1334 that Ninja will check the timestamp of the output after the action 1335 completes. If output timestamp is unchanged, the step will be treated 1336 as if it never needed to be rebuilt, potentially eliminating some 1337 downstream steps for incremental builds. Scripts can improve build 1338 performance by taking care not to change the timstamp of the output 1339 file(s) if the contents have not changed. 1340``` 1341 1342#### **File name handling** 1343 1344``` 1345 All output files must be inside the output directory of the build. 1346 You would generally use |$target_out_dir| or |$target_gen_dir| to 1347 reference the output or generated intermediate file directories, 1348 respectively. 1349``` 1350 1351#### **Variables** 1352 1353``` 1354 args, data, data_deps, depfile, deps, inputs, metadata, outputs*, pool, 1355 response_file_contents, script*, sources 1356 * = required 1357``` 1358 1359#### **Example** 1360 1361``` 1362 action("run_this_guy_once") { 1363 script = "doprocessing.py" 1364 sources = [ "my_configuration.txt" ] 1365 outputs = [ "$target_gen_dir/insightful_output.txt" ] 1366 1367 # Our script imports this Python file so we want to rebuild if it changes. 1368 inputs = [ "helper_library.py" ] 1369 1370 # Note that we have to manually pass the sources to our script if the 1371 # script needs them as inputs. 1372 args = [ "--out", rebase_path(target_gen_dir, root_build_dir) ] + 1373 rebase_path(sources, root_build_dir) 1374 } 1375``` 1376### <a name="func_action_foreach"></a>**action_foreach**: Declare a target that runs a script over a set of files. 1377 1378``` 1379 This target type allows you to run a script once-per-file over a set of 1380 sources. If you want to run a script once that takes many files as input, see 1381 "gn help action". 1382``` 1383 1384#### **Inputs** 1385 1386``` 1387 The script will be run once per file in the "sources" variable. The "outputs" 1388 variable should specify one or more files with a source expansion pattern in 1389 it (see "gn help source_expansion"). The output file(s) for each script 1390 invocation should be unique. Normally you use "{{source_name_part}}" in each 1391 output file. 1392 1393 If your script takes additional data as input, such as a shared configuration 1394 file or a Python module it uses, those files should be listed in the "inputs" 1395 variable. These files are treated as dependencies of each script invocation. 1396 1397 If the command line length is very long, you can use response files to pass 1398 args to your script. See "gn help response_file_contents". 1399 1400 You can dynamically write input dependencies (for incremental rebuilds if an 1401 input file changes) by writing a depfile when the script is run (see "gn help 1402 depfile"). This is more flexible than "inputs". 1403 1404 The "deps" and "public_deps" for an action will always be 1405 completed before any part of the action is run so it can depend on 1406 the output of previous steps. The "data_deps" will be built if the 1407 action is built, but may not have completed before all steps of the 1408 action are started. This can give additional parallelism in the build 1409 for runtime-only dependencies. 1410``` 1411 1412#### **Outputs** 1413 1414``` 1415 The script will be executed with the given arguments with the current 1416 directory being that of the root build directory. If you pass files 1417 to your script, see "gn help rebase_path" for how to convert 1418 file names to be relative to the build directory (file names in the 1419 sources, outputs, and inputs will be all treated as relative to the 1420 current build file and converted as needed automatically). 1421 1422 GN sets Ninja's flag 'restat = 1` for all action commands. This means 1423 that Ninja will check the timestamp of the output after the action 1424 completes. If output timestamp is unchanged, the step will be treated 1425 as if it never needed to be rebuilt, potentially eliminating some 1426 downstream steps for incremental builds. Scripts can improve build 1427 performance by taking care not to change the timstamp of the output 1428 file(s) if the contents have not changed. 1429``` 1430 1431#### **File name handling** 1432 1433``` 1434 All output files must be inside the output directory of the build. 1435 You would generally use |$target_out_dir| or |$target_gen_dir| to 1436 reference the output or generated intermediate file directories, 1437 respectively. 1438``` 1439 1440#### **Variables** 1441 1442``` 1443 args, data, data_deps, depfile, deps, inputs, metadata, outputs*, pool, 1444 response_file_contents, script*, sources* 1445 * = required 1446``` 1447 1448#### **Example** 1449 1450``` 1451 # Runs the script over each IDL file. The IDL script will generate both a .cc 1452 # and a .h file for each input. 1453 action_foreach("my_idl") { 1454 script = "idl_processor.py" 1455 sources = [ "foo.idl", "bar.idl" ] 1456 1457 # Our script reads this file each time, so we need to list it as a 1458 # dependency so we can rebuild if it changes. 1459 inputs = [ "my_configuration.txt" ] 1460 1461 # Transformation from source file name to output file names. 1462 outputs = [ "$target_gen_dir/{{source_name_part}}.h", 1463 "$target_gen_dir/{{source_name_part}}.cc" ] 1464 1465 # Note that since "args" is opaque to GN, if you specify paths here, you 1466 # will need to convert it to be relative to the build directory using 1467 # rebase_path(). 1468 args = [ 1469 "{{source}}", 1470 "-o", 1471 rebase_path(target_gen_dir, root_build_dir) + 1472 "/{{source_name_part}}.h" ] 1473 } 1474``` 1475### <a name="func_bundle_data"></a>**bundle_data**: [iOS/macOS] Declare a target without output. 1476 1477``` 1478 This target type allows one to declare data that is required at runtime. It is 1479 used to inform "create_bundle" targets of the files to copy into generated 1480 bundle, see "gn help create_bundle" for help. 1481 1482 The target must define a list of files as "sources" and a single "outputs". 1483 If there are multiple files, source expansions must be used to express the 1484 output. The output must reference a file inside of {{bundle_root_dir}}. 1485 1486 This target can be used on all platforms though it is designed only to 1487 generate iOS/macOS bundle. In cross-platform projects, it is advised to put it 1488 behind iOS/macOS conditionals. 1489 1490 See "gn help create_bundle" for more information. 1491``` 1492 1493#### **Variables** 1494 1495``` 1496 sources*, outputs*, deps, data_deps, metadata, public_deps, visibility 1497 * = required 1498``` 1499 1500#### **Examples** 1501 1502``` 1503 bundle_data("icudata") { 1504 sources = [ "sources/data/in/icudtl.dat" ] 1505 outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ] 1506 } 1507 1508 bundle_data("base_unittests_bundle_data]") { 1509 sources = [ "test/data" ] 1510 outputs = [ 1511 "{{bundle_resources_dir}}/{{source_root_relative_dir}}/" + 1512 "{{source_file_part}}" 1513 ] 1514 } 1515 1516 bundle_data("material_typography_bundle_data") { 1517 sources = [ 1518 "src/MaterialTypography.bundle/Roboto-Bold.ttf", 1519 "src/MaterialTypography.bundle/Roboto-Italic.ttf", 1520 "src/MaterialTypography.bundle/Roboto-Regular.ttf", 1521 "src/MaterialTypography.bundle/Roboto-Thin.ttf", 1522 ] 1523 outputs = [ 1524 "{{bundle_resources_dir}}/MaterialTypography.bundle/" 1525 "{{source_file_part}}" 1526 ] 1527 } 1528``` 1529### <a name="func_copy"></a>**copy**: Declare a target that copies files. 1530 1531#### **File name handling** 1532 1533``` 1534 All output files must be inside the output directory of the build. You would 1535 generally use |$target_out_dir| or |$target_gen_dir| to reference the output 1536 or generated intermediate file directories, respectively. 1537 1538 Both "sources" and "outputs" must be specified. Sources can include as many 1539 files as you want, but there can only be one item in the outputs list (plural 1540 is used for the name for consistency with other target types). 1541 1542 If there is more than one source file, your output name should specify a 1543 mapping from each source file to an output file name using source expansion 1544 (see "gn help source_expansion"). The placeholders will look like 1545 "{{source_name_part}}", for example. 1546``` 1547 1548#### **Examples** 1549 1550``` 1551 # Write a rule that copies a checked-in DLL to the output directory. 1552 copy("mydll") { 1553 sources = [ "mydll.dll" ] 1554 outputs = [ "$target_out_dir/mydll.dll" ] 1555 } 1556 1557 # Write a rule to copy several files to the target generated files directory. 1558 copy("myfiles") { 1559 sources = [ "data1.dat", "data2.dat", "data3.dat" ] 1560 1561 # Use source expansion to generate output files with the corresponding file 1562 # names in the gen dir. This will just copy each file. 1563 outputs = [ "$target_gen_dir/{{source_file_part}}" ] 1564 } 1565``` 1566### <a name="func_create_bundle"></a>**create_bundle**: [ios/macOS] Build an iOS or macOS bundle. 1567 1568``` 1569 This target generates an iOS or macOS bundle (which is a directory with a 1570 well-know structure). This target does not define any sources, instead they 1571 are computed from all "bundle_data" target this one depends on transitively 1572 (the recursion stops at "create_bundle" targets). 1573 1574 The "bundle_*_dir" are be used for the expansion of {{bundle_*_dir}} rules in 1575 "bundle_data" outputs. The properties are optional but must be defined if any 1576 of the "bundle_data" target use them. 1577 1578 This target can be used on all platforms though it is designed only to 1579 generate iOS or macOS bundle. In cross-platform projects, it is advised to put 1580 it behind iOS/macOS conditionals. 1581 1582 If a create_bundle is specified as a data_deps for another target, the bundle 1583 is considered a leaf, and its public and private dependencies will not 1584 contribute to any data or data_deps. Required runtime dependencies should be 1585 placed in the bundle. A create_bundle can declare its own explicit data and 1586 data_deps, however. 1587``` 1588 1589#### **Code signing** 1590 1591``` 1592 Some bundle needs to be code signed as part of the build (on iOS all 1593 application needs to be code signed to run on a device). The code signature 1594 can be configured via the code_signing_script variable. 1595 1596 If set, code_signing_script is the path of a script that invoked after all 1597 files have been moved into the bundle. The script must not change any file in 1598 the bundle, but may add new files. 1599 1600 If code_signing_script is defined, then code_signing_outputs must also be 1601 defined and non-empty to inform when the script needs to be re-run. The 1602 code_signing_args will be passed as is to the script (so path have to be 1603 rebased) and additional inputs may be listed with the variable 1604 code_signing_sources. 1605``` 1606 1607#### **Variables** 1608 1609``` 1610 bundle_root_dir, bundle_contents_dir, bundle_resources_dir, 1611 bundle_executable_dir, bundle_deps_filter, deps, data_deps, public_deps, 1612 visibility, product_type, code_signing_args, code_signing_script, 1613 code_signing_sources, code_signing_outputs, xcode_extra_attributes, 1614 xcode_test_application_name, partial_info_plist, metadata 1615``` 1616 1617#### **Example** 1618 1619``` 1620 # Defines a template to create an application. On most platform, this is just 1621 # an alias for an "executable" target, but on iOS/macOS, it builds an 1622 # application bundle. 1623 template("app") { 1624 if (!is_ios && !is_mac) { 1625 executable(target_name) { 1626 forward_variables_from(invoker, "*") 1627 } 1628 } else { 1629 app_name = target_name 1630 gen_path = target_gen_dir 1631 1632 action("${app_name}_generate_info_plist") { 1633 script = [ "//build/ios/ios_gen_plist.py" ] 1634 sources = [ "templates/Info.plist" ] 1635 outputs = [ "$gen_path/Info.plist" ] 1636 args = rebase_path(sources, root_build_dir) + 1637 rebase_path(outputs, root_build_dir) 1638 } 1639 1640 bundle_data("${app_name}_bundle_info_plist") { 1641 public_deps = [ ":${app_name}_generate_info_plist" ] 1642 sources = [ "$gen_path/Info.plist" ] 1643 outputs = [ "{{bundle_contents_dir}}/Info.plist" ] 1644 } 1645 1646 executable("${app_name}_generate_executable") { 1647 forward_variables_from(invoker, "*", [ 1648 "output_name", 1649 "visibility", 1650 ]) 1651 output_name = 1652 rebase_path("$gen_path/$app_name", root_build_dir) 1653 } 1654 1655 code_signing = 1656 defined(invoker.code_signing) && invoker.code_signing 1657 1658 if (!is_ios || !code_signing) { 1659 bundle_data("${app_name}_bundle_executable") { 1660 public_deps = [ ":${app_name}_generate_executable" ] 1661 sources = [ "$gen_path/$app_name" ] 1662 outputs = [ "{{bundle_executable_dir}}/$app_name" ] 1663 } 1664 } 1665 1666 create_bundle("$app_name.app") { 1667 product_type = "com.apple.product-type.application" 1668 1669 if (is_ios) { 1670 bundle_root_dir = "$root_build_dir/$target_name" 1671 bundle_contents_dir = bundle_root_dir 1672 bundle_resources_dir = bundle_contents_dir 1673 bundle_executable_dir = bundle_contents_dir 1674 1675 xcode_extra_attributes = { 1676 ONLY_ACTIVE_ARCH = "YES" 1677 DEBUG_INFORMATION_FORMAT = "dwarf" 1678 } 1679 } else { 1680 bundle_root_dir = "$root_build_dir/$target_name" 1681 bundle_contents_dir = "$bundle_root_dir/Contents" 1682 bundle_resources_dir = "$bundle_contents_dir/Resources" 1683 bundle_executable_dir = "$bundle_contents_dir/MacOS" 1684 } 1685 deps = [ ":${app_name}_bundle_info_plist" ] 1686 if (is_ios && code_signing) { 1687 deps += [ ":${app_name}_generate_executable" ] 1688 code_signing_script = "//build/config/ios/codesign.py" 1689 code_signing_sources = [ 1690 invoker.entitlements_path, 1691 "$target_gen_dir/$app_name", 1692 ] 1693 code_signing_outputs = [ 1694 "$bundle_root_dir/$app_name", 1695 "$bundle_root_dir/_CodeSignature/CodeResources", 1696 "$bundle_root_dir/embedded.mobileprovision", 1697 "$target_gen_dir/$app_name.xcent", 1698 ] 1699 code_signing_args = [ 1700 "-i=" + ios_code_signing_identity, 1701 "-b=" + rebase_path( 1702 "$target_gen_dir/$app_name", root_build_dir), 1703 "-e=" + rebase_path( 1704 invoker.entitlements_path, root_build_dir), 1705 "-e=" + rebase_path( 1706 "$target_gen_dir/$app_name.xcent", root_build_dir), 1707 rebase_path(bundle_root_dir, root_build_dir), 1708 ] 1709 } else { 1710 deps += [ ":${app_name}_bundle_executable" ] 1711 } 1712 } 1713 } 1714 } 1715``` 1716### <a name="func_executable"></a>**executable**: Declare an executable target. 1717 1718#### **Language and compilation** 1719 1720``` 1721 The tools and commands used to create this target type will be 1722 determined by the source files in its sources. Targets containing 1723 multiple compiler-incompatible languages are not allowed (e.g. a 1724 target containing both C and C++ sources is acceptable, but a 1725 target containing C and Rust sources is not). 1726``` 1727 1728#### **Variables** 1729 1730``` 1731 Flags: cflags, cflags_c, cflags_cc, cflags_objc, cflags_objcc, 1732 asmflags, defines, include_dirs, inputs, ldflags, lib_dirs, 1733 libs, precompiled_header, precompiled_source, rustflags, 1734 rustenv, swiftflags 1735 Deps: data_deps, deps, public_deps 1736 Dependent configs: all_dependent_configs, public_configs 1737 General: check_includes, configs, data, friend, inputs, metadata, 1738 output_name, output_extension, public, sources, testonly, 1739 visibility 1740 Rust variables: aliased_deps, crate_root, crate_name 1741``` 1742### <a name="func_generated_file"></a>**generated_file**: Declare a generated_file target. 1743 1744``` 1745 Writes data value(s) to disk on resolution. This target type mirrors some 1746 functionality of the write_file() function, but also provides the ability to 1747 collect metadata from its dependencies on resolution rather than writing out 1748 at parse time. 1749 1750 The `outputs` variable is required to be a list with a single element, 1751 specifying the intended location of the output file. 1752 1753 The `output_conversion` variable specified the format to write the 1754 value. See `gn help io_conversion`. 1755 1756 One of `contents` or `data_keys` must be specified; use of `contents` will 1757 write the contents of that value to file, while use of `data_keys` will 1758 trigger a metadata collection walk based on the dependencies of the target and 1759 the optional values of the `rebase` and `walk_keys` variables. See 1760 `gn help metadata`. 1761 1762 Collected metadata, if specified, will be returned in postorder of 1763 dependencies. See the example for details. 1764``` 1765 1766#### **Example (metadata collection)** 1767 1768``` 1769 Given the following targets defined in //base/BUILD.gn, where A depends on B 1770 and B depends on C and D: 1771 1772 group("a") { 1773 metadata = { 1774 doom_melon = [ "enable" ] 1775 my_files = [ "foo.cpp" ] 1776 1777 # Note: this is functionally equivalent to not defining `my_barrier` 1778 # at all in this target's metadata. 1779 my_barrier = [ "" ] 1780 } 1781 1782 deps = [ ":b" ] 1783 } 1784 1785 group("b") { 1786 metadata = { 1787 my_files = [ "bar.cpp" ] 1788 my_barrier = [ ":c" ] 1789 } 1790 1791 deps = [ ":c", ":d" ] 1792 } 1793 1794 group("c") { 1795 metadata = { 1796 doom_melon = [ "disable" ] 1797 my_files = [ "baz.cpp" ] 1798 } 1799 } 1800 1801 group("d") { 1802 metadata = { 1803 my_files = [ "missing.cpp" ] 1804 } 1805 } 1806 1807 If the following generated_file target is defined: 1808 1809 generated_file("my_files_metadata") { 1810 outputs = [ "$root_build_dir/my_files.json" ] 1811 data_keys = [ "my_files" ] 1812 1813 deps = [ "//base:a" ] 1814 } 1815 1816 The following will be written to "$root_build_dir/my_files.json" (less the 1817 comments): 1818 [ 1819 "baz.cpp", // from //base:c via //base:b 1820 "missing.cpp" // from //base:d via //base:b 1821 "bar.cpp", // from //base:b via //base:a 1822 "foo.cpp", // from //base:a 1823 ] 1824 1825 Alternatively, as an example of using walk_keys, if the following 1826 generated_file target is defined: 1827 1828 generated_file("my_files_metadata") { 1829 outputs = [ "$root_build_dir/my_files.json" ] 1830 data_keys = [ "my_files" ] 1831 walk_keys = [ "my_barrier" ] 1832 1833 deps = [ "//base:a" ] 1834 } 1835 1836 The following will be written to "$root_build_dir/my_files.json" (again less 1837 the comments): 1838 [ 1839 "baz.cpp", // from //base:c via //base:b 1840 "bar.cpp", // from //base:b via //base:a 1841 "foo.cpp", // from //base:a 1842 ] 1843 1844 If `rebase` is used in the following generated_file target: 1845 1846 generated_file("my_files_metadata") { 1847 outputs = [ "$root_build_dir/my_files.json" ] 1848 data_keys = [ "my_files" ] 1849 walk_keys = [ "my_barrier" ] 1850 rebase = root_build_dir 1851 1852 deps = [ "//base:a" ] 1853 } 1854 1855 The following will be written to "$root_build_dir/my_files.json" (again less 1856 the comments) (assuming root_build_dir = "//out"): 1857 [ 1858 "../base/baz.cpp", // from //base:c via //base:b 1859 "../base/bar.cpp", // from //base:b via //base:a 1860 "../base/foo.cpp", // from //base:a 1861 ] 1862``` 1863 1864#### **Variables** 1865 1866``` 1867 contents 1868 data_keys 1869 rebase 1870 walk_keys 1871 output_conversion 1872 Deps: data_deps, deps, public_deps 1873 Dependent configs: all_dependent_configs, public_configs 1874``` 1875### <a name="func_group"></a>**group**: Declare a named group of targets. 1876 1877``` 1878 This target type allows you to create meta-targets that just collect a set of 1879 dependencies into one named target. Groups can additionally specify configs 1880 that apply to their dependents. 1881``` 1882 1883#### **Variables** 1884 1885``` 1886 Deps: data_deps, deps, public_deps 1887 Dependent configs: all_dependent_configs, public_configs 1888``` 1889 1890#### **Example** 1891 1892``` 1893 group("all") { 1894 deps = [ 1895 "//project:runner", 1896 "//project:unit_tests", 1897 ] 1898 } 1899``` 1900### <a name="func_loadable_module"></a>**loadable_module**: Declare a loadable module target. 1901 1902``` 1903 This target type allows you to create an object file that is (and can only 1904 be) loaded and unloaded at runtime. 1905 1906 A loadable module will be specified on the linker line for targets listing 1907 the loadable module in its "deps". If you don't want this (if you don't need 1908 to dynamically load the library at runtime), then you should use a 1909 "shared_library" target type instead. 1910``` 1911 1912#### **Language and compilation** 1913 1914``` 1915 The tools and commands used to create this target type will be 1916 determined by the source files in its sources. Targets containing 1917 multiple compiler-incompatible languages are not allowed (e.g. a 1918 target containing both C and C++ sources is acceptable, but a 1919 target containing C and Rust sources is not). 1920``` 1921 1922#### **Variables** 1923 1924``` 1925 Flags: cflags, cflags_c, cflags_cc, cflags_objc, cflags_objcc, 1926 asmflags, defines, include_dirs, inputs, ldflags, lib_dirs, 1927 libs, precompiled_header, precompiled_source, rustflags, 1928 rustenv, swiftflags 1929 Deps: data_deps, deps, public_deps 1930 Dependent configs: all_dependent_configs, public_configs 1931 General: check_includes, configs, data, friend, inputs, metadata, 1932 output_name, output_extension, public, sources, testonly, 1933 visibility 1934 Rust variables: aliased_deps, crate_root, crate_name, crate_type 1935``` 1936### <a name="func_rust_library"></a>**rust_library**: Declare a Rust library target. 1937 1938``` 1939 A Rust library is an archive containing additional rust-c provided metadata. 1940 These are the files produced by the rustc compiler with the `.rlib` 1941 extension, and are the intermediate step for most Rust-based binaries. 1942``` 1943 1944#### **Language and compilation** 1945 1946``` 1947 The tools and commands used to create this target type will be 1948 determined by the source files in its sources. Targets containing 1949 multiple compiler-incompatible languages are not allowed (e.g. a 1950 target containing both C and C++ sources is acceptable, but a 1951 target containing C and Rust sources is not). 1952``` 1953 1954#### **Variables** 1955 1956``` 1957 Flags: cflags, cflags_c, cflags_cc, cflags_objc, cflags_objcc, 1958 asmflags, defines, include_dirs, inputs, ldflags, lib_dirs, 1959 libs, precompiled_header, precompiled_source, rustflags, 1960 rustenv, swiftflags 1961 Deps: data_deps, deps, public_deps 1962 Dependent configs: all_dependent_configs, public_configs 1963 General: check_includes, configs, data, friend, inputs, metadata, 1964 output_name, output_extension, public, sources, testonly, 1965 visibility 1966 Rust variables: aliased_deps, crate_root, crate_name 1967``` 1968### <a name="func_rust_proc_macro"></a>**rust_proc_macro**: Declare a Rust procedural macro target. 1969 1970``` 1971 A Rust procedural macro allows creating syntax extensions as execution of a 1972 function. They are compiled as dynamic libraries and used by the compiler at 1973 runtime. 1974 1975 Their use is the same as of other Rust libraries, but their build has some 1976 additional restrictions in terms of supported flags. 1977``` 1978 1979#### **Language and compilation** 1980 1981``` 1982 The tools and commands used to create this target type will be 1983 determined by the source files in its sources. Targets containing 1984 multiple compiler-incompatible languages are not allowed (e.g. a 1985 target containing both C and C++ sources is acceptable, but a 1986 target containing C and Rust sources is not). 1987``` 1988 1989#### **Variables** 1990 1991``` 1992 Flags: cflags, cflags_c, cflags_cc, cflags_objc, cflags_objcc, 1993 asmflags, defines, include_dirs, inputs, ldflags, lib_dirs, 1994 libs, precompiled_header, precompiled_source, rustflags, 1995 rustenv, swiftflags 1996 Deps: data_deps, deps, public_deps 1997 Dependent configs: all_dependent_configs, public_configs 1998 General: check_includes, configs, data, friend, inputs, metadata, 1999 output_name, output_extension, public, sources, testonly, 2000 visibility 2001 Rust variables: aliased_deps, crate_root, crate_name 2002``` 2003### <a name="func_shared_library"></a>**shared_library**: Declare a shared library target. 2004 2005``` 2006 A shared library will be specified on the linker line for targets listing the 2007 shared library in its "deps". If you don't want this (say you dynamically 2008 load the library at runtime), then you should depend on the shared library 2009 via "data_deps" or, on Darwin platforms, use a "loadable_module" target type 2010 instead. 2011``` 2012 2013#### **Language and compilation** 2014 2015``` 2016 The tools and commands used to create this target type will be 2017 determined by the source files in its sources. Targets containing 2018 multiple compiler-incompatible languages are not allowed (e.g. a 2019 target containing both C and C++ sources is acceptable, but a 2020 target containing C and Rust sources is not). 2021``` 2022 2023#### **Variables** 2024 2025``` 2026 Flags: cflags, cflags_c, cflags_cc, cflags_objc, cflags_objcc, 2027 asmflags, defines, include_dirs, inputs, ldflags, lib_dirs, 2028 libs, precompiled_header, precompiled_source, rustflags, 2029 rustenv, swiftflags 2030 Deps: data_deps, deps, public_deps 2031 Dependent configs: all_dependent_configs, public_configs 2032 General: check_includes, configs, data, friend, inputs, metadata, 2033 output_name, output_extension, public, sources, testonly, 2034 visibility 2035 Rust variables: aliased_deps, crate_root, crate_name, crate_type 2036``` 2037### <a name="func_source_set"></a>**source_set**: Declare a source set target. 2038 2039``` 2040 Only C-language source sets are supported at the moment. 2041``` 2042 2043#### **C-language source_sets** 2044 2045``` 2046 A source set is a collection of sources that get compiled, but are not linked 2047 to produce any kind of library. Instead, the resulting object files are 2048 implicitly added to the linker line of all targets that depend on the source 2049 set. 2050 2051 In most cases, a source set will behave like a static library, except no 2052 actual library file will be produced. This will make the build go a little 2053 faster by skipping creation of a large static library, while maintaining the 2054 organizational benefits of focused build targets. 2055 2056 The main difference between a source set and a static library is around 2057 handling of exported symbols. Most linkers assume declaring a function 2058 exported means exported from the static library. The linker can then do dead 2059 code elimination to delete code not reachable from exported functions. 2060 2061 A source set will not do this code elimination since there is no link step. 2062 This allows you to link many source sets into a shared library and have the 2063 "exported symbol" notation indicate "export from the final shared library and 2064 not from the intermediate targets." There is no way to express this concept 2065 when linking multiple static libraries into a shared library. 2066``` 2067 2068#### **Variables** 2069 2070``` 2071 Flags: cflags, cflags_c, cflags_cc, cflags_objc, cflags_objcc, 2072 asmflags, defines, include_dirs, inputs, ldflags, lib_dirs, 2073 libs, precompiled_header, precompiled_source, rustflags, 2074 rustenv, swiftflags 2075 Deps: data_deps, deps, public_deps 2076 Dependent configs: all_dependent_configs, public_configs 2077 General: check_includes, configs, data, friend, inputs, metadata, 2078 output_name, output_extension, public, sources, testonly, 2079 visibility 2080``` 2081### <a name="func_static_library"></a>**static_library**: Declare a static library target. 2082 2083``` 2084 Make a ".a" / ".lib" file. 2085 2086 If you only need the static library for intermediate results in the build, 2087 you should consider a source_set instead since it will skip the (potentially 2088 slow) step of creating the intermediate library file. 2089``` 2090 2091#### **Variables** 2092 2093``` 2094 complete_static_lib 2095 Flags: cflags, cflags_c, cflags_cc, cflags_objc, cflags_objcc, 2096 asmflags, defines, include_dirs, inputs, ldflags, lib_dirs, 2097 libs, precompiled_header, precompiled_source, rustflags, 2098 rustenv, swiftflags 2099 Deps: data_deps, deps, public_deps 2100 Dependent configs: all_dependent_configs, public_configs 2101 General: check_includes, configs, data, friend, inputs, metadata, 2102 output_name, output_extension, public, sources, testonly, 2103 visibility 2104 Rust variables: aliased_deps, crate_root, crate_name 2105 2106 The tools and commands used to create this target type will be 2107 determined by the source files in its sources. Targets containing 2108 multiple compiler-incompatible languages are not allowed (e.g. a 2109 target containing both C and C++ sources is acceptable, but a 2110 target containing C and Rust sources is not). 2111``` 2112### <a name="func_target"></a>**target**: Declare an target with the given programmatic type. 2113 2114``` 2115 target(target_type_string, target_name_string) { ... } 2116 2117 The target() function is a way to invoke a built-in target or template with a 2118 type determined at runtime. This is useful for cases where the type of a 2119 target might not be known statically. 2120 2121 Only templates and built-in target functions are supported for the 2122 target_type_string parameter. Arbitrary functions, configs, and toolchains 2123 are not supported. 2124 2125 The call: 2126 target("source_set", "doom_melon") { 2127 Is equivalent to: 2128 source_set("doom_melon") { 2129``` 2130 2131#### **Example** 2132 2133``` 2134 if (foo_build_as_shared) { 2135 my_type = "shared_library" 2136 } else { 2137 my_type = "source_set" 2138 } 2139 2140 target(my_type, "foo") { 2141 ... 2142 } 2143``` 2144## <a name="functions"></a>Buildfile functions 2145 2146### <a name="func_assert"></a>**assert**: Assert an expression is true at generation time. 2147 2148``` 2149 assert(<condition> [, <error string>]) 2150 2151 If the condition is false, the build will fail with an error. If the 2152 optional second argument is provided, that string will be printed 2153 with the error message. 2154``` 2155 2156#### **Examples** 2157 2158``` 2159 assert(is_win) 2160 assert(defined(sources), "Sources must be defined"); 2161``` 2162### <a name="func_config"></a>**config**: Defines a configuration object. 2163 2164``` 2165 Configuration objects can be applied to targets and specify sets of compiler 2166 flags, includes, defines, etc. They provide a way to conveniently group sets 2167 of this configuration information. 2168 2169 A config is referenced by its label just like a target. 2170 2171 The values in a config are additive only. If you want to remove a flag you 2172 need to remove the corresponding config that sets it. The final set of flags, 2173 defines, etc. for a target is generated in this order: 2174 2175 1. The values specified directly on the target (rather than using a config). 2176 2. The configs specified in the target's "configs" list, in order. 2177 3. Public_configs from a breadth-first traversal of the dependency tree in 2178 the order that the targets appear in "deps". 2179 4. All dependent configs from a breadth-first traversal of the dependency 2180 tree in the order that the targets appear in "deps". 2181``` 2182 2183#### **More background** 2184 2185``` 2186 Configs solve a problem where the build system needs to have a higher-level 2187 understanding of various compiler settings. For example, some compiler flags 2188 have to appear in a certain order relative to each other, some settings like 2189 defines and flags logically go together, and the build system needs to 2190 de-duplicate flags even though raw command-line parameters can't always be 2191 operated on in that way. 2192 2193 The config gives a name to a group of settings that can then be reasoned 2194 about by GN. GN can know that configs with the same label are the same thing 2195 so can be de-duplicated. It allows related settings to be grouped so they 2196 are added or removed as a unit. And it allows targets to refer to settings 2197 with conceptual names ("no_rtti", "enable_exceptions", etc.) rather than 2198 having to hard-coding every compiler's flags each time they are referred to. 2199``` 2200 2201#### **Variables valid in a config definition** 2202 2203``` 2204 Flags: cflags, cflags_c, cflags_cc, cflags_objc, cflags_objcc, 2205 asmflags, defines, include_dirs, inputs, ldflags, lib_dirs, 2206 libs, precompiled_header, precompiled_source, rustflags, 2207 rustenv, swiftflags 2208 Nested configs: configs 2209 General: visibility 2210``` 2211 2212#### **Variables on a target used to apply configs** 2213 2214``` 2215 all_dependent_configs, configs, public_configs 2216``` 2217 2218#### **Example** 2219 2220``` 2221 config("myconfig") { 2222 include_dirs = [ "include/common" ] 2223 defines = [ "ENABLE_DOOM_MELON" ] 2224 } 2225 2226 executable("mything") { 2227 configs = [ ":myconfig" ] 2228 } 2229``` 2230### <a name="func_declare_args"></a>**declare_args**: Declare build arguments. 2231 2232``` 2233 Introduces the given arguments into the current scope. If they are not 2234 specified on the command line or in a toolchain's arguments, the default 2235 values given in the declare_args block will be used. However, these defaults 2236 will not override command-line values. 2237 2238 See also "gn help buildargs" for an overview. 2239 2240 The precise behavior of declare args is: 2241 2242 1. The declare_args() block executes. Any variable defined in the enclosing 2243 scope is available for reading, but any variable defined earlier in 2244 the current scope is not (since the overrides haven't been applied yet). 2245 2246 2. At the end of executing the block, any variables set within that scope 2247 are saved, with the values specified in the block used as the "default value" 2248 for that argument. Once saved, these variables are available for override 2249 via args.gn. 2250 2251 3. User-defined overrides are applied. Anything set in "gn args" now 2252 overrides any default values. The resulting set of variables is promoted 2253 to be readable from the following code in the file. 2254 2255 This has some ramifications that may not be obvious: 2256 2257 - You should not perform difficult work inside a declare_args block since 2258 this only sets a default value that may be discarded. In particular, 2259 don't use the result of exec_script() to set the default value. If you 2260 want to have a script-defined default, set some default "undefined" value 2261 like [], "", or -1, and after the declare_args block, call exec_script if 2262 the value is unset by the user. 2263 2264 - Because you cannot read the value of a variable defined in the same 2265 block, if you need to make the default value of one arg depend 2266 on the possibly-overridden value of another, write two separate 2267 declare_args() blocks: 2268 2269 declare_args() { 2270 enable_foo = true 2271 } 2272 declare_args() { 2273 # Bar defaults to same user-overridden state as foo. 2274 enable_bar = enable_foo 2275 } 2276``` 2277 2278#### **Example** 2279 2280``` 2281 declare_args() { 2282 enable_teleporter = true 2283 enable_doom_melon = false 2284 } 2285 2286 If you want to override the (default disabled) Doom Melon: 2287 gn --args="enable_doom_melon=true enable_teleporter=true" 2288 This also sets the teleporter, but it's already defaulted to on so it will 2289 have no effect. 2290``` 2291### <a name="func_defined"></a>**defined**: Returns whether an identifier is defined. 2292 2293``` 2294 Returns true if the given argument is defined. This is most useful in 2295 templates to assert that the caller set things up properly. 2296 2297 You can pass an identifier: 2298 defined(foo) 2299 which will return true or false depending on whether foo is defined in the 2300 current scope. 2301 2302 You can also check a named scope: 2303 defined(foo.bar) 2304 which will return true or false depending on whether bar is defined in the 2305 named scope foo. It will throw an error if foo is not defined or is not a 2306 scope. 2307``` 2308 2309#### **Example** 2310 2311``` 2312 template("mytemplate") { 2313 # To help users call this template properly... 2314 assert(defined(invoker.sources), "Sources must be defined") 2315 2316 # If we want to accept an optional "values" argument, we don't 2317 # want to dereference something that may not be defined. 2318 if (defined(invoker.values)) { 2319 values = invoker.values 2320 } else { 2321 values = "some default value" 2322 } 2323 } 2324``` 2325### <a name="func_exec_script"></a>**exec_script**: Synchronously run a script and return the output. 2326 2327``` 2328 exec_script(filename, 2329 arguments = [], 2330 input_conversion = "", 2331 file_dependencies = []) 2332 2333 Runs the given script, returning the stdout of the script. The build 2334 generation will fail if the script does not exist or returns a nonzero exit 2335 code. 2336 2337 The current directory when executing the script will be the root build 2338 directory. If you are passing file names, you will want to use the 2339 rebase_path() function to make file names relative to this path (see "gn help 2340 rebase_path"). 2341 2342 The default script interpreter is Python ("python" on POSIX, "python.exe" or 2343 "python.bat" on Windows). This can be configured by the script_executable 2344 variable, see "gn help dotfile". 2345``` 2346 2347#### **Arguments**: 2348 2349``` 2350 filename: 2351 File name of script to execute. Non-absolute names will be treated as 2352 relative to the current build file. 2353 2354 arguments: 2355 A list of strings to be passed to the script as arguments. May be 2356 unspecified or the empty list which means no arguments. 2357 2358 input_conversion: 2359 Controls how the file is read and parsed. See `gn help io_conversion`. 2360 2361 If unspecified, defaults to the empty string which causes the script 2362 result to be discarded. exec script will return None. 2363 2364 dependencies: 2365 (Optional) A list of files that this script reads or otherwise depends 2366 on. These dependencies will be added to the build result such that if any 2367 of them change, the build will be regenerated and the script will be 2368 re-run. 2369 2370 The script itself will be an implicit dependency so you do not need to 2371 list it. 2372``` 2373 2374#### **Example** 2375 2376``` 2377 all_lines = exec_script( 2378 "myscript.py", [some_input], "list lines", 2379 [ rebase_path("data_file.txt", root_build_dir) ]) 2380 2381 # This example just calls the script with no arguments and discards the 2382 # result. 2383 exec_script("//foo/bar/myscript.py") 2384``` 2385### <a name="func_filter_exclude"></a>**filter_exclude**: Remove values that match a set of patterns. 2386 2387``` 2388 filter_exclude(values, exclude_patterns) 2389 2390 The argument values must be a list of strings. 2391 2392 The argument exclude_patterns must be a list of file patterns (see 2393 "gn help file_pattern"). Any elements in values matching at least one 2394 of those patterns will be excluded. 2395``` 2396 2397#### **Examples** 2398``` 2399 values = [ "foo.cc", "foo.h", "foo.proto" ] 2400 result = filter_exclude(values, [ "*.proto" ]) 2401 # result will be [ "foo.cc", "foo.h" ] 2402``` 2403### <a name="func_filter_include"></a>**filter_include**: Remove values that do not match a set of patterns. 2404 2405``` 2406 filter_include(values, include_patterns) 2407 2408 The argument values must be a list of strings. 2409 2410 The argument include_patterns must be a list of file patterns (see 2411 "gn help file_pattern"). Only elements from values matching at least 2412 one of the pattern will be included. 2413``` 2414 2415#### **Examples** 2416``` 2417 values = [ "foo.cc", "foo.h", "foo.proto" ] 2418 result = filter_include(values, [ "*.proto" ]) 2419 # result will be [ "foo.proto" ] 2420``` 2421### <a name="func_foreach"></a>**foreach**: Iterate over a list. 2422 2423``` 2424 foreach(<loop_var>, <list>) { 2425 <loop contents> 2426 } 2427 2428 Executes the loop contents block over each item in the list, assigning the 2429 loop_var to each item in sequence. The <loop_var> will be a copy so assigning 2430 to it will not mutate the list. The loop will iterate over a copy of <list> 2431 so mutating it inside the loop will not affect iteration. 2432 2433 The block does not introduce a new scope, so that variable assignments inside 2434 the loop will be visible once the loop terminates. 2435 2436 The loop variable will temporarily shadow any existing variables with the 2437 same name for the duration of the loop. After the loop terminates the loop 2438 variable will no longer be in scope, and the previous value (if any) will be 2439 restored. 2440``` 2441 2442#### **Example** 2443 2444``` 2445 mylist = [ "a", "b", "c" ] 2446 foreach(i, mylist) { 2447 print(i) 2448 } 2449 2450 Prints: 2451 a 2452 b 2453 c 2454``` 2455### <a name="func_forward_variables_from"></a>**forward_variables_from**: Copies variables from a different scope. 2456 2457``` 2458 forward_variables_from(from_scope, variable_list_or_star, 2459 variable_to_not_forward_list = []) 2460 2461 Copies the given variables from the given scope to the local scope if they 2462 exist. This is normally used in the context of templates to use the values of 2463 variables defined in the template invocation to a template-defined target. 2464 2465 The variables in the given variable_list will be copied if they exist in the 2466 given scope or any enclosing scope. If they do not exist, nothing will happen 2467 and they be left undefined in the current scope. 2468 2469 As a special case, if the variable_list is a string with the value of "*", 2470 all variables from the given scope will be copied. "*" only copies variables 2471 set directly on the from_scope, not enclosing ones. Otherwise it would 2472 duplicate all global variables. 2473 2474 When an explicit list of variables is supplied, if the variable exists in the 2475 current (destination) scope already, an error will be thrown. If "*" is 2476 specified, variables in the current scope will be clobbered (the latter is 2477 important because most targets have an implicit configs list, which means it 2478 wouldn't work at all if it didn't clobber). 2479 2480 If variables_to_not_forward_list is non-empty, then it must contains a list 2481 of variable names that will not be forwarded. This is mostly useful when 2482 variable_list_or_star has a value of "*". 2483``` 2484 2485#### **Examples** 2486 2487``` 2488 # forward_variables_from(invoker, ["foo"]) 2489 # is equivalent to: 2490 assert(!defined(foo)) 2491 if (defined(invoker.foo)) { 2492 foo = invoker.foo 2493 } 2494 2495 # This is a common action template. It would invoke a script with some given 2496 # parameters, and wants to use the various types of deps and the visibility 2497 # from the invoker if it's defined. It also injects an additional dependency 2498 # to all targets. 2499 template("my_test") { 2500 action(target_name) { 2501 forward_variables_from(invoker, [ "data_deps", "deps", 2502 "public_deps", "visibility"]) 2503 # Add our test code to the dependencies. 2504 # "deps" may or may not be defined at this point. 2505 if (defined(deps)) { 2506 deps += [ "//tools/doom_melon" ] 2507 } else { 2508 deps = [ "//tools/doom_melon" ] 2509 } 2510 } 2511 } 2512 2513 # This is a template around a target whose type depends on a global variable. 2514 # It forwards all values from the invoker. 2515 template("my_wrapper") { 2516 target(my_wrapper_target_type, target_name) { 2517 forward_variables_from(invoker, "*") 2518 } 2519 } 2520 2521 # A template that wraps another. It adds behavior based on one 2522 # variable, and forwards all others to the nested target. 2523 template("my_ios_test_app") { 2524 ios_test_app(target_name) { 2525 forward_variables_from(invoker, "*", ["test_bundle_name"]) 2526 if (!defined(extra_substitutions)) { 2527 extra_substitutions = [] 2528 } 2529 extra_substitutions += [ "BUNDLE_ID_TEST_NAME=$test_bundle_name" ] 2530 } 2531 } 2532``` 2533### <a name="func_get_label_info"></a>**get_label_info**: Get an attribute from a target's label. 2534 2535``` 2536 get_label_info(target_label, what) 2537 2538 Given the label of a target, returns some attribute of that target. The 2539 target need not have been previously defined in the same file, since none of 2540 the attributes depend on the actual target definition, only the label itself. 2541 2542 See also "gn help get_target_outputs". 2543``` 2544 2545#### **Possible values for the "what" parameter** 2546 2547``` 2548 "name" 2549 The short name of the target. This will match the value of the 2550 "target_name" variable inside that target's declaration. For the label 2551 "//foo/bar:baz" this will return "baz". 2552 2553 "dir" 2554 The directory containing the target's definition, with no slash at the 2555 end. For the label "//foo/bar:baz" this will return "//foo/bar". 2556 2557 "target_gen_dir" 2558 The generated file directory for the target. This will match the value of 2559 the "target_gen_dir" variable when inside that target's declaration. 2560 2561 "root_gen_dir" 2562 The root of the generated file tree for the target. This will match the 2563 value of the "root_gen_dir" variable when inside that target's 2564 declaration. 2565 2566 "target_out_dir 2567 The output directory for the target. This will match the value of the 2568 "target_out_dir" variable when inside that target's declaration. 2569 2570 "root_out_dir" 2571 The root of the output file tree for the target. This will match the 2572 value of the "root_out_dir" variable when inside that target's 2573 declaration. 2574 2575 "label_no_toolchain" 2576 The fully qualified version of this label, not including the toolchain. 2577 For the input ":bar" it might return "//foo:bar". 2578 2579 "label_with_toolchain" 2580 The fully qualified version of this label, including the toolchain. For 2581 the input ":bar" it might return "//foo:bar(//toolchain:x64)". 2582 2583 "toolchain" 2584 The label of the toolchain. This will match the value of the 2585 "current_toolchain" variable when inside that target's declaration. 2586``` 2587 2588#### **Examples** 2589 2590``` 2591 get_label_info(":foo", "name") 2592 # Returns string "foo". 2593 2594 get_label_info("//foo/bar:baz", "target_gen_dir") 2595 # Returns string "//out/Debug/gen/foo/bar". 2596``` 2597### <a name="func_get_path_info"></a>**get_path_info**: Extract parts of a file or directory name. 2598 2599``` 2600 get_path_info(input, what) 2601 2602 The first argument is either a string representing a file or directory name, 2603 or a list of such strings. If the input is a list the return value will be a 2604 list containing the result of applying the rule to each item in the input. 2605``` 2606 2607#### **Possible values for the "what" parameter** 2608 2609``` 2610 "file" 2611 The substring after the last slash in the path, including the name and 2612 extension. If the input ends in a slash, the empty string will be 2613 returned. 2614 "foo/bar.txt" => "bar.txt" 2615 "bar.txt" => "bar.txt" 2616 "foo/" => "" 2617 "" => "" 2618 2619 "name" 2620 The substring of the file name not including the extension. 2621 "foo/bar.txt" => "bar" 2622 "foo/bar" => "bar" 2623 "foo/" => "" 2624 2625 "extension" 2626 The substring following the last period following the last slash, or the 2627 empty string if not found. The period is not included. 2628 "foo/bar.txt" => "txt" 2629 "foo/bar" => "" 2630 2631 "dir" 2632 The directory portion of the name, not including the slash. 2633 "foo/bar.txt" => "foo" 2634 "//foo/bar" => "//foo" 2635 "foo" => "." 2636 2637 The result will never end in a slash, so if the resulting is empty, the 2638 system ("/") or source ("//") roots, a "." will be appended such that it 2639 is always legal to append a slash and a filename and get a valid path. 2640 2641 "out_dir" 2642 The output file directory corresponding to the path of the given file, 2643 not including a trailing slash. 2644 "//foo/bar/baz.txt" => "//out/Default/obj/foo/bar" 2645 2646 "gen_dir" 2647 The generated file directory corresponding to the path of the given file, 2648 not including a trailing slash. 2649 "//foo/bar/baz.txt" => "//out/Default/gen/foo/bar" 2650 2651 "abspath" 2652 The full absolute path name to the file or directory. It will be resolved 2653 relative to the current directory, and then the source- absolute version 2654 will be returned. If the input is system- absolute, the same input will 2655 be returned. 2656 "foo/bar.txt" => "//mydir/foo/bar.txt" 2657 "foo/" => "//mydir/foo/" 2658 "//foo/bar" => "//foo/bar" (already absolute) 2659 "/usr/include" => "/usr/include" (already absolute) 2660 2661 If you want to make the path relative to another directory, or to be 2662 system-absolute, see rebase_path(). 2663``` 2664 2665#### **Examples** 2666``` 2667 sources = [ "foo.cc", "foo.h" ] 2668 result = get_path_info(source, "abspath") 2669 # result will be [ "//mydir/foo.cc", "//mydir/foo.h" ] 2670 2671 result = get_path_info("//foo/bar/baz.cc", "dir") 2672 # result will be "//foo/bar" 2673 2674 # Extract the source-absolute directory name, 2675 result = get_path_info(get_path_info(path, "dir"), "abspath") 2676``` 2677### <a name="func_get_target_outputs"></a>**get_target_outputs**: [file list] Get the list of outputs from a target. 2678 2679``` 2680 get_target_outputs(target_label) 2681 2682 Returns a list of output files for the named target. The named target must 2683 have been previously defined in the current file before this function is 2684 called (it can't reference targets in other files because there isn't a 2685 defined execution order, and it obviously can't reference targets that are 2686 defined after the function call). 2687 2688 Only copy, generated_file, and action targets are supported. The outputs from 2689 binary targets will depend on the toolchain definition which won't 2690 necessarily have been loaded by the time a given line of code has run, and 2691 source sets and groups have no useful output file. 2692``` 2693 2694#### **Return value** 2695 2696``` 2697 The names in the resulting list will be absolute file paths (normally like 2698 "//out/Debug/bar.exe", depending on the build directory). 2699 2700 action, copy, and generated_file targets: this will just return the files 2701 specified in the "outputs" variable of the target. 2702 2703 action_foreach targets: this will return the result of applying the output 2704 template to the sources (see "gn help source_expansion"). This will be the 2705 same result (though with guaranteed absolute file paths), as 2706 process_file_template will return for those inputs (see "gn help 2707 process_file_template"). 2708 2709 source sets and groups: this will return a list containing the path of the 2710 "stamp" file that Ninja will produce once all outputs are generated. This 2711 probably isn't very useful. 2712``` 2713 2714#### **Example** 2715 2716``` 2717 # Say this action generates a bunch of C source files. 2718 action_foreach("my_action") { 2719 sources = [ ... ] 2720 outputs = [ ... ] 2721 } 2722 2723 # Compile the resulting source files into a source set. 2724 source_set("my_lib") { 2725 sources = get_target_outputs(":my_action") 2726 } 2727``` 2728### <a name="func_getenv"></a>**getenv**: Get an environment variable. 2729 2730``` 2731 value = getenv(env_var_name) 2732 2733 Returns the value of the given environment variable. If the value is not 2734 found, it will try to look up the variable with the "opposite" case (based on 2735 the case of the first letter of the variable), but is otherwise 2736 case-sensitive. 2737 2738 If the environment variable is not found, the empty string will be returned. 2739 Note: it might be nice to extend this if we had the concept of "none" in the 2740 language to indicate lookup failure. 2741``` 2742 2743#### **Example** 2744 2745``` 2746 home_dir = getenv("HOME") 2747``` 2748### <a name="func_import"></a>**import**: Import a file into the current scope. 2749 2750``` 2751 The import command loads the rules and variables resulting from executing the 2752 given file into the current scope. 2753 2754 By convention, imported files are named with a .gni extension. 2755 2756 An import is different than a C++ "include". The imported file is executed in 2757 a standalone environment from the caller of the import command. The results 2758 of this execution are cached for other files that import the same .gni file. 2759 2760 Note that you can not import a BUILD.gn file that's otherwise used in the 2761 build. Files must either be imported or implicitly loaded as a result of deps 2762 rules, but not both. 2763 2764 The imported file's scope will be merged with the scope at the point import 2765 was called. If there is a conflict (both the current scope and the imported 2766 file define some variable or rule with the same name but different value), a 2767 runtime error will be thrown. Therefore, it's good practice to minimize the 2768 stuff that an imported file defines. 2769 2770 Variables and templates beginning with an underscore '_' are considered 2771 private and will not be imported. Imported files can use such variables for 2772 internal computation without affecting other files. 2773``` 2774 2775#### **Examples** 2776 2777``` 2778 import("//build/rules/idl_compilation_rule.gni") 2779 2780 # Looks in the current directory. 2781 import("my_vars.gni") 2782``` 2783### <a name="func_not_needed"></a>**not_needed**: Mark variables from scope as not needed. 2784 2785``` 2786 not_needed(variable_list_or_star, variable_to_ignore_list = []) 2787 not_needed(from_scope, variable_list_or_star, 2788 variable_to_ignore_list = []) 2789 2790 Mark the variables in the current or given scope as not needed, which means 2791 you will not get an error about unused variables for these. The 2792 variable_to_ignore_list allows excluding variables from "all matches" if 2793 variable_list_or_star is "*". 2794``` 2795 2796#### **Example** 2797 2798``` 2799 not_needed("*", [ "config" ]) 2800 not_needed([ "data_deps", "deps" ]) 2801 not_needed(invoker, "*", [ "config" ]) 2802 not_needed(invoker, [ "data_deps", "deps" ]) 2803``` 2804### <a name="func_pool"></a>**pool**: Defines a pool object. 2805 2806``` 2807 Pool objects can be applied to a tool to limit the parallelism of the 2808 build. This object has a single property "depth" corresponding to 2809 the number of tasks that may run simultaneously. 2810 2811 As the file containing the pool definition may be executed in the 2812 context of more than one toolchain it is recommended to specify an 2813 explicit toolchain when defining and referencing a pool. 2814 2815 A pool named "console" defined in the root build file represents Ninja's 2816 console pool. Targets using this pool will have access to the console's 2817 stdin and stdout, and output will not be buffered. This special pool must 2818 have a depth of 1. Pools not defined in the root must not be named "console". 2819 The console pool can only be defined for the default toolchain. 2820 Refer to the Ninja documentation on the console pool for more info. 2821 2822 A pool is referenced by its label just like a target. 2823``` 2824 2825#### **Variables** 2826 2827``` 2828 depth* 2829 * = required 2830``` 2831 2832#### **Example** 2833 2834``` 2835 if (current_toolchain == default_toolchain) { 2836 pool("link_pool") { 2837 depth = 1 2838 } 2839 } 2840 2841 toolchain("toolchain") { 2842 tool("link") { 2843 command = "..." 2844 pool = ":link_pool($default_toolchain)" 2845 } 2846 } 2847``` 2848### <a name="func_print"></a>**print**: Prints to the console. 2849 2850``` 2851 Prints all arguments to the console separated by spaces. A newline is 2852 automatically appended to the end. 2853 2854 This function is intended for debugging. Note that build files are run in 2855 parallel so you may get interleaved prints. A buildfile may also be executed 2856 more than once in parallel in the context of different toolchains so the 2857 prints from one file may be duplicated or 2858 interleaved with itself. 2859``` 2860 2861#### **Examples** 2862 2863``` 2864 print("Hello world") 2865 2866 print(sources, deps) 2867``` 2868### <a name="func_process_file_template"></a>**process_file_template**: Do template expansion over a list of files. 2869 2870``` 2871 process_file_template(source_list, template) 2872 2873 process_file_template applies a template list to a source file list, 2874 returning the result of applying each template to each source. This is 2875 typically used for computing output file names from input files. 2876 2877 In most cases, get_target_outputs() will give the same result with shorter, 2878 more maintainable code. This function should only be used when that function 2879 can't be used (like there's no target or the target is defined in another 2880 build file). 2881``` 2882 2883#### **Arguments** 2884 2885``` 2886 The source_list is a list of file names. 2887 2888 The template can be a string or a list. If it is a list, multiple output 2889 strings are generated for each input. 2890 2891 The template should contain source expansions to which each name in the 2892 source list is applied. See "gn help source_expansion". 2893``` 2894 2895#### **Example** 2896 2897``` 2898 sources = [ 2899 "foo.idl", 2900 "bar.idl", 2901 ] 2902 myoutputs = process_file_template( 2903 sources, 2904 [ "$target_gen_dir/{{source_name_part}}.cc", 2905 "$target_gen_dir/{{source_name_part}}.h" ]) 2906 2907 The result in this case will be: 2908 [ "//out/Debug/foo.cc" 2909 "//out/Debug/foo.h" 2910 "//out/Debug/bar.cc" 2911 "//out/Debug/bar.h" ] 2912``` 2913### <a name="func_read_file"></a>**read_file**: Read a file into a variable. 2914 2915``` 2916 read_file(filename, input_conversion) 2917 2918 Whitespace will be trimmed from the end of the file. Throws an error if the 2919 file can not be opened. 2920``` 2921 2922#### **Arguments** 2923 2924``` 2925 filename 2926 Filename to read, relative to the build file. 2927 2928 input_conversion 2929 Controls how the file is read and parsed. See `gn help io_conversion`. 2930``` 2931 2932#### **Example** 2933 2934``` 2935 lines = read_file("foo.txt", "list lines") 2936``` 2937### <a name="func_rebase_path"></a>**rebase_path**: Rebase a file or directory to another location. 2938 2939``` 2940 converted = rebase_path(input, 2941 new_base = "", 2942 current_base = ".") 2943 2944 Takes a string argument representing a file name, or a list of such strings 2945 and converts it/them to be relative to a different base directory. 2946 2947 When invoking the compiler or scripts, GN will automatically convert sources 2948 and include directories to be relative to the build directory. However, if 2949 you're passing files directly in the "args" array or doing other manual 2950 manipulations where GN doesn't know something is a file name, you will need 2951 to convert paths to be relative to what your tool is expecting. 2952 2953 The common case is to use this to convert paths relative to the current 2954 directory to be relative to the build directory (which will be the current 2955 directory when executing scripts). 2956 2957 If you want to convert a file path to be source-absolute (that is, beginning 2958 with a double slash like "//foo/bar"), you should use the get_path_info() 2959 function. This function won't work because it will always make relative 2960 paths, and it needs to support making paths relative to the source root, so 2961 it can't also generate source-absolute paths without more special-cases. 2962``` 2963 2964#### **Arguments** 2965 2966``` 2967 input 2968 A string or list of strings representing file or directory names. These 2969 can be relative paths ("foo/bar.txt"), system absolute paths 2970 ("/foo/bar.txt"), or source absolute paths ("//foo/bar.txt"). 2971 2972 new_base 2973 The directory to convert the paths to be relative to. This can be an 2974 absolute path or a relative path (which will be treated as being relative 2975 to the current BUILD-file's directory). 2976 2977 As a special case, if new_base is the empty string (the default), all 2978 paths will be converted to system-absolute native style paths with system 2979 path separators. This is useful for invoking external programs. 2980 2981 current_base 2982 Directory representing the base for relative paths in the input. If this 2983 is not an absolute path, it will be treated as being relative to the 2984 current build file. Use "." (the default) to convert paths from the 2985 current BUILD-file's directory. 2986``` 2987 2988#### **Return value** 2989 2990``` 2991 The return value will be the same type as the input value (either a string or 2992 a list of strings). All relative and source-absolute file names will be 2993 converted to be relative to the requested output System-absolute paths will 2994 be unchanged. 2995 2996 Whether an output path will end in a slash will match whether the 2997 corresponding input path ends in a slash. It will return "." or "./" 2998 (depending on whether the input ends in a slash) to avoid returning empty 2999 strings. This means if you want a root path ("//" or "/") not ending in a 3000 slash, you can add a dot ("//."). 3001``` 3002 3003#### **Example** 3004 3005``` 3006 # Convert a file in the current directory to be relative to the build 3007 # directory (the current dir when executing compilers and scripts). 3008 foo = rebase_path("myfile.txt", root_build_dir) 3009 # might produce "../../project/myfile.txt". 3010 3011 # Convert a file to be system absolute: 3012 foo = rebase_path("myfile.txt") 3013 # Might produce "D:\\source\\project\\myfile.txt" on Windows or 3014 # "/home/you/source/project/myfile.txt" on Linux. 3015 3016 # Typical usage for converting to the build directory for a script. 3017 action("myscript") { 3018 # Don't convert sources, GN will automatically convert these to be relative 3019 # to the build directory when it constructs the command line for your 3020 # script. 3021 sources = [ "foo.txt", "bar.txt" ] 3022 3023 # Extra file args passed manually need to be explicitly converted 3024 # to be relative to the build directory: 3025 args = [ 3026 "--data", 3027 rebase_path("//mything/data/input.dat", root_build_dir), 3028 "--rel", 3029 rebase_path("relative_path.txt", root_build_dir) 3030 ] + rebase_path(sources, root_build_dir) 3031 } 3032``` 3033### <a name="func_set_default_toolchain"></a>**set_default_toolchain**: Sets the default toolchain name. 3034 3035``` 3036 set_default_toolchain(toolchain_label) 3037 3038 The given label should identify a toolchain definition (see "gn help 3039 toolchain"). This toolchain will be used for all targets unless otherwise 3040 specified. 3041 3042 This function is only valid to call during the processing of the build 3043 configuration file. Since the build configuration file is processed 3044 separately for each toolchain, this function will be a no-op when called 3045 under any non-default toolchains. 3046 3047 For example, the default toolchain should be appropriate for the current 3048 environment. If the current environment is 32-bit and somebody references a 3049 target with a 64-bit toolchain, we wouldn't want processing of the build 3050 config file for the 64-bit toolchain to reset the default toolchain to 3051 64-bit, we want to keep it 32-bits. 3052``` 3053 3054#### **Argument** 3055 3056``` 3057 toolchain_label 3058 Toolchain name. 3059``` 3060 3061#### **Example** 3062 3063``` 3064 # Set default toolchain only has an effect when run in the context of the 3065 # default toolchain. Pick the right one according to the current CPU 3066 # architecture. 3067 if (target_cpu == "x64") { 3068 set_default_toolchain("//toolchains:64") 3069 } else if (target_cpu == "x86") { 3070 set_default_toolchain("//toolchains:32") 3071 } 3072``` 3073### <a name="func_set_defaults"></a>**set_defaults**: Set default values for a target type. 3074 3075``` 3076 set_defaults(<target_type_name>) { <values...> } 3077 3078 Sets the default values for a given target type. Whenever target_type_name is 3079 seen in the future, the values specified in set_default's block will be 3080 copied into the current scope. 3081 3082 When the target type is used, the variable copying is very strict. If a 3083 variable with that name is already in scope, the build will fail with an 3084 error. 3085 3086 set_defaults can be used for built-in target types ("executable", 3087 "shared_library", etc.) and custom ones defined via the "template" command. 3088 It can be called more than once and the most recent call in any scope will 3089 apply, but there is no way to refer to the previous defaults and modify them 3090 (each call to set_defaults must supply a complete list of all defaults it 3091 wants). If you want to share defaults, store them in a separate variable. 3092``` 3093 3094#### **Example** 3095 3096``` 3097 set_defaults("static_library") { 3098 configs = [ "//tools/mything:settings" ] 3099 } 3100 3101 static_library("mylib") { 3102 # The configs will be auto-populated as above. You can remove it if 3103 # you don't want the default for a particular default: 3104 configs -= [ "//tools/mything:settings" ] 3105 } 3106``` 3107### <a name="func_split_list"></a>**split_list**: Splits a list into N different sub-lists. 3108 3109``` 3110 result = split_list(input, n) 3111 3112 Given a list and a number N, splits the list into N sub-lists of 3113 approximately equal size. The return value is a list of the sub-lists. The 3114 result will always be a list of size N. If N is greater than the number of 3115 elements in the input, it will be padded with empty lists. 3116 3117 The expected use is to divide source files into smaller uniform chunks. 3118``` 3119 3120#### **Example** 3121 3122``` 3123 The code: 3124 mylist = [1, 2, 3, 4, 5, 6] 3125 print(split_list(mylist, 3)) 3126 3127 Will print: 3128 [[1, 2], [3, 4], [5, 6] 3129``` 3130### <a name="func_string_join"></a>**string_join**: Concatenates a list of strings with a separator. 3131 3132``` 3133 result = string_join(separator, strings) 3134 3135 Concatenate a list of strings with intervening occurrences of separator. 3136``` 3137 3138#### **Examples** 3139 3140``` 3141 string_join("", ["a", "b", "c"]) --> "abc" 3142 string_join("|", ["a", "b", "c"]) --> "a|b|c" 3143 string_join(", ", ["a", "b", "c"]) --> "a, b, c" 3144 string_join("s", ["", ""]) --> "s" 3145``` 3146### <a name="func_string_replace"></a>**string_replace**: Replaces substring in the given string. 3147 3148``` 3149 result = string_replace(str, old, new[, max]) 3150 3151 Returns a copy of the string str in which the occurrences of old have been 3152 replaced with new, optionally restricting the number of replacements. The 3153 replacement is performed sequentially, so if new contains old, it won't be 3154 replaced. 3155``` 3156 3157#### **Example** 3158 3159``` 3160 The code: 3161 mystr = "Hello, world!" 3162 print(string_replace(mystr, "world", "GN")) 3163 3164 Will print: 3165 Hello, GN! 3166``` 3167### <a name="func_string_split"></a>**string_split**: Split string into a list of strings. 3168 3169``` 3170 result = string_split(str[, sep]) 3171 3172 Split string into all substrings separated by separator and returns a list 3173 of the substrings between those separators. 3174 3175 If the separator argument is omitted, the split is by any whitespace, and 3176 any leading/trailing whitespace is ignored; similar to Python's str.split(). 3177``` 3178 3179#### **Examples without a separator (split on whitespace)**: 3180 3181``` 3182 string_split("") --> [] 3183 string_split("a") --> ["a"] 3184 string_split(" aa bb") --> ["aa", "bb"] 3185``` 3186 3187#### **Examples with a separator (split on separators)**: 3188 3189``` 3190 string_split("", "|") --> [""] 3191 string_split(" a b ", " ") --> ["", "", "a", "b", "", ""] 3192 string_split("aa+-bb+-c", "+-") --> ["aa", "bb", "c"] 3193``` 3194### <a name="func_template"></a>**template**: Define a template rule. 3195 3196``` 3197 A template defines a custom name that acts like a function. It provides a way 3198 to add to the built-in target types. 3199 3200 The template() function is used to declare a template. To invoke the 3201 template, just use the name of the template like any other target type. 3202 3203 Often you will want to declare your template in a special file that other 3204 files will import (see "gn help import") so your template rule can be shared 3205 across build files. 3206``` 3207 3208#### **Variables and templates**: 3209 3210``` 3211 When you call template() it creates a closure around all variables currently 3212 in scope with the code in the template block. When the template is invoked, 3213 the closure will be executed. 3214 3215 When the template is invoked, the code in the caller is executed and passed 3216 to the template code as an implicit "invoker" variable. The template uses 3217 this to read state out of the invoking code. 3218 3219 One thing explicitly excluded from the closure is the "current directory" 3220 against which relative file names are resolved. The current directory will be 3221 that of the invoking code, since typically that code specifies the file 3222 names. This means all files internal to the template should use absolute 3223 names. 3224 3225 A template will typically forward some or all variables from the invoking 3226 scope to a target that it defines. Often, such variables might be optional. 3227 Use the pattern: 3228 3229 if (defined(invoker.deps)) { 3230 deps = invoker.deps 3231 } 3232 3233 The function forward_variables_from() provides a shortcut to forward one or 3234 more or possibly all variables in this manner: 3235 3236 forward_variables_from(invoker, ["deps", "public_deps"]) 3237``` 3238 3239#### **Target naming** 3240 3241``` 3242 Your template should almost always define a built-in target with the name the 3243 template invoker specified. For example, if you have an IDL template and 3244 somebody does: 3245 idl("foo") {... 3246 you will normally want this to expand to something defining a source_set or 3247 static_library named "foo" (among other things you may need). This way, when 3248 another target specifies a dependency on "foo", the static_library or 3249 source_set will be linked. 3250 3251 It is also important that any other targets your template expands to have 3252 unique names, or you will get collisions. 3253 3254 Access the invoking name in your template via the implicit "target_name" 3255 variable. This should also be the basis for how other targets that a template 3256 expands to ensure uniqueness. 3257 3258 A typical example would be a template that defines an action to generate some 3259 source files, and a source_set to compile that source. Your template would 3260 name the source_set "target_name" because that's what you want external 3261 targets to depend on to link your code. And you would name the action 3262 something like "${target_name}_action" to make it unique. The source set 3263 would have a dependency on the action to make it run. 3264``` 3265 3266#### **Overriding builtin targets** 3267 3268``` 3269 You can use template to redefine a built-in target in which case your template 3270 takes a precedence over the built-in one. All uses of the target from within 3271 the template definition will refer to the built-in target which makes it 3272 possible to extend the behavior of the built-in target: 3273 3274 template("shared_library") { 3275 shared_library(shlib) { 3276 forward_variables_from(invoker, "*") 3277 ... 3278 } 3279 } 3280``` 3281 3282#### **Example of defining a template** 3283 3284``` 3285 template("my_idl") { 3286 # Be nice and help callers debug problems by checking that the variables 3287 # the template requires are defined. This gives a nice message rather than 3288 # giving the user an error about an undefined variable in the file defining 3289 # the template 3290 # 3291 # You can also use defined() to give default values to variables 3292 # unspecified by the invoker. 3293 assert(defined(invoker.sources), 3294 "Need sources in $target_name listing the idl files.") 3295 3296 # Name of the intermediate target that does the code gen. This must 3297 # incorporate the target name so it's unique across template 3298 # instantiations. 3299 code_gen_target_name = target_name + "_code_gen" 3300 3301 # Intermediate target to convert IDL to C source. Note that the name is 3302 # based on the name the invoker of the template specified. This way, each 3303 # time the template is invoked we get a unique intermediate action name 3304 # (since all target names are in the global scope). 3305 action_foreach(code_gen_target_name) { 3306 # Access the scope defined by the invoker via the implicit "invoker" 3307 # variable. 3308 sources = invoker.sources 3309 3310 # Note that we need an absolute path for our script file name. The 3311 # current directory when executing this code will be that of the invoker 3312 # (this is why we can use the "sources" directly above without having to 3313 # rebase all of the paths). But if we need to reference a script relative 3314 # to the template file, we'll need to use an absolute path instead. 3315 script = "//tools/idl/idl_code_generator.py" 3316 3317 # Tell GN how to expand output names given the sources. 3318 # See "gn help source_expansion" for more. 3319 outputs = [ "$target_gen_dir/{{source_name_part}}.cc", 3320 "$target_gen_dir/{{source_name_part}}.h" ] 3321 } 3322 3323 # Name the source set the same as the template invocation so instancing 3324 # this template produces something that other targets can link to in their 3325 # deps. 3326 source_set(target_name) { 3327 # Generates the list of sources, we get these from the action_foreach 3328 # above. 3329 sources = get_target_outputs(":$code_gen_target_name") 3330 3331 # This target depends on the files produced by the above code gen target. 3332 deps = [ ":$code_gen_target_name" ] 3333 } 3334 } 3335``` 3336 3337#### **Example of invoking the resulting template** 3338 3339``` 3340 # This calls the template code above, defining target_name to be 3341 # "foo_idl_files" and "invoker" to be the set of stuff defined in the curly 3342 # brackets. 3343 my_idl("foo_idl_files") { 3344 # Goes into the template as "invoker.sources". 3345 sources = [ "foo.idl", "bar.idl" ] 3346 } 3347 3348 # Here is a target that depends on our template. 3349 executable("my_exe") { 3350 # Depend on the name we gave the template call above. Internally, this will 3351 # produce a dependency from executable to the source_set inside the 3352 # template (since it has this name), which will in turn depend on the code 3353 # gen action. 3354 deps = [ ":foo_idl_files" ] 3355 } 3356``` 3357### <a name="func_tool"></a>**tool**: Specify arguments to a toolchain tool. 3358 3359#### **Usage** 3360 3361``` 3362 tool(<tool type>) { 3363 <tool variables...> 3364 } 3365``` 3366 3367#### **Tool types** 3368 3369``` 3370 Compiler tools: 3371 "cc": C compiler 3372 "cxx": C++ compiler 3373 "cxx_module": C++ compiler used for Clang .modulemap files 3374 "objc": Objective C compiler 3375 "objcxx": Objective C++ compiler 3376 "rc": Resource compiler (Windows .rc files) 3377 "asm": Assembler 3378 "swift": Swift compiler driver 3379 3380 Linker tools: 3381 "alink": Linker for static libraries (archives) 3382 "solink": Linker for shared libraries 3383 "link": Linker for executables 3384 3385 Other tools: 3386 "stamp": Tool for creating stamp files 3387 "copy": Tool to copy files. 3388 "action": Defaults for actions 3389 3390 Platform specific tools: 3391 "copy_bundle_data": [iOS, macOS] Tool to copy files in a bundle. 3392 "compile_xcassets": [iOS, macOS] Tool to compile asset catalogs. 3393 3394 Rust tools: 3395 "rust_bin": Tool for compiling Rust binaries 3396 "rust_cdylib": Tool for compiling C-compatible dynamic libraries. 3397 "rust_dylib": Tool for compiling Rust dynamic libraries. 3398 "rust_macro": Tool for compiling Rust procedural macros. 3399 "rust_rlib": Tool for compiling Rust libraries. 3400 "rust_staticlib": Tool for compiling Rust static libraries. 3401``` 3402 3403#### **Tool variables** 3404 3405``` 3406 command [string with substitutions] 3407 Valid for: all tools except "action" (required) 3408 3409 The command to run. 3410 3411 command_launcher [string] 3412 Valid for: all tools except "action" (optional) 3413 3414 The prefix with which to launch the command (e.g. the path to a Goma or 3415 CCache compiler launcher). 3416 3417 Note that this prefix will not be included in the compilation database or 3418 IDE files generated from the build. 3419 3420 default_output_dir [string with substitutions] 3421 Valid for: linker tools 3422 3423 Default directory name for the output file relative to the 3424 root_build_dir. It can contain other substitution patterns. This will 3425 be the default value for the {{output_dir}} expansion (discussed below) 3426 but will be overridden by the "output_dir" variable in a target, if one 3427 is specified. 3428 3429 GN doesn't do anything with this string other than pass it along, 3430 potentially with target-specific overrides. It is the tool's job to use 3431 the expansion so that the files will be in the right place. 3432 3433 default_output_extension [string] 3434 Valid for: linker tools 3435 3436 Extension for the main output of a linkable tool. It includes the 3437 leading dot. This will be the default value for the 3438 {{output_extension}} expansion (discussed below) but will be overridden 3439 by by the "output extension" variable in a target, if one is specified. 3440 Empty string means no extension. 3441 3442 GN doesn't actually do anything with this extension other than pass it 3443 along, potentially with target-specific overrides. One would typically 3444 use the {{output_extension}} value in the "outputs" to read this value. 3445 3446 Example: default_output_extension = ".exe" 3447 3448 depfile [string with substitutions] 3449 Valid for: compiler tools (optional) 3450 3451 If the tool can write ".d" files, this specifies the name of the 3452 resulting file. These files are used to list header file dependencies 3453 (or other implicit input dependencies) that are discovered at build 3454 time. See also "depsformat". 3455 3456 Example: depfile = "{{output}}.d" 3457 3458 depsformat [string] 3459 Valid for: compiler tools (when depfile is specified) 3460 3461 Format for the deps outputs. This is either "gcc" or "msvc". See the 3462 ninja documentation for "deps" for more information. 3463 3464 Example: depsformat = "gcc" 3465 3466 description [string with substitutions, optional] 3467 Valid for: all tools 3468 3469 What to print when the command is run. 3470 3471 Example: description = "Compiling {{source}}" 3472 3473 exe_output_extension [string, optional, rust tools only] 3474 rlib_output_extension [string, optional, rust tools only] 3475 dylib_output_extension [string, optional, rust tools only] 3476 cdylib_output_extension [string, optional, rust tools only] 3477 rust_proc_macro_output_extension [string, optional, rust tools only] 3478 Valid for: Rust tools 3479 3480 These specify the default tool output for each of the crate types. 3481 The default is empty for executables, shared, and static libraries and 3482 ".rlib" for rlibs. Note that the Rust compiler complains with an error 3483 if external crates do not take the form `lib<name>.rlib` or 3484 `lib<name>.<shared_extension>`, where `<shared_extension>` is `.so`, 3485 `.dylib`, or `.dll` as appropriate for the platform. 3486 3487 lib_switch [string, optional, link tools only] 3488 lib_dir_switch [string, optional, link tools only] 3489 Valid for: Linker tools except "alink" 3490 3491 These strings will be prepended to the libraries and library search 3492 directories, respectively, because linkers differ on how to specify 3493 them. 3494 3495 If you specified: 3496 lib_switch = "-l" 3497 lib_dir_switch = "-L" 3498 then the "{{libs}}" expansion for 3499 [ "freetype", "expat" ] 3500 would be 3501 "-lfreetype -lexpat". 3502 3503 framework_switch [string, optional, link tools only] 3504 weak_framework_switch [string, optional, link tools only] 3505 framework_dir_switch [string, optional, link tools only] 3506 Valid for: Linker tools 3507 3508 These strings will be prepended to the frameworks and framework search 3509 path directories, respectively, because linkers differ on how to specify 3510 them. 3511 3512 If you specified: 3513 framework_switch = "-framework " 3514 weak_framework_switch = "-weak_framework " 3515 framework_dir_switch = "-F" 3516 and: 3517 framework_dirs = [ "$root_out_dir" ] 3518 frameworks = [ "UIKit.framework", "Foo.framework" ] 3519 weak_frameworks = [ "MediaPlayer.framework" ] 3520 would be: 3521 "-F. -framework UIKit -framework Foo -weak_framework MediaPlayer" 3522 3523 swiftmodule_switch [string, optional, link tools only] 3524 Valid for: Linker tools except "alink" 3525 3526 The string will be prependend to the path to the .swiftmodule files 3527 that are embedded in the linker output. 3528 3529 If you specified: 3530 swiftmodule_swift = "-Wl,-add_ast_path," 3531 then the "{{swiftmodules}}" expansion for 3532 [ "obj/foo/Foo.swiftmodule" ] 3533 would be 3534 "-Wl,-add_ast_path,obj/foo/Foo.swiftmodule" 3535 3536 outputs [list of strings with substitutions] 3537 Valid for: Linker and compiler tools (required) 3538 3539 An array of names for the output files the tool produces. These are 3540 relative to the build output directory. There must always be at least 3541 one output file. There can be more than one output (a linker might 3542 produce a library and an import library, for example). 3543 3544 This array just declares to GN what files the tool will produce. It is 3545 your responsibility to specify the tool command that actually produces 3546 these files. 3547 3548 If you specify more than one output for shared library links, you 3549 should consider setting link_output, depend_output, and 3550 runtime_outputs. 3551 3552 Example for a compiler tool that produces .obj files: 3553 outputs = [ 3554 "{{source_out_dir}}/{{source_name_part}}.obj" 3555 ] 3556 3557 Example for a linker tool that produces a .dll and a .lib. The use of 3558 {{target_output_name}}, {{output_extension}} and {{output_dir}} allows 3559 the target to override these values. 3560 outputs = [ 3561 "{{output_dir}}/{{target_output_name}}{{output_extension}}", 3562 "{{output_dir}}/{{target_output_name}}.lib", 3563 ] 3564 3565 partial_outputs [list of strings with substitutions] 3566 Valid for: "swift" only 3567 3568 An array of names for the partial outputs the tool produces. These 3569 are relative to the build output directory. The expansion will be 3570 evaluated for each file listed in the "sources" of the target. 3571 3572 This is used to deal with whole module optimization, allowing to 3573 list one object file per source file when whole module optimization 3574 is disabled. 3575 3576 pool [label, optional] 3577 Valid for: all tools (optional) 3578 3579 Label of the pool to use for the tool. Pools are used to limit the 3580 number of tasks that can execute concurrently during the build. 3581 3582 See also "gn help pool". 3583 3584 link_output [string with substitutions] 3585 depend_output [string with substitutions] 3586 Valid for: "solink" only (optional) 3587 3588 These two files specify which of the outputs from the solink tool 3589 should be used for linking and dependency tracking. These should match 3590 entries in the "outputs". If unspecified, the first item in the 3591 "outputs" array will be used for all. See "Separate linking and 3592 dependencies for shared libraries" below for more. 3593 3594 On Windows, where the tools produce a .dll shared library and a .lib 3595 import library, you will want the first two to be the import library 3596 and the third one to be the .dll file. On Linux, if you're not doing 3597 the separate linking/dependency optimization, all of these should be 3598 the .so output. 3599 3600 output_prefix [string] 3601 Valid for: Linker tools (optional) 3602 3603 Prefix to use for the output name. Defaults to empty. This prefix will 3604 be prepended to the name of the target (or the output_name if one is 3605 manually specified for it) if the prefix is not already there. The 3606 result will show up in the {{output_name}} substitution pattern. 3607 3608 Individual targets can opt-out of the output prefix by setting: 3609 output_prefix_override = true 3610 (see "gn help output_prefix_override"). 3611 3612 This is typically used to prepend "lib" to libraries on 3613 Posix systems: 3614 output_prefix = "lib" 3615 3616 precompiled_header_type [string] 3617 Valid for: "cc", "cxx", "objc", "objcxx" 3618 3619 Type of precompiled headers. If undefined or the empty string, 3620 precompiled headers will not be used for this tool. Otherwise use "gcc" 3621 or "msvc". 3622 3623 For precompiled headers to be used for a given target, the target (or a 3624 config applied to it) must also specify a "precompiled_header" and, for 3625 "msvc"-style headers, a "precompiled_source" value. If the type is 3626 "gcc", then both "precompiled_header" and "precompiled_source" must 3627 resolve to the same file, despite the different formats required for 3628 each." 3629 3630 See "gn help precompiled_header" for more. 3631 3632 restat [boolean] 3633 Valid for: all tools (optional, defaults to false) 3634 3635 Requests that Ninja check the file timestamp after this tool has run to 3636 determine if anything changed. Set this if your tool has the ability to 3637 skip writing output if the output file has not changed. 3638 3639 Normally, Ninja will assume that when a tool runs the output be new and 3640 downstream dependents must be rebuild. When this is set to trye, Ninja 3641 can skip rebuilding downstream dependents for input changes that don't 3642 actually affect the output. 3643 3644 Example: 3645 restat = true 3646 3647 rspfile [string with substitutions] 3648 Valid for: all tools except "action" (optional) 3649 3650 Name of the response file. If empty, no response file will be 3651 used. See "rspfile_content". 3652 3653 rspfile_content [string with substitutions] 3654 Valid for: all tools except "action" (required when "rspfile" is used) 3655 3656 The contents to be written to the response file. This may include all 3657 or part of the command to send to the tool which allows you to get 3658 around OS command-line length limits. 3659 3660 This example adds the inputs and libraries to a response file, but 3661 passes the linker flags directly on the command line: 3662 tool("link") { 3663 command = "link -o {{output}} {{ldflags}} @{{output}}.rsp" 3664 rspfile = "{{output}}.rsp" 3665 rspfile_content = "{{inputs}} {{solibs}} {{libs}} {{rlibs}}" 3666 } 3667 3668 runtime_outputs [string list with substitutions] 3669 Valid for: linker tools 3670 3671 If specified, this list is the subset of the outputs that should be 3672 added to runtime deps (see "gn help runtime_deps"). By default (if 3673 runtime_outputs is empty or unspecified), it will be the link_output. 3674 3675 rust_sysroot 3676 Valid for: Rust tools 3677 3678 A path relative to root_out_dir. This is not used in the build 3679 process, but may be used when generating metadata for rust-analyzer. 3680 (See --export-rust-project). It enables such metadata to include 3681 information about the Rust standard library. 3682``` 3683 3684#### **Expansions for tool variables** 3685 3686``` 3687 All paths are relative to the root build directory, which is the current 3688 directory for running all tools. These expansions are available to all tools: 3689 3690 {{label}} 3691 The label of the current target. This is typically used in the 3692 "description" field for link tools. The toolchain will be omitted from 3693 the label for targets in the default toolchain, and will be included 3694 for targets in other toolchains. 3695 3696 {{label_name}} 3697 The short name of the label of the target. This is the part after the 3698 colon. For "//foo/bar:baz" this will be "baz". Unlike 3699 {{target_output_name}}, this is not affected by the "output_prefix" in 3700 the tool or the "output_name" set on the target. 3701 3702 {{label_no_toolchain}} 3703 The label of the current target, never including the toolchain 3704 (otherwise, this is identical to {{label}}). This is used as the module 3705 name when using .modulemap files. 3706 3707 {{output}} 3708 The relative path and name of the output(s) of the current build step. 3709 If there is more than one output, this will expand to a list of all of 3710 them. Example: "out/base/my_file.o" 3711 3712 {{target_gen_dir}} 3713 {{target_out_dir}} 3714 The directory of the generated file and output directories, 3715 respectively, for the current target. There is no trailing slash. See 3716 also {{output_dir}} for linker tools. Example: "out/base/test" 3717 3718 {{target_output_name}} 3719 The short name of the current target with no path information, or the 3720 value of the "output_name" variable if one is specified in the target. 3721 This will include the "output_prefix" if any. See also {{label_name}}. 3722 3723 Example: "libfoo" for the target named "foo" and an output prefix for 3724 the linker tool of "lib". 3725 3726 Compiler tools have the notion of a single input and a single output, along 3727 with a set of compiler-specific flags. The following expansions are 3728 available: 3729 3730 {{asmflags}} 3731 {{cflags}} 3732 {{cflags_c}} 3733 {{cflags_cc}} 3734 {{cflags_objc}} 3735 {{cflags_objcc}} 3736 {{defines}} 3737 {{include_dirs}} 3738 Strings correspond that to the processed flags/defines/include 3739 directories specified for the target. 3740 Example: "--enable-foo --enable-bar" 3741 3742 Defines will be prefixed by "-D" and include directories will be 3743 prefixed by "-I" (these work with Posix tools as well as Microsoft 3744 ones). 3745 3746 {{module_deps}} 3747 {{module_deps_no_self}} 3748 Strings that correspond to the flags necessary to depend upon the Clang 3749 modules referenced by the current target. The "_no_self" version doesn't 3750 include the module for the current target, and can be used to compile 3751 the pcm itself. 3752 3753 {{source}} 3754 The relative path and name of the current input file. 3755 Example: "../../base/my_file.cc" 3756 3757 {{source_file_part}} 3758 The file part of the source including the extension (with no directory 3759 information). 3760 Example: "foo.cc" 3761 3762 {{source_name_part}} 3763 The filename part of the source file with no directory or extension. 3764 Example: "foo" 3765 3766 {{source_gen_dir}} 3767 {{source_out_dir}} 3768 The directory in the generated file and output directories, 3769 respectively, for the current input file. If the source file is in the 3770 same directory as the target is declared in, they will will be the same 3771 as the "target" versions above. Example: "gen/base/test" 3772 3773 Linker tools have multiple inputs and (potentially) multiple outputs. The 3774 static library tool ("alink") is not considered a linker tool. The following 3775 expansions are available: 3776 3777 {{inputs}} 3778 {{inputs_newline}} 3779 Expands to the inputs to the link step. This will be a list of object 3780 files and static libraries. 3781 Example: "obj/foo.o obj/bar.o obj/somelibrary.a" 3782 3783 The "_newline" version will separate the input files with newlines 3784 instead of spaces. This is useful in response files: some linkers can 3785 take a "-filelist" flag which expects newline separated files, and some 3786 Microsoft tools have a fixed-sized buffer for parsing each line of a 3787 response file. 3788 3789 {{ldflags}} 3790 Expands to the processed set of ldflags and library search paths 3791 specified for the target. 3792 Example: "-m64 -fPIC -pthread -L/usr/local/mylib" 3793 3794 {{libs}} 3795 Expands to the list of system libraries to link to. Each will be 3796 prefixed by the "lib_switch". 3797 3798 Example: "-lfoo -lbar" 3799 3800 {{output_dir}} 3801 The value of the "output_dir" variable in the target, or the the value 3802 of the "default_output_dir" value in the tool if the target does not 3803 override the output directory. This will be relative to the 3804 root_build_dir and will not end in a slash. Will be "." for output to 3805 the root_build_dir. 3806 3807 This is subtly different than {{target_out_dir}} which is defined by GN 3808 based on the target's path and not overridable. {{output_dir}} is for 3809 the final output, {{target_out_dir}} is generally for object files and 3810 other outputs. 3811 3812 Usually {{output_dir}} would be defined in terms of either 3813 {{target_out_dir}} or {{root_out_dir}} 3814 3815 {{output_extension}} 3816 The value of the "output_extension" variable in the target, or the 3817 value of the "default_output_extension" value in the tool if the target 3818 does not specify an output extension. 3819 Example: ".so" 3820 3821 {{solibs}} 3822 Extra libraries from shared library dependencies not specified in the 3823 {{inputs}}. This is the list of link_output files from shared libraries 3824 (if the solink tool specifies a "link_output" variable separate from 3825 the "depend_output"). 3826 3827 These should generally be treated the same as libs by your tool. 3828 3829 Example: "libfoo.so libbar.so" 3830 3831 {{rlibs}} 3832 Any Rust .rlibs which need to be linked into a final C++ target. 3833 These should be treated as {{inputs}} except that sometimes 3834 they might have different linker directives applied. 3835 3836 Example: "obj/foo/libfoo.rlib" 3837 3838 {{frameworks}} 3839 Shared libraries packaged as framework bundle. This is principally 3840 used on Apple's platforms (macOS and iOS). All name must be ending 3841 with ".framework" suffix; the suffix will be stripped when expanding 3842 {{frameworks}} and each item will be preceded by "-framework" or 3843 "-weak_framework". 3844 3845 {{swiftmodules}} 3846 Swift .swiftmodule files that needs to be embedded into the binary. 3847 This is necessary to correctly link with object generated by the 3848 Swift compiler (the .swiftmodule file cannot be embedded in object 3849 files directly). Those will be prefixed with "swiftmodule_switch" 3850 value. 3851 3852 The static library ("alink") tool allows {{arflags}} plus the common tool 3853 substitutions. 3854 3855 The copy tool allows the common compiler/linker substitutions, plus 3856 {{source}} which is the source of the copy. The stamp tool allows only the 3857 common tool substitutions. 3858 3859 The copy_bundle_data and compile_xcassets tools only allows the common tool 3860 substitutions. Both tools are required to create iOS/macOS bundles and need 3861 only be defined on those platforms. 3862 3863 The copy_bundle_data tool will be called with one source and needs to copy 3864 (optionally optimizing the data representation) to its output. It may be 3865 called with a directory as input and it needs to be recursively copied. 3866 3867 The compile_xcassets tool will be called with one or more source (each an 3868 asset catalog) that needs to be compiled to a single output. The following 3869 substitutions are available: 3870 3871 {{inputs}} 3872 Expands to the list of .xcassets to use as input to compile the asset 3873 catalog. 3874 3875 {{bundle_product_type}} 3876 Expands to the product_type of the bundle that will contain the 3877 compiled asset catalog. Usually corresponds to the product_type 3878 property of the corresponding create_bundle target. 3879 3880 {{bundle_partial_info_plist}} 3881 Expands to the path to the partial Info.plist generated by the 3882 assets catalog compiler. Usually based on the target_name of 3883 the create_bundle target. 3884 3885 {{xcasset_compiler_flags}} 3886 Expands to the list of flags specified in corresponding 3887 create_bundle target. 3888 3889 The Swift tool has multiple input and outputs. It must have exactly one 3890 output of .swiftmodule type, but can have one or more object file outputs, 3891 in addition to other type of outputs. The following expansions are available: 3892 3893 {{module_name}} 3894 Expands to the string representing the module name of target under 3895 compilation (see "module_name" variable). 3896 3897 {{module_dirs}} 3898 Expands to the list of -I<path> for the target Swift module search 3899 path computed from target dependencies. 3900 3901 {{swiftflags}} 3902 Expands to the list of strings representing Swift compiler flags. 3903 3904 Rust tools have the notion of a single input and a single output, along 3905 with a set of compiler-specific flags. The following expansions are 3906 available: 3907 3908 {{crate_name}} 3909 Expands to the string representing the crate name of target under 3910 compilation. 3911 3912 {{crate_type}} 3913 Expands to the string representing the type of crate for the target 3914 under compilation. 3915 3916 {{externs}} 3917 Expands to the list of --extern flags needed to include addition Rust 3918 libraries in this target. Includes any specified renamed dependencies. 3919 3920 {{rustdeps}} 3921 Expands to the list of -Ldependency=<path> strings needed to compile 3922 this target. 3923 3924 {{rustenv}} 3925 Expands to the list of environment variables. 3926 3927 {{rustflags}} 3928 Expands to the list of strings representing Rust compiler flags. 3929``` 3930 3931#### **Separate linking and dependencies for shared libraries** 3932 3933``` 3934 Shared libraries are special in that not all changes to them require that 3935 dependent targets be re-linked. If the shared library is changed but no 3936 imports or exports are different, dependent code needn't be relinked, which 3937 can speed up the build. 3938 3939 If your link step can output a list of exports from a shared library and 3940 writes the file only if the new one is different, the timestamp of this file 3941 can be used for triggering re-links, while the actual shared library would be 3942 used for linking. 3943 3944 You will need to specify 3945 restat = true 3946 in the linker tool to make this work, so Ninja will detect if the timestamp 3947 of the dependency file has changed after linking (otherwise it will always 3948 assume that running a command updates the output): 3949 3950 tool("solink") { 3951 command = "..." 3952 outputs = [ 3953 "{{output_dir}}/{{target_output_name}}{{output_extension}}", 3954 "{{output_dir}}/{{target_output_name}}{{output_extension}}.TOC", 3955 ] 3956 link_output = 3957 "{{output_dir}}/{{target_output_name}}{{output_extension}}" 3958 depend_output = 3959 "{{output_dir}}/{{target_output_name}}{{output_extension}}.TOC" 3960 restat = true 3961 } 3962``` 3963 3964#### **Example** 3965 3966``` 3967 toolchain("my_toolchain") { 3968 # Put these at the top to apply to all tools below. 3969 lib_switch = "-l" 3970 lib_dir_switch = "-L" 3971 3972 tool("cc") { 3973 command = "gcc {{source}} -o {{output}}" 3974 outputs = [ "{{source_out_dir}}/{{source_name_part}}.o" ] 3975 description = "GCC {{source}}" 3976 } 3977 tool("cxx") { 3978 command = "g++ {{source}} -o {{output}}" 3979 outputs = [ "{{source_out_dir}}/{{source_name_part}}.o" ] 3980 description = "G++ {{source}}" 3981 } 3982 }; 3983``` 3984### <a name="func_toolchain"></a>**toolchain**: Defines a toolchain. 3985 3986``` 3987 A toolchain is a set of commands and build flags used to compile the source 3988 code. The toolchain() function defines these commands. 3989``` 3990 3991#### **Toolchain overview** 3992 3993``` 3994 You can have more than one toolchain in use at once in a build and a target 3995 can exist simultaneously in multiple toolchains. A build file is executed 3996 once for each toolchain it is referenced in so the GN code can vary all 3997 parameters of each target (or which targets exist) on a per-toolchain basis. 3998 3999 When you have a simple build with only one toolchain, the build config file 4000 is loaded only once at the beginning of the build. It must call 4001 set_default_toolchain() (see "gn help set_default_toolchain") to tell GN the 4002 label of the toolchain definition to use. The "toolchain_args" section of the 4003 toolchain definition is ignored. 4004 4005 When a target has a dependency on a target using different toolchain (see "gn 4006 help labels" for how to specify this), GN will start a build using that 4007 secondary toolchain to resolve the target. GN will load the build config file 4008 with the build arguments overridden as specified in the toolchain_args. 4009 Because the default toolchain is already known, calls to 4010 set_default_toolchain() are ignored. 4011 4012 To load a file in an alternate toolchain, GN does the following: 4013 4014 1. Loads the file with the toolchain definition in it (as determined by the 4015 toolchain label). 4016 2. Re-runs the master build configuration file, applying the arguments 4017 specified by the toolchain_args section of the toolchain definition. 4018 3. Loads the destination build file in the context of the configuration file 4019 in the previous step. 4020 4021 The toolchain configuration is two-way. In the default toolchain (i.e. the 4022 main build target) the configuration flows from the build config file to the 4023 toolchain. The build config file looks at the state of the build (OS type, 4024 CPU architecture, etc.) and decides which toolchain to use (via 4025 set_default_toolchain()). In secondary toolchains, the configuration flows 4026 from the toolchain to the build config file: the "toolchain_args" in the 4027 toolchain definition specifies the arguments to re-invoke the build. 4028``` 4029 4030#### **Functions and variables** 4031 4032``` 4033 tool() 4034 The tool() function call specifies the commands to run for a given step. See 4035 "gn help tool". 4036 4037 toolchain_args [scope] 4038 Overrides for build arguments to pass to the toolchain when invoking it. 4039 This is a variable of type "scope" where the variable names correspond to 4040 variables in declare_args() blocks. 4041 4042 When you specify a target using an alternate toolchain, the master build 4043 configuration file is re-interpreted in the context of that toolchain. 4044 toolchain_args allows you to control the arguments passed into this 4045 alternate invocation of the build. 4046 4047 Any default system arguments or arguments passed in via "gn args" will also 4048 be passed to the alternate invocation unless explicitly overridden by 4049 toolchain_args. 4050 4051 The toolchain_args will be ignored when the toolchain being defined is the 4052 default. In this case, it's expected you want the default argument values. 4053 4054 See also "gn help buildargs" for an overview of these arguments. 4055 4056 propagates_configs [boolean, default=false] 4057 Determines whether public_configs and all_dependent_configs in this 4058 toolchain propagate to targets in other toolchains. 4059 4060 When false (the default), this toolchain will not propagate any configs to 4061 targets in other toolchains that depend on it targets inside this 4062 toolchain. This matches the most common usage of toolchains where they 4063 represent different architectures or compilers and the settings that apply 4064 to one won't necessarily apply to others. 4065 4066 When true, configs (public and all-dependent) will cross the boundary out 4067 of this toolchain as if the toolchain boundary wasn't there. This only 4068 affects one direction of dependencies: a toolchain can't control whether 4069 it accepts such configs, only whether it pushes them. The build is 4070 responsible for ensuring that any external targets depending on targets in 4071 this toolchain are compatible with the compiler flags, etc. that may be 4072 propagated. 4073 4074 deps [string list] 4075 Dependencies of this toolchain. These dependencies will be resolved before 4076 any target in the toolchain is compiled. To avoid circular dependencies 4077 these must be targets defined in another toolchain. 4078 4079 This is expressed as a list of targets, and generally these targets will 4080 always specify a toolchain: 4081 deps = [ "//foo/bar:baz(//build/toolchain:bootstrap)" ] 4082 4083 This concept is somewhat inefficient to express in Ninja (it requires a lot 4084 of duplicate of rules) so should only be used when absolutely necessary. 4085``` 4086 4087#### **Example of defining a toolchain** 4088 4089``` 4090 toolchain("32") { 4091 tool("cc") { 4092 command = "gcc {{source}}" 4093 ... 4094 } 4095 4096 toolchain_args = { 4097 use_doom_melon = true # Doom melon always required for 32-bit builds. 4098 current_cpu = "x86" 4099 } 4100 } 4101 4102 toolchain("64") { 4103 tool("cc") { 4104 command = "gcc {{source}}" 4105 ... 4106 } 4107 4108 toolchain_args = { 4109 # use_doom_melon is not overridden here, it will take the default. 4110 current_cpu = "x64" 4111 } 4112 } 4113``` 4114 4115#### **Example of cross-toolchain dependencies** 4116 4117``` 4118 If a 64-bit target wants to depend on a 32-bit binary, it would specify a 4119 dependency using data_deps (data deps are like deps that are only needed at 4120 runtime and aren't linked, since you can't link a 32-bit and a 64-bit 4121 library). 4122 4123 executable("my_program") { 4124 ... 4125 if (target_cpu == "x64") { 4126 # The 64-bit build needs this 32-bit helper. 4127 data_deps = [ ":helper(//toolchains:32)" ] 4128 } 4129 } 4130 4131 if (target_cpu == "x86") { 4132 # Our helper library is only compiled in 32-bits. 4133 shared_library("helper") { 4134 ... 4135 } 4136 } 4137``` 4138### <a name="func_write_file"></a>**write_file**: Write a file to disk. 4139 4140``` 4141 write_file(filename, data, output_conversion = "") 4142 4143 If data is a list, the list will be written one-item-per-line with no quoting 4144 or brackets. 4145 4146 If the file exists and the contents are identical to that being written, the 4147 file will not be updated. This will prevent unnecessary rebuilds of targets 4148 that depend on this file. 4149 4150 One use for write_file is to write a list of inputs to an script that might 4151 be too long for the command line. However, it is preferable to use response 4152 files for this purpose. See "gn help response_file_contents". 4153``` 4154 4155#### **Arguments** 4156 4157``` 4158 filename 4159 Filename to write. This must be within the output directory. 4160 4161 data 4162 The list or string to write. 4163 4164 output_conversion 4165 Controls how the output is written. See `gn help io_conversion`. 4166``` 4167## <a name="predefined_variables"></a>Built-in predefined variables 4168 4169### <a name="var_current_cpu"></a>**current_cpu**: The processor architecture of the current toolchain. 4170 4171``` 4172 The build configuration usually sets this value based on the value of 4173 "host_cpu" (see "gn help host_cpu") and then threads this through the 4174 toolchain definitions to ensure that it always reflects the appropriate 4175 value. 4176 4177 This value is not used internally by GN for any purpose. It is set to the 4178 empty string ("") by default but is declared so that it can be overridden on 4179 the command line if so desired. 4180 4181 See "gn help target_cpu" for a list of common values returned. 4182``` 4183### <a name="var_current_os"></a>**current_os**: The operating system of the current toolchain. 4184 4185``` 4186 The build configuration usually sets this value based on the value of 4187 "target_os" (see "gn help target_os"), and then threads this through the 4188 toolchain definitions to ensure that it always reflects the appropriate 4189 value. 4190 4191 This value is not used internally by GN for any purpose. It is set to the 4192 empty string ("") by default but is declared so that it can be overridden on 4193 the command line if so desired. 4194 4195 See "gn help target_os" for a list of common values returned. 4196``` 4197### <a name="var_current_toolchain"></a>**current_toolchain**: Label of the current toolchain. 4198 4199``` 4200 A fully-qualified label representing the current toolchain. You can use this 4201 to make toolchain-related decisions in the build. See also 4202 "default_toolchain". 4203``` 4204 4205#### **Example** 4206 4207``` 4208 if (current_toolchain == "//build:64_bit_toolchain") { 4209 executable("output_thats_64_bit_only") { 4210 ... 4211``` 4212### <a name="var_default_toolchain"></a>**default_toolchain**: [string] Label of the default toolchain. 4213 4214``` 4215 A fully-qualified label representing the default toolchain, which may not 4216 necessarily be the current one (see "current_toolchain"). 4217``` 4218### <a name="var_gn_version"></a>**gn_version**: [number] The version of gn. 4219 4220``` 4221 Corresponds to the number printed by `gn --version`. 4222``` 4223 4224#### **Example** 4225 4226``` 4227 assert(gn_version >= 1700, "need GN version 1700 for the frobulate feature") 4228``` 4229### <a name="var_host_cpu"></a>**host_cpu**: The processor architecture that GN is running on. 4230 4231``` 4232 This is value is exposed so that cross-compile toolchains can access the host 4233 architecture when needed. 4234 4235 The value should generally be considered read-only, but it can be overridden 4236 in order to handle unusual cases where there might be multiple plausible 4237 values for the host architecture (e.g., if you can do either 32-bit or 64-bit 4238 builds). The value is not used internally by GN for any purpose. 4239``` 4240 4241#### **Some possible values** 4242 4243``` 4244 - "x64" 4245 - "x86" 4246``` 4247### <a name="var_host_os"></a>**host_os**: [string] The operating system that GN is running on. 4248 4249``` 4250 This value is exposed so that cross-compiles can access the host build 4251 system's settings. 4252 4253 This value should generally be treated as read-only. It, however, is not used 4254 internally by GN for any purpose. 4255``` 4256 4257#### **Some possible values** 4258 4259``` 4260 - "linux" 4261 - "mac" 4262 - "win" 4263``` 4264### <a name="var_invoker"></a>**invoker**: [string] The invoking scope inside a template. 4265 4266``` 4267 Inside a template invocation, this variable refers to the scope of the 4268 invoker of the template. Outside of template invocations, this variable is 4269 undefined. 4270 4271 All of the variables defined inside the template invocation are accessible as 4272 members of the "invoker" scope. This is the way that templates read values 4273 set by the callers. 4274 4275 This is often used with "defined" to see if a value is set on the invoking 4276 scope. 4277 4278 See "gn help template" for more examples. 4279``` 4280 4281#### **Example** 4282 4283``` 4284 template("my_template") { 4285 print(invoker.sources) # Prints [ "a.cc", "b.cc" ] 4286 print(defined(invoker.foo)) # Prints false. 4287 print(defined(invoker.bar)) # Prints true. 4288 } 4289 4290 my_template("doom_melon") { 4291 sources = [ "a.cc", "b.cc" ] 4292 bar = 123 4293 } 4294``` 4295### <a name="var_python_path"></a>**python_path**: Absolute path of Python. 4296 4297``` 4298 Normally used in toolchain definitions if running some command requires 4299 Python. You will normally not need this when invoking scripts since GN 4300 automatically finds it for you. 4301``` 4302### <a name="var_root_build_dir"></a>**root_build_dir**: [string] Directory where build commands are run. 4303 4304``` 4305 This is the root build output directory which will be the current directory 4306 when executing all compilers and scripts. 4307 4308 Most often this is used with rebase_path (see "gn help rebase_path") to 4309 convert arguments to be relative to a script's current directory. 4310``` 4311### <a name="var_root_gen_dir"></a>**root_gen_dir**: Directory for the toolchain's generated files. 4312 4313``` 4314 Absolute path to the root of the generated output directory tree for the 4315 current toolchain. An example would be "//out/Debug/gen" for the default 4316 toolchain, or "//out/Debug/arm/gen" for the "arm" toolchain. 4317 4318 This is primarily useful for setting up include paths for generated files. If 4319 you are passing this to a script, you will want to pass it through 4320 rebase_path() (see "gn help rebase_path") to convert it to be relative to the 4321 build directory. 4322 4323 See also "target_gen_dir" which is usually a better location for generated 4324 files. It will be inside the root generated dir. 4325``` 4326### <a name="var_root_out_dir"></a>**root_out_dir**: [string] Root directory for toolchain output files. 4327 4328``` 4329 Absolute path to the root of the output directory tree for the current 4330 toolchain. It will not have a trailing slash. 4331 4332 For the default toolchain this will be the same as the root_build_dir. An 4333 example would be "//out/Debug" for the default toolchain, or 4334 "//out/Debug/arm" for the "arm" toolchain. 4335 4336 This is primarily useful for setting up script calls. If you are passing this 4337 to a script, you will want to pass it through rebase_path() (see "gn help 4338 rebase_path") to convert it to be relative to the build directory. 4339 4340 See also "target_out_dir" which is usually a better location for output 4341 files. It will be inside the root output dir. 4342``` 4343 4344#### **Example** 4345 4346``` 4347 action("myscript") { 4348 # Pass the output dir to the script. 4349 args = [ "-o", rebase_path(root_out_dir, root_build_dir) ] 4350 } 4351``` 4352### <a name="var_target_cpu"></a>**target_cpu**: The desired cpu architecture for the build. 4353 4354``` 4355 This value should be used to indicate the desired architecture for the 4356 primary objects of the build. It will match the cpu architecture of the 4357 default toolchain, but not necessarily the current toolchain. 4358 4359 In many cases, this is the same as "host_cpu", but in the case of 4360 cross-compiles, this can be set to something different. This value is 4361 different from "current_cpu" in that it does not change based on the current 4362 toolchain. When writing rules, "current_cpu" should be used rather than 4363 "target_cpu" most of the time. 4364 4365 This value is not used internally by GN for any purpose, so it may be set to 4366 whatever value is needed for the build. GN defaults this value to the empty 4367 string ("") and the configuration files should set it to an appropriate value 4368 (e.g., setting it to the value of "host_cpu") if it is not overridden on the 4369 command line or in the args.gn file. 4370``` 4371 4372#### **Possible values** 4373 4374``` 4375 - "x86" 4376 - "x64" 4377 - "arm" 4378 - "arm64" 4379 - "mipsel" 4380``` 4381### <a name="var_target_gen_dir"></a>**target_gen_dir**: Directory for a target's generated files. 4382 4383``` 4384 Absolute path to the target's generated file directory. This will be the 4385 "root_gen_dir" followed by the relative path to the current build file. If 4386 your file is in "//tools/doom_melon" then target_gen_dir would be 4387 "//out/Debug/gen/tools/doom_melon". It will not have a trailing slash. 4388 4389 This is primarily useful for setting up include paths for generated files. If 4390 you are passing this to a script, you will want to pass it through 4391 rebase_path() (see "gn help rebase_path") to convert it to be relative to the 4392 build directory. 4393 4394 See also "gn help root_gen_dir". 4395``` 4396 4397#### **Example** 4398 4399``` 4400 action("myscript") { 4401 # Pass the generated output dir to the script. 4402 args = [ "-o", rebase_path(target_gen_dir, root_build_dir) ] 4403 } 4404``` 4405### <a name="var_target_name"></a>**target_name**: [string] The name of the current target. 4406 4407``` 4408 Inside a target or template invocation, this variable refers to the name 4409 given to the target or template invocation. Outside of these, this variable 4410 is undefined. 4411 4412 This is most often used in template definitions to name targets defined in 4413 the template based on the name of the invocation. This is necessary both to 4414 ensure generated targets have unique names and to generate a target with the 4415 exact name of the invocation that other targets can depend on. 4416 4417 Be aware that this value will always reflect the innermost scope. So when 4418 defining a target inside a template, target_name will refer to the target 4419 rather than the template invocation. To get the name of the template 4420 invocation in this case, you should save target_name to a temporary variable 4421 outside of any target definitions. 4422 4423 See "gn help template" for more examples. 4424``` 4425 4426#### **Example** 4427 4428``` 4429 executable("doom_melon") { 4430 print(target_name) # Prints "doom_melon". 4431 } 4432 4433 template("my_template") { 4434 print(target_name) # Prints "space_ray" when invoked below. 4435 4436 executable(target_name + "_impl") { 4437 print(target_name) # Prints "space_ray_impl". 4438 } 4439 } 4440 4441 my_template("space_ray") { 4442 } 4443``` 4444### <a name="var_target_os"></a>**target_os**: The desired operating system for the build. 4445 4446``` 4447 This value should be used to indicate the desired operating system for the 4448 primary object(s) of the build. It will match the OS of the default 4449 toolchain. 4450 4451 In many cases, this is the same as "host_os", but in the case of 4452 cross-compiles, it may be different. This variable differs from "current_os" 4453 in that it can be referenced from inside any toolchain and will always return 4454 the initial value. 4455 4456 This should be set to the most specific value possible. So, "android" or 4457 "chromeos" should be used instead of "linux" where applicable, even though 4458 Android and ChromeOS are both Linux variants. This can mean that one needs to 4459 write 4460 4461 if (target_os == "android" || target_os == "linux") { 4462 # ... 4463 } 4464 4465 and so forth. 4466 4467 This value is not used internally by GN for any purpose, so it may be set to 4468 whatever value is needed for the build. GN defaults this value to the empty 4469 string ("") and the configuration files should set it to an appropriate value 4470 (e.g., setting it to the value of "host_os") if it is not set via the command 4471 line or in the args.gn file. 4472``` 4473 4474#### **Possible values** 4475 4476``` 4477 - "android" 4478 - "chromeos" 4479 - "ios" 4480 - "linux" 4481 - "nacl" 4482 - "mac" 4483 - "win" 4484``` 4485### <a name="var_target_out_dir"></a>**target_out_dir**: [string] Directory for target output files. 4486 4487``` 4488 Absolute path to the target's generated file directory. If your current 4489 target is in "//tools/doom_melon" then this value might be 4490 "//out/Debug/obj/tools/doom_melon". It will not have a trailing slash. 4491 4492 This is primarily useful for setting up arguments for calling scripts. If you 4493 are passing this to a script, you will want to pass it through rebase_path() 4494 (see "gn help rebase_path") to convert it to be relative to the build 4495 directory. 4496 4497 See also "gn help root_out_dir". 4498``` 4499 4500#### **Example** 4501 4502``` 4503 action("myscript") { 4504 # Pass the output dir to the script. 4505 args = [ "-o", rebase_path(target_out_dir, root_build_dir) ] 4506 } 4507``` 4508## <a name="target_variables"></a>Variables you set in targets 4509 4510### <a name="var_aliased_deps"></a>**aliased_deps**: [scope] Set of crate-dependency pairs. 4511 4512``` 4513 Valid for `rust_library` targets and `executable`, `static_library`, and 4514 `shared_library` targets that contain Rust sources. 4515 4516 A scope, each key indicating the renamed crate and the corresponding value 4517 specifying the label of the dependency producing the relevant binary. 4518 4519 All dependencies listed in this field *must* be listed as deps of the target. 4520 4521 executable("foo") { 4522 sources = [ "main.rs" ] 4523 deps = [ "//bar" ] 4524 } 4525 4526 This target would compile the `foo` crate with the following `extern` flag: 4527 `rustc ...command... --extern bar=<build_out_dir>/obj/bar` 4528 4529 executable("foo") { 4530 sources = [ "main.rs" ] 4531 deps = [ ":bar" ] 4532 aliased_deps = { 4533 bar_renamed = ":bar" 4534 } 4535 } 4536 4537 With the addition of `aliased_deps`, above target would instead compile with: 4538 `rustc ...command... --extern bar_renamed=<build_out_dir>/obj/bar` 4539``` 4540### <a name="var_all_dependent_configs"></a>**all_dependent_configs**: Configs to be forced on dependents. 4541 4542``` 4543 A list of config labels. 4544 4545 All targets depending on this one, and recursively, all targets depending on 4546 those, will have the configs listed in this variable added to them. These 4547 configs will also apply to the current target. 4548 4549 This addition happens in a second phase once a target and all of its 4550 dependencies have been resolved. Therefore, a target will not see these 4551 force-added configs in their "configs" variable while the script is running, 4552 and they can not be removed. As a result, this capability should generally 4553 only be used to add defines and include directories necessary to compile a 4554 target's headers. 4555 4556 See also "public_configs". 4557``` 4558 4559#### **Ordering of flags and values** 4560 4561``` 4562 1. Those set on the current target (not in a config). 4563 2. Those set on the "configs" on the target in order that the 4564 configs appear in the list. 4565 3. Those set on the "all_dependent_configs" on the target in order 4566 that the configs appear in the list. 4567 4. Those set on the "public_configs" on the target in order that 4568 those configs appear in the list. 4569 5. all_dependent_configs pulled from dependencies, in the order of 4570 the "deps" list. This is done recursively. If a config appears 4571 more than once, only the first occurrence will be used. 4572 6. public_configs pulled from dependencies, in the order of the 4573 "deps" list. If a dependency is public, they will be applied 4574 recursively. 4575``` 4576### <a name="var_allow_circular_includes_from"></a>**allow_circular_includes_from**: Permit includes from deps. 4577 4578``` 4579 A list of target labels. Must be a subset of the target's "deps". These 4580 targets will be permitted to include headers from the current target despite 4581 the dependency going in the opposite direction. 4582 4583 When you use this, both targets must be included in a final binary for it to 4584 link. To keep linker errors from happening, it is good practice to have all 4585 external dependencies depend only on one of the two targets, and to set the 4586 visibility on the other to enforce this. Thus the targets will always be 4587 linked together in any output. 4588``` 4589 4590#### **Details** 4591 4592``` 4593 Normally, for a file in target A to include a file from target B, A must list 4594 B as a dependency. This invariant is enforced by the "gn check" command (and 4595 the --check flag to "gn gen" -- see "gn help check"). 4596 4597 Sometimes, two targets might be the same unit for linking purposes (two 4598 source sets or static libraries that would always be linked together in a 4599 final executable or shared library) and they each include headers from the 4600 other: you want A to be able to include B's headers, and B to include A's 4601 headers. This is not an ideal situation but is sometimes unavoidable. 4602 4603 This list, if specified, lists which of the dependencies of the current 4604 target can include header files from the current target. That is, if A 4605 depends on B, B can only include headers from A if it is in A's 4606 allow_circular_includes_from list. Normally includes must follow the 4607 direction of dependencies, this flag allows them to go in the opposite 4608 direction. 4609``` 4610 4611#### **Danger** 4612 4613``` 4614 In the above example, A's headers are likely to include headers from A's 4615 dependencies. Those dependencies may have public_configs that apply flags, 4616 defines, and include paths that make those headers work properly. 4617 4618 With allow_circular_includes_from, B can include A's headers, and 4619 transitively from A's dependencies, without having the dependencies that 4620 would bring in the public_configs those headers need. The result may be 4621 errors or inconsistent builds. 4622 4623 So when you use allow_circular_includes_from, make sure that any compiler 4624 settings, flags, and include directories are the same between both targets 4625 (consider putting such things in a shared config they can both reference). 4626 Make sure the dependencies are also the same (you might consider a group to 4627 collect such dependencies they both depend on). 4628``` 4629 4630#### **Example** 4631 4632``` 4633 source_set("a") { 4634 deps = [ ":b", ":a_b_shared_deps" ] 4635 allow_circular_includes_from = [ ":b" ] 4636 ... 4637 } 4638 4639 source_set("b") { 4640 deps = [ ":a_b_shared_deps" ] 4641 # Sources here can include headers from a despite lack of deps. 4642 ... 4643 } 4644 4645 group("a_b_shared_deps") { 4646 public_deps = [ ":c" ] 4647 } 4648``` 4649### <a name="var_arflags"></a>**arflags**: Arguments passed to static_library archiver. 4650 4651``` 4652 A list of flags passed to the archive/lib command that creates static 4653 libraries. 4654 4655 arflags are NOT pushed to dependents, so applying arflags to source sets or 4656 any other target type will be a no-op. As with ldflags, you could put the 4657 arflags in a config and set that as a public or "all dependent" config, but 4658 that will likely not be what you want. If you have a chain of static 4659 libraries dependent on each other, this can cause the flags to propagate up 4660 to other static libraries. Due to the nature of how arflags are typically 4661 used, you will normally want to apply them directly on static_library targets 4662 themselves. 4663``` 4664 4665#### **Ordering of flags and values** 4666 4667``` 4668 1. Those set on the current target (not in a config). 4669 2. Those set on the "configs" on the target in order that the 4670 configs appear in the list. 4671 3. Those set on the "all_dependent_configs" on the target in order 4672 that the configs appear in the list. 4673 4. Those set on the "public_configs" on the target in order that 4674 those configs appear in the list. 4675 5. all_dependent_configs pulled from dependencies, in the order of 4676 the "deps" list. This is done recursively. If a config appears 4677 more than once, only the first occurrence will be used. 4678 6. public_configs pulled from dependencies, in the order of the 4679 "deps" list. If a dependency is public, they will be applied 4680 recursively. 4681``` 4682### <a name="var_args"></a>**args**: (target variable) Arguments passed to an action. 4683 4684``` 4685 For action and action_foreach targets, args is the list of arguments to pass 4686 to the script. Typically you would use source expansion (see "gn help 4687 source_expansion") to insert the source file names. 4688 4689 See also "gn help action" and "gn help action_foreach". 4690``` 4691### <a name="var_asmflags"></a>**asmflags**: Flags passed to the assembler. 4692 4693``` 4694 A list of strings. 4695 4696 "asmflags" are passed to any invocation of a tool that takes an .asm or .S 4697 file as input. 4698``` 4699 4700#### **Ordering of flags and values** 4701 4702``` 4703 1. Those set on the current target (not in a config). 4704 2. Those set on the "configs" on the target in order that the 4705 configs appear in the list. 4706 3. Those set on the "all_dependent_configs" on the target in order 4707 that the configs appear in the list. 4708 4. Those set on the "public_configs" on the target in order that 4709 those configs appear in the list. 4710 5. all_dependent_configs pulled from dependencies, in the order of 4711 the "deps" list. This is done recursively. If a config appears 4712 more than once, only the first occurrence will be used. 4713 6. public_configs pulled from dependencies, in the order of the 4714 "deps" list. If a dependency is public, they will be applied 4715 recursively. 4716``` 4717### <a name="var_assert_no_deps"></a>**assert_no_deps**: Ensure no deps on these targets. 4718 4719``` 4720 A list of label patterns. 4721 4722 This list is a list of patterns that must not match any of the transitive 4723 dependencies of the target. These include all public, private, and data 4724 dependencies, and cross shared library boundaries. This allows you to express 4725 that undesirable code isn't accidentally added to downstream dependencies in 4726 a way that might otherwise be difficult to notice. 4727 4728 Checking does not cross executable boundaries. If a target depends on an 4729 executable, it's assumed that the executable is a tool that is producing part 4730 of the build rather than something that is linked and distributed. This 4731 allows assert_no_deps to express what is distributed in the final target 4732 rather than depend on the internal build steps (which may include 4733 non-distributable code). 4734 4735 See "gn help label_pattern" for the format of the entries in the list. These 4736 patterns allow blacklisting individual targets or whole directory 4737 hierarchies. 4738 4739 Sometimes it is desirable to enforce that many targets have no dependencies 4740 on a target or set of targets. One efficient way to express this is to create 4741 a group with the assert_no_deps rule on it, and make that group depend on all 4742 targets you want to apply that assertion to. 4743``` 4744 4745#### **Example** 4746 4747``` 4748 executable("doom_melon") { 4749 deps = [ "//foo:bar" ] 4750 ... 4751 assert_no_deps = [ 4752 "//evil/*", # Don't link any code from the evil directory. 4753 "//foo:test_support", # This target is also disallowed. 4754 ] 4755 } 4756``` 4757### <a name="var_bridge_header"></a>**bridge_header**: [string] Path to C/Objective-C compatibility header. 4758 4759``` 4760 Valid for binary targets that contain Swift sources. 4761 4762 Path to an header that includes C/Objective-C functions and types that 4763 needs to be made available to the Swift module. 4764``` 4765### <a name="var_bundle_contents_dir"></a>**bundle_contents_dir**: Expansion of {{bundle_contents_dir}} in 4766``` 4767 create_bundle. 4768 4769 A string corresponding to a path in $root_build_dir. 4770 4771 This string is used by the "create_bundle" target to expand the 4772 {{bundle_contents_dir}} of the "bundle_data" target it depends on. This must 4773 correspond to a path under "bundle_root_dir". 4774 4775 See "gn help bundle_root_dir" for examples. 4776``` 4777### <a name="var_bundle_deps_filter"></a>**bundle_deps_filter**: [label list] A list of labels that are filtered out. 4778 4779``` 4780 A list of target labels. 4781 4782 This list contains target label patterns that should be filtered out when 4783 creating the bundle. Any target matching one of those label will be removed 4784 from the dependencies of the create_bundle target. 4785 4786 This is mostly useful when creating application extension bundle as the 4787 application extension has access to runtime resources from the application 4788 bundle and thus do not require a second copy. 4789 4790 See "gn help create_bundle" for more information. 4791``` 4792 4793#### **Example** 4794 4795``` 4796 create_bundle("today_extension") { 4797 deps = [ 4798 "//base" 4799 ] 4800 bundle_root_dir = "$root_out_dir/today_extension.appex" 4801 bundle_deps_filter = [ 4802 # The extension uses //base but does not use any function calling into 4803 # third_party/icu and thus does not need the icudtl.dat file. 4804 "//third_party/icu:icudata", 4805 ] 4806 } 4807``` 4808### <a name="var_bundle_executable_dir"></a>**bundle_executable_dir** 4809 4810``` 4811 bundle_executable_dir: Expansion of {{bundle_executable_dir}} in 4812 create_bundle. 4813 4814 A string corresponding to a path in $root_build_dir. 4815 4816 This string is used by the "create_bundle" target to expand the 4817 {{bundle_executable_dir}} of the "bundle_data" target it depends on. This 4818 must correspond to a path under "bundle_root_dir". 4819 4820 See "gn help bundle_root_dir" for examples. 4821``` 4822### <a name="var_bundle_resources_dir"></a>**bundle_resources_dir** 4823 4824``` 4825 bundle_resources_dir: Expansion of {{bundle_resources_dir}} in 4826 create_bundle. 4827 4828 A string corresponding to a path in $root_build_dir. 4829 4830 This string is used by the "create_bundle" target to expand the 4831 {{bundle_resources_dir}} of the "bundle_data" target it depends on. This must 4832 correspond to a path under "bundle_root_dir". 4833 4834 See "gn help bundle_root_dir" for examples. 4835``` 4836### <a name="var_bundle_root_dir"></a>**bundle_root_dir**: Expansion of {{bundle_root_dir}} in create_bundle. 4837 4838``` 4839 A string corresponding to a path in root_build_dir. 4840 4841 This string is used by the "create_bundle" target to expand the 4842 {{bundle_root_dir}} of the "bundle_data" target it depends on. This must 4843 correspond to a path under root_build_dir. 4844``` 4845 4846#### **Example** 4847 4848``` 4849 bundle_data("info_plist") { 4850 sources = [ "Info.plist" ] 4851 outputs = [ "{{bundle_contents_dir}}/Info.plist" ] 4852 } 4853 4854 create_bundle("doom_melon.app") { 4855 deps = [ ":info_plist" ] 4856 bundle_root_dir = "${root_build_dir}/doom_melon.app" 4857 bundle_contents_dir = "${bundle_root_dir}/Contents" 4858 bundle_resources_dir = "${bundle_contents_dir}/Resources" 4859 bundle_executable_dir = "${bundle_contents_dir}/MacOS" 4860 } 4861``` 4862### <a name="var_cflags"></a>**cflags***: Flags passed to the C compiler. 4863 4864``` 4865 A list of strings. 4866 4867 "cflags" are passed to all invocations of the C, C++, Objective C, and 4868 Objective C++ compilers. 4869 4870 To target one of these variants individually, use "cflags_c", "cflags_cc", 4871 "cflags_objc", and "cflags_objcc", respectively. These variant-specific 4872 versions of cflags* will be appended on the compiler command line after 4873 "cflags". 4874 4875 See also "asmflags" for flags for assembly-language files and "swiftflags" 4876 for swift files. 4877``` 4878 4879#### **Ordering of flags and values** 4880 4881``` 4882 1. Those set on the current target (not in a config). 4883 2. Those set on the "configs" on the target in order that the 4884 configs appear in the list. 4885 3. Those set on the "all_dependent_configs" on the target in order 4886 that the configs appear in the list. 4887 4. Those set on the "public_configs" on the target in order that 4888 those configs appear in the list. 4889 5. all_dependent_configs pulled from dependencies, in the order of 4890 the "deps" list. This is done recursively. If a config appears 4891 more than once, only the first occurrence will be used. 4892 6. public_configs pulled from dependencies, in the order of the 4893 "deps" list. If a dependency is public, they will be applied 4894 recursively. 4895``` 4896### <a name="var_cflags_c"></a>**cflags***: Flags passed to the C compiler. 4897 4898``` 4899 A list of strings. 4900 4901 "cflags" are passed to all invocations of the C, C++, Objective C, and 4902 Objective C++ compilers. 4903 4904 To target one of these variants individually, use "cflags_c", "cflags_cc", 4905 "cflags_objc", and "cflags_objcc", respectively. These variant-specific 4906 versions of cflags* will be appended on the compiler command line after 4907 "cflags". 4908 4909 See also "asmflags" for flags for assembly-language files and "swiftflags" 4910 for swift files. 4911``` 4912 4913#### **Ordering of flags and values** 4914 4915``` 4916 1. Those set on the current target (not in a config). 4917 2. Those set on the "configs" on the target in order that the 4918 configs appear in the list. 4919 3. Those set on the "all_dependent_configs" on the target in order 4920 that the configs appear in the list. 4921 4. Those set on the "public_configs" on the target in order that 4922 those configs appear in the list. 4923 5. all_dependent_configs pulled from dependencies, in the order of 4924 the "deps" list. This is done recursively. If a config appears 4925 more than once, only the first occurrence will be used. 4926 6. public_configs pulled from dependencies, in the order of the 4927 "deps" list. If a dependency is public, they will be applied 4928 recursively. 4929``` 4930### <a name="var_cflags_cc"></a>**cflags***: Flags passed to the C compiler. 4931 4932``` 4933 A list of strings. 4934 4935 "cflags" are passed to all invocations of the C, C++, Objective C, and 4936 Objective C++ compilers. 4937 4938 To target one of these variants individually, use "cflags_c", "cflags_cc", 4939 "cflags_objc", and "cflags_objcc", respectively. These variant-specific 4940 versions of cflags* will be appended on the compiler command line after 4941 "cflags". 4942 4943 See also "asmflags" for flags for assembly-language files and "swiftflags" 4944 for swift files. 4945``` 4946 4947#### **Ordering of flags and values** 4948 4949``` 4950 1. Those set on the current target (not in a config). 4951 2. Those set on the "configs" on the target in order that the 4952 configs appear in the list. 4953 3. Those set on the "all_dependent_configs" on the target in order 4954 that the configs appear in the list. 4955 4. Those set on the "public_configs" on the target in order that 4956 those configs appear in the list. 4957 5. all_dependent_configs pulled from dependencies, in the order of 4958 the "deps" list. This is done recursively. If a config appears 4959 more than once, only the first occurrence will be used. 4960 6. public_configs pulled from dependencies, in the order of the 4961 "deps" list. If a dependency is public, they will be applied 4962 recursively. 4963``` 4964### <a name="var_cflags_objc"></a>**cflags***: Flags passed to the C compiler. 4965 4966``` 4967 A list of strings. 4968 4969 "cflags" are passed to all invocations of the C, C++, Objective C, and 4970 Objective C++ compilers. 4971 4972 To target one of these variants individually, use "cflags_c", "cflags_cc", 4973 "cflags_objc", and "cflags_objcc", respectively. These variant-specific 4974 versions of cflags* will be appended on the compiler command line after 4975 "cflags". 4976 4977 See also "asmflags" for flags for assembly-language files and "swiftflags" 4978 for swift files. 4979``` 4980 4981#### **Ordering of flags and values** 4982 4983``` 4984 1. Those set on the current target (not in a config). 4985 2. Those set on the "configs" on the target in order that the 4986 configs appear in the list. 4987 3. Those set on the "all_dependent_configs" on the target in order 4988 that the configs appear in the list. 4989 4. Those set on the "public_configs" on the target in order that 4990 those configs appear in the list. 4991 5. all_dependent_configs pulled from dependencies, in the order of 4992 the "deps" list. This is done recursively. If a config appears 4993 more than once, only the first occurrence will be used. 4994 6. public_configs pulled from dependencies, in the order of the 4995 "deps" list. If a dependency is public, they will be applied 4996 recursively. 4997``` 4998### <a name="var_cflags_objcc"></a>**cflags***: Flags passed to the C compiler. 4999 5000``` 5001 A list of strings. 5002 5003 "cflags" are passed to all invocations of the C, C++, Objective C, and 5004 Objective C++ compilers. 5005 5006 To target one of these variants individually, use "cflags_c", "cflags_cc", 5007 "cflags_objc", and "cflags_objcc", respectively. These variant-specific 5008 versions of cflags* will be appended on the compiler command line after 5009 "cflags". 5010 5011 See also "asmflags" for flags for assembly-language files and "swiftflags" 5012 for swift files. 5013``` 5014 5015#### **Ordering of flags and values** 5016 5017``` 5018 1. Those set on the current target (not in a config). 5019 2. Those set on the "configs" on the target in order that the 5020 configs appear in the list. 5021 3. Those set on the "all_dependent_configs" on the target in order 5022 that the configs appear in the list. 5023 4. Those set on the "public_configs" on the target in order that 5024 those configs appear in the list. 5025 5. all_dependent_configs pulled from dependencies, in the order of 5026 the "deps" list. This is done recursively. If a config appears 5027 more than once, only the first occurrence will be used. 5028 6. public_configs pulled from dependencies, in the order of the 5029 "deps" list. If a dependency is public, they will be applied 5030 recursively. 5031``` 5032### <a name="var_check_includes"></a>**check_includes**: [boolean] Controls whether a target's files are checked. 5033 5034``` 5035 When true (the default), the "gn check" command (as well as "gn gen" with the 5036 --check flag) will check this target's sources and headers for proper 5037 dependencies. 5038 5039 When false, the files in this target will be skipped by default. This does 5040 not affect other targets that depend on the current target, it just skips 5041 checking the includes of the current target's files. 5042 5043 If there are a few conditionally included headers that trip up checking, you 5044 can exclude headers individually by annotating them with "nogncheck" (see "gn 5045 help nogncheck"). 5046 5047 The topic "gn help check" has general information on how checking works and 5048 advice on how to pass a check in problematic cases. 5049``` 5050 5051#### **Example** 5052 5053``` 5054 source_set("busted_includes") { 5055 # This target's includes are messed up, exclude it from checking. 5056 check_includes = false 5057 ... 5058 } 5059``` 5060### <a name="var_code_signing_args"></a>**code_signing_args**: [string list] Arguments passed to code signing script. 5061 5062``` 5063 For create_bundle targets, code_signing_args is the list of arguments to pass 5064 to the code signing script. Typically you would use source expansion (see "gn 5065 help source_expansion") to insert the source file names. 5066 5067 See also "gn help create_bundle". 5068``` 5069### <a name="var_code_signing_outputs"></a>**code_signing_outputs**: [file list] Output files for code signing step. 5070 5071``` 5072 Outputs from the code signing step of a create_bundle target. Must refer to 5073 files in the build directory. 5074 5075 See also "gn help create_bundle". 5076``` 5077### <a name="var_code_signing_script"></a>**code_signing_script**: [file name] Script for code signing." 5078 5079``` 5080 An absolute or buildfile-relative file name of a Python script to run for a 5081 create_bundle target to perform code signing step. 5082 5083 See also "gn help create_bundle". 5084``` 5085### <a name="var_code_signing_sources"></a>**code_signing_sources**: [file list] Sources for code signing step. 5086 5087``` 5088 A list of files used as input for code signing script step of a create_bundle 5089 target. Non-absolute paths will be resolved relative to the current build 5090 file. 5091 5092 See also "gn help create_bundle". 5093``` 5094### <a name="var_complete_static_lib"></a>**complete_static_lib**: [boolean] Links all deps into a static library. 5095 5096``` 5097 A static library normally doesn't include code from dependencies, but instead 5098 forwards the static libraries and source sets in its deps up the dependency 5099 chain until a linkable target (an executable or shared library) is reached. 5100 The final linkable target only links each static library once, even if it 5101 appears more than once in its dependency graph. 5102 5103 In some cases the static library might be the final desired output. For 5104 example, you may be producing a static library for distribution to third 5105 parties. In this case, the static library should include code for all 5106 dependencies in one complete package. However, complete static libraries 5107 themselves are never linked into other complete static libraries. All 5108 complete static libraries are for distribution and linking them in would 5109 cause code duplication in this case. If the static library is not for 5110 distribution, it should not be complete. 5111 5112 GN treats non-complete static libraries as source sets when they are linked 5113 into complete static libraries. This is done because some tools like AR do 5114 not handle dependent static libraries properly. This makes it easier to write 5115 "alink" rules. 5116 5117 In rare cases it makes sense to list a header in more than one target if it 5118 could be considered conceptually a member of both. libraries. 5119``` 5120 5121#### **Example** 5122 5123``` 5124 static_library("foo") { 5125 complete_static_lib = true 5126 deps = [ "bar" ] 5127 } 5128``` 5129### <a name="var_configs"></a>**configs**: Configs applying to this target or config. 5130 5131``` 5132 A list of config labels. 5133``` 5134 5135#### **Configs on a target** 5136 5137``` 5138 When used on a target, the include_dirs, defines, etc. in each config are 5139 appended in the order they appear to the compile command for each file in the 5140 target. They will appear after the include_dirs, defines, etc. that the 5141 target sets directly. 5142 5143 Since configs apply after the values set on a target, directly setting a 5144 compiler flag will prepend it to the command line. If you want to append a 5145 flag instead, you can put that flag in a one-off config and append that 5146 config to the target's configs list. 5147 5148 The build configuration script will generally set up the default configs 5149 applying to a given target type (see "set_defaults"). When a target is being 5150 defined, it can add to or remove from this list. 5151``` 5152 5153#### **Configs on a config** 5154 5155``` 5156 It is possible to create composite configs by specifying configs on a config. 5157 One might do this to forward values, or to factor out blocks of settings from 5158 very large configs into more manageable named chunks. 5159 5160 In this case, the composite config is expanded to be the concatenation of its 5161 own values, and in order, the values from its sub-configs *before* anything 5162 else happens. This has some ramifications: 5163 5164 - A target has no visibility into a config's sub-configs. Target code only 5165 sees the name of the composite config. It can't remove sub-configs or opt 5166 in to only parts of it. The composite config may not even be defined 5167 before the target is. 5168 5169 - You can get duplication of values if a config is listed twice, say, on a 5170 target and in a sub-config that also applies. In other cases, the configs 5171 applying to a target are de-duped. It's expected that if a config is 5172 listed as a sub-config that it is only used in that context. (Note that 5173 it's possible to fix this and de-dupe, but it's not normally relevant and 5174 complicates the implementation.) 5175``` 5176 5177#### **Ordering of flags and values** 5178 5179``` 5180 1. Those set on the current target (not in a config). 5181 2. Those set on the "configs" on the target in order that the 5182 configs appear in the list. 5183 3. Those set on the "all_dependent_configs" on the target in order 5184 that the configs appear in the list. 5185 4. Those set on the "public_configs" on the target in order that 5186 those configs appear in the list. 5187 5. all_dependent_configs pulled from dependencies, in the order of 5188 the "deps" list. This is done recursively. If a config appears 5189 more than once, only the first occurrence will be used. 5190 6. public_configs pulled from dependencies, in the order of the 5191 "deps" list. If a dependency is public, they will be applied 5192 recursively. 5193``` 5194 5195#### **Example** 5196 5197``` 5198 # Configs on a target. 5199 source_set("foo") { 5200 # Don't use the default RTTI config that BUILDCONFIG applied to us. 5201 configs -= [ "//build:no_rtti" ] 5202 5203 # Add some of our own settings. 5204 configs += [ ":mysettings" ] 5205 } 5206 5207 # Create a default_optimization config that forwards to one of a set of more 5208 # specialized configs depending on build flags. This pattern is useful 5209 # because it allows a target to opt in to either a default set, or a more 5210 # specific set, while avoid duplicating the settings in two places. 5211 config("super_optimization") { 5212 cflags = [ ... ] 5213 } 5214 config("default_optimization") { 5215 if (optimize_everything) { 5216 configs = [ ":super_optimization" ] 5217 } else { 5218 configs = [ ":no_optimization" ] 5219 } 5220 } 5221``` 5222### <a name="var_contents"></a>**contents**: Contents to write to file. 5223 5224``` 5225 The contents of the file for a generated_file target. 5226 See "gn help generated_file". 5227``` 5228### <a name="var_crate_name"></a>**crate_name**: [string] The name for the compiled crate. 5229 5230``` 5231 Valid for `rust_library` targets and `executable`, `static_library`, 5232 `shared_library`, and `source_set` targets that contain Rust sources. 5233 5234 If crate_name is not set, then this rule will use the target name. 5235``` 5236### <a name="var_crate_root"></a>**crate_root**: [string] The root source file for a binary or library. 5237 5238``` 5239 Valid for `rust_library` targets and `executable`, `static_library`, 5240 `shared_library`, and `source_set` targets that contain Rust sources. 5241 5242 This file is usually the `main.rs` or `lib.rs` for binaries and libraries, 5243 respectively. 5244 5245 If crate_root is not set, then this rule will look for a lib.rs file (or 5246 main.rs for executable) or a single file in sources, if sources contains 5247 only one file. 5248``` 5249### <a name="var_crate_type"></a>**crate_type**: [string] The type of linkage to use on a shared_library. 5250 5251``` 5252 Valid for `rust_library` targets and `executable`, `static_library`, 5253 `shared_library`, and `source_set` targets that contain Rust sources. 5254 5255 Options for this field are "cdylib", "staticlib", "proc-macro", and "dylib". 5256 This field sets the `crate-type` attribute for the `rustc` tool on static 5257 libraries, as well as the appropriate output extension in the 5258 `rust_output_extension` attribute. Since outputs must be explicit, the `lib` 5259 crate type (where the Rust compiler produces what it thinks is the 5260 appropriate library type) is not supported. 5261 5262 It should be noted that the "dylib" crate type in Rust is unstable in the set 5263 of symbols it exposes, and most usages today are potentially wrong and will 5264 be broken in the future. 5265 5266 Static libraries, rust libraries, and executables have this field set 5267 automatically. 5268``` 5269### <a name="var_data"></a>**data**: Runtime data file dependencies. 5270 5271``` 5272 Lists files or directories required to run the given target. These are 5273 typically data files or directories of data files. The paths are interpreted 5274 as being relative to the current build file. Since these are runtime 5275 dependencies, they do not affect which targets are built or when. To declare 5276 input files to a script, use "inputs". 5277 5278 Appearing in the "data" section does not imply any special handling such as 5279 copying them to the output directory. This is just used for declaring runtime 5280 dependencies. Runtime dependencies can be queried using the "runtime_deps" 5281 category of "gn desc" or written during build generation via 5282 "--runtime-deps-list-file". 5283 5284 GN doesn't require data files to exist at build-time. So actions that produce 5285 files that are in turn runtime dependencies can list those generated files 5286 both in the "outputs" list as well as the "data" list. 5287 5288 By convention, directories are listed with a trailing slash: 5289 data = [ "test/data/" ] 5290 However, no verification is done on these so GN doesn't enforce this. The 5291 paths are just rebased and passed along when requested. 5292 5293 Note: On iOS and macOS, create_bundle targets will not be recursed into when 5294 gathering data. See "gn help create_bundle" for details. 5295 5296 See "gn help runtime_deps" for how these are used. 5297``` 5298### <a name="var_data_deps"></a>**data_deps**: Non-linked dependencies. 5299 5300``` 5301 A list of target labels. 5302 5303 Specifies dependencies of a target that are not actually linked into the 5304 current target. Such dependencies will be built and will be available at 5305 runtime. 5306 5307 This is normally used for things like plugins or helper programs that a 5308 target needs at runtime. 5309 5310 Note: On iOS and macOS, create_bundle targets will not be recursed into when 5311 gathering data_deps. See "gn help create_bundle" for details. 5312 5313 See also "gn help deps" and "gn help data". 5314``` 5315 5316#### **Example** 5317 5318``` 5319 executable("foo") { 5320 deps = [ "//base" ] 5321 data_deps = [ "//plugins:my_runtime_plugin" ] 5322 } 5323``` 5324### <a name="var_data_keys"></a>**data_keys**: Keys from which to collect metadata. 5325 5326``` 5327 These keys are used to identify metadata to collect. If a walked target 5328 defines this key in its metadata, its value will be appended to the resulting 5329 collection. 5330 5331 See "gn help generated_file". 5332``` 5333### <a name="var_defines"></a>**defines**: C preprocessor defines. 5334 5335``` 5336 A list of strings 5337 5338 These strings will be passed to the C/C++ compiler as #defines. The strings 5339 may or may not include an "=" to assign a value. 5340``` 5341 5342#### **Ordering of flags and values** 5343 5344``` 5345 1. Those set on the current target (not in a config). 5346 2. Those set on the "configs" on the target in order that the 5347 configs appear in the list. 5348 3. Those set on the "all_dependent_configs" on the target in order 5349 that the configs appear in the list. 5350 4. Those set on the "public_configs" on the target in order that 5351 those configs appear in the list. 5352 5. all_dependent_configs pulled from dependencies, in the order of 5353 the "deps" list. This is done recursively. If a config appears 5354 more than once, only the first occurrence will be used. 5355 6. public_configs pulled from dependencies, in the order of the 5356 "deps" list. If a dependency is public, they will be applied 5357 recursively. 5358``` 5359 5360#### **Example** 5361 5362``` 5363 defines = [ "AWESOME_FEATURE", "LOG_LEVEL=3" ] 5364``` 5365### <a name="var_depfile"></a>**depfile**: [string] File name for input dependencies for actions. 5366 5367``` 5368 If nonempty, this string specifies that the current action or action_foreach 5369 target will generate the given ".d" file containing the dependencies of the 5370 input. Empty or unset means that the script doesn't generate the files. 5371 5372 A depfile should be used only when a target depends on files that are not 5373 already specified by a target's inputs and sources. Likewise, depfiles should 5374 specify only those dependencies not already included in sources or inputs. 5375 5376 The .d file should go in the target output directory. If you have more than 5377 one source file that the script is being run over, you can use the output 5378 file expansions described in "gn help action_foreach" to name the .d file 5379 according to the input. 5380 5381 The format is that of a Makefile and all paths must be relative to the root 5382 build directory. Only one output may be listed and it must match the first 5383 output of the action. 5384 5385 Although depfiles are created by an action, they should not be listed in the 5386 action's "outputs" unless another target will use the file as an input. 5387``` 5388 5389#### **Example** 5390 5391``` 5392 action_foreach("myscript_target") { 5393 script = "myscript.py" 5394 sources = [ ... ] 5395 5396 # Locate the depfile in the output directory named like the 5397 # inputs but with a ".d" appended. 5398 depfile = "$relative_target_output_dir/{{source_name}}.d" 5399 5400 # Say our script uses "-o <d file>" to indicate the depfile. 5401 args = [ "{{source}}", "-o", depfile ] 5402 } 5403``` 5404### <a name="var_deps"></a>**deps**: Private linked dependencies. 5405 5406``` 5407 A list of target labels. 5408 5409 Specifies private dependencies of a target. Private dependencies are 5410 propagated up the dependency tree and linked to dependent targets, but do not 5411 grant the ability to include headers from the dependency. Public configs are 5412 not forwarded. 5413``` 5414 5415#### **Details of dependency propagation** 5416 5417``` 5418 Source sets, shared libraries, and non-complete static libraries will be 5419 propagated up the dependency tree across groups, non-complete static 5420 libraries and source sets. 5421 5422 Executables, shared libraries, and complete static libraries will link all 5423 propagated targets and stop propagation. Actions and copy steps also stop 5424 propagation, allowing them to take a library as an input but not force 5425 dependents to link to it. 5426 5427 Propagation of all_dependent_configs and public_configs happens independently 5428 of target type. all_dependent_configs are always propagated across all types 5429 of targets, and public_configs are always propagated across public deps of 5430 all types of targets. 5431 5432 Data dependencies are propagated differently. See "gn help data_deps" and 5433 "gn help runtime_deps". 5434 5435 See also "public_deps". 5436``` 5437### <a name="var_externs"></a>**externs**: [scope] Set of Rust crate-dependency pairs. 5438 5439``` 5440 A list, each value being a scope indicating a pair of crate name and the path 5441 to the Rust library. 5442 5443 These libraries will be passed as `--extern crate_name=path` to compiler 5444 invocation containing the current target. 5445``` 5446 5447#### **Examples** 5448 5449``` 5450 executable("foo") { 5451 sources = [ "main.rs" ] 5452 externs = [{ 5453 crate_name = "bar", 5454 path = "path/to/bar.rlib" 5455 }] 5456 } 5457 5458 This target would compile the `foo` crate with the following `extern` flag: 5459 `--extern bar=path/to/bar.rlib`. 5460``` 5461### <a name="var_framework_dirs"></a>**framework_dirs**: [directory list] Additional framework search directories. 5462 5463``` 5464 A list of source directories. 5465 5466 The directories in this list will be added to the framework search path for 5467 the files in the affected target. 5468``` 5469 5470#### **Ordering of flags and values** 5471 5472``` 5473 1. Those set on the current target (not in a config). 5474 2. Those set on the "configs" on the target in order that the 5475 configs appear in the list. 5476 3. Those set on the "all_dependent_configs" on the target in order 5477 that the configs appear in the list. 5478 4. Those set on the "public_configs" on the target in order that 5479 those configs appear in the list. 5480 5. all_dependent_configs pulled from dependencies, in the order of 5481 the "deps" list. This is done recursively. If a config appears 5482 more than once, only the first occurrence will be used. 5483 6. public_configs pulled from dependencies, in the order of the 5484 "deps" list. If a dependency is public, they will be applied 5485 recursively. 5486``` 5487 5488#### **Example** 5489 5490``` 5491 framework_dirs = [ "src/include", "//third_party/foo" ] 5492``` 5493### <a name="var_frameworks"></a>**frameworks**: [name list] Name of frameworks that must be linked. 5494 5495``` 5496 A list of framework names. 5497 5498 The frameworks named in that list will be linked with any dynamic link 5499 type target. 5500``` 5501 5502#### **Ordering of flags and values** 5503 5504``` 5505 1. Those set on the current target (not in a config). 5506 2. Those set on the "configs" on the target in order that the 5507 configs appear in the list. 5508 3. Those set on the "all_dependent_configs" on the target in order 5509 that the configs appear in the list. 5510 4. Those set on the "public_configs" on the target in order that 5511 those configs appear in the list. 5512 5. all_dependent_configs pulled from dependencies, in the order of 5513 the "deps" list. This is done recursively. If a config appears 5514 more than once, only the first occurrence will be used. 5515 6. public_configs pulled from dependencies, in the order of the 5516 "deps" list. If a dependency is public, they will be applied 5517 recursively. 5518``` 5519 5520#### **Example** 5521 5522``` 5523 frameworks = [ "Foundation.framework", "Foo.framework" ] 5524``` 5525### <a name="var_friend"></a>**friend**: Allow targets to include private headers. 5526 5527``` 5528 A list of label patterns (see "gn help label_pattern") that allow dependent 5529 targets to include private headers. Applies to all binary targets. 5530 5531 Normally if a target lists headers in the "public" list (see "gn help 5532 public"), other headers are implicitly marked as private. Private headers 5533 can not be included by other targets, even with a public dependency path. 5534 The "gn check" function performs this validation. 5535 5536 A friend declaration allows one or more targets to include private headers. 5537 This is useful for things like unit tests that are closely associated with a 5538 target and require internal knowledge without opening up all headers to be 5539 included by all dependents. 5540 5541 A friend target does not allow that target to include headers when no 5542 dependency exists. A public dependency path must still exist between two 5543 targets to include any headers from a destination target. The friend 5544 annotation merely allows the use of headers that would otherwise be 5545 prohibited because they are private. 5546 5547 The friend annotation is matched only against the target containing the file 5548 with the include directive. Friend annotations are not propagated across 5549 public or private dependencies. Friend annotations do not affect visibility. 5550``` 5551 5552#### **Example** 5553 5554``` 5555 static_library("lib") { 5556 # This target can include our private headers. 5557 friend = [ ":unit_tests" ] 5558 5559 public = [ 5560 "public_api.h", # Normal public API for dependent targets. 5561 ] 5562 5563 # Private API and sources. 5564 sources = [ 5565 "a_source_file.cc", 5566 5567 # Normal targets that depend on this one won't be able to include this 5568 # because this target defines a list of "public" headers. Without the 5569 # "public" list, all headers are implicitly public. 5570 "private_api.h", 5571 ] 5572 } 5573 5574 executable("unit_tests") { 5575 sources = [ 5576 # This can include "private_api.h" from the :lib target because it 5577 # depends on that target and because of the friend annotation. 5578 "my_test.cc", 5579 ] 5580 5581 deps = [ 5582 ":lib", # Required for the include to be allowed. 5583 ] 5584 } 5585``` 5586### <a name="var_include_dirs"></a>**include_dirs**: Additional include directories. 5587 5588``` 5589 A list of source directories. 5590 5591 The directories in this list will be added to the include path for the files 5592 in the affected target. 5593``` 5594 5595#### **Ordering of flags and values** 5596 5597``` 5598 1. Those set on the current target (not in a config). 5599 2. Those set on the "configs" on the target in order that the 5600 configs appear in the list. 5601 3. Those set on the "all_dependent_configs" on the target in order 5602 that the configs appear in the list. 5603 4. Those set on the "public_configs" on the target in order that 5604 those configs appear in the list. 5605 5. all_dependent_configs pulled from dependencies, in the order of 5606 the "deps" list. This is done recursively. If a config appears 5607 more than once, only the first occurrence will be used. 5608 6. public_configs pulled from dependencies, in the order of the 5609 "deps" list. If a dependency is public, they will be applied 5610 recursively. 5611``` 5612 5613#### **Example** 5614 5615``` 5616 include_dirs = [ "src/include", "//third_party/foo" ] 5617``` 5618### <a name="var_inputs"></a>**inputs**: Additional compile-time dependencies. 5619 5620``` 5621 Inputs are compile-time dependencies of the current target. This means that 5622 all inputs must be available before compiling any of the sources or executing 5623 any actions. 5624 5625 Inputs are typically only used for action and action_foreach targets. 5626``` 5627 5628#### **Inputs for actions** 5629 5630``` 5631 For action and action_foreach targets, inputs should be the inputs to script 5632 that don't vary. These should be all .py files that the script uses via 5633 imports (the main script itself will be an implicit dependency of the action 5634 so need not be listed). 5635 5636 For action targets, inputs and sources are treated the same, but from a style 5637 perspective, it's recommended to follow the same rule as action_foreach and 5638 put helper files in the inputs, and the data used by the script (if any) in 5639 sources. 5640 5641 Note that another way to declare input dependencies from an action is to have 5642 the action write a depfile (see "gn help depfile"). This allows the script to 5643 dynamically write input dependencies, that might not be known until actually 5644 executing the script. This is more efficient than doing processing while 5645 running GN to determine the inputs, and is easier to keep in-sync than 5646 hardcoding the list. 5647``` 5648 5649#### **Script input gotchas** 5650 5651``` 5652 It may be tempting to write a script that enumerates all files in a directory 5653 as inputs. Don't do this! Even if you specify all the files in the inputs or 5654 sources in the GN target (or worse, enumerate the files in an exec_script 5655 call when running GN, which will be slow), the dependencies will be broken. 5656 5657 The problem happens if a file is ever removed because the inputs are not 5658 listed on the command line to the script. Because the script hasn't changed 5659 and all inputs are up to date, the script will not re-run and you will get a 5660 stale build. Instead, either list all inputs on the command line to the 5661 script, or if there are many, create a separate list file that the script 5662 reads. As long as this file is listed in the inputs, the build will detect 5663 when it has changed in any way and the action will re-run. 5664``` 5665 5666#### **Inputs for binary targets** 5667 5668``` 5669 Any input dependencies will be resolved before compiling any sources or 5670 linking the target. Normally, all actions that a target depends on will be run 5671 before any files in a target are compiled. So if you depend on generated 5672 headers, you do not typically need to list them in the inputs section. 5673 5674 Inputs for binary targets will be treated as implicit dependencies, meaning 5675 that changes in any of the inputs will force all sources in the target to be 5676 recompiled. If an input only applies to a subset of source files, you may 5677 want to split those into a separate target to avoid unnecessary recompiles. 5678``` 5679 5680#### **Example** 5681 5682``` 5683 action("myscript") { 5684 script = "domything.py" 5685 inputs = [ "input.data" ] 5686 } 5687``` 5688### <a name="var_ldflags"></a>**ldflags**: Flags passed to the linker. 5689 5690``` 5691 A list of strings. 5692 5693 These flags are passed on the command-line to the linker and generally 5694 specify various linking options. Most targets will not need these and will 5695 use "libs" and "lib_dirs" instead. 5696 5697 ldflags are NOT pushed to dependents, so applying ldflags to source sets or 5698 static libraries will be a no-op. If you want to apply ldflags to dependent 5699 targets, put them in a config and set it in the all_dependent_configs or 5700 public_configs. 5701``` 5702 5703#### **Ordering of flags and values** 5704 5705``` 5706 1. Those set on the current target (not in a config). 5707 2. Those set on the "configs" on the target in order that the 5708 configs appear in the list. 5709 3. Those set on the "all_dependent_configs" on the target in order 5710 that the configs appear in the list. 5711 4. Those set on the "public_configs" on the target in order that 5712 those configs appear in the list. 5713 5. all_dependent_configs pulled from dependencies, in the order of 5714 the "deps" list. This is done recursively. If a config appears 5715 more than once, only the first occurrence will be used. 5716 6. public_configs pulled from dependencies, in the order of the 5717 "deps" list. If a dependency is public, they will be applied 5718 recursively. 5719``` 5720### <a name="var_lib_dirs"></a>**lib_dirs**: Additional library directories. 5721 5722``` 5723 A list of directories. 5724 5725 Specifies additional directories passed to the linker for searching for the 5726 required libraries. If an item is not an absolute path, it will be treated as 5727 being relative to the current build file. 5728 5729 libs and lib_dirs work differently than other flags in two respects. 5730 First, they are inherited across static library boundaries until a 5731 shared library or executable target is reached. Second, they are 5732 uniquified so each one is only passed once (the first instance of it 5733 will be the one used). 5734``` 5735 5736#### **Ordering of flags and values** 5737 5738``` 5739 1. Those set on the current target (not in a config). 5740 2. Those set on the "configs" on the target in order that the 5741 configs appear in the list. 5742 3. Those set on the "all_dependent_configs" on the target in order 5743 that the configs appear in the list. 5744 4. Those set on the "public_configs" on the target in order that 5745 those configs appear in the list. 5746 5. all_dependent_configs pulled from dependencies, in the order of 5747 the "deps" list. This is done recursively. If a config appears 5748 more than once, only the first occurrence will be used. 5749 6. public_configs pulled from dependencies, in the order of the 5750 "deps" list. If a dependency is public, they will be applied 5751 recursively. 5752 5753 For "libs" and "lib_dirs" only, the values propagated from 5754 dependencies (as described above) are applied last assuming they 5755 are not already in the list. 5756``` 5757 5758#### **Example** 5759 5760``` 5761 lib_dirs = [ "/usr/lib/foo", "lib/doom_melon" ] 5762``` 5763### <a name="var_libs"></a>**libs**: Additional libraries to link. 5764 5765``` 5766 A list of library names or library paths. 5767 5768 These libraries will be linked into the final binary (executable or shared 5769 library) containing the current target. 5770 5771 libs and lib_dirs work differently than other flags in two respects. 5772 First, they are inherited across static library boundaries until a 5773 shared library or executable target is reached. Second, they are 5774 uniquified so each one is only passed once (the first instance of it 5775 will be the one used). 5776``` 5777 5778#### **Types of libs** 5779 5780``` 5781 There are several different things that can be expressed in libs: 5782 5783 File paths 5784 Values containing '/' will be treated as references to files in the 5785 checkout. They will be rebased to be relative to the build directory and 5786 specified in the "libs" for linker tools. This facility should be used 5787 for libraries that are checked in to the version control. For libraries 5788 that are generated by the build, use normal GN deps to link them. 5789 5790 System libraries 5791 Values not containing '/' will be treated as system library names. These 5792 will be passed unmodified to the linker and prefixed with the 5793 "lib_switch" attribute of the linker tool. Generally you would set the 5794 "lib_dirs" so the given library is found. Your BUILD.gn file should not 5795 specify the switch (like "-l"): this will be encoded in the "lib_switch" 5796 of the tool. 5797``` 5798 5799#### **Ordering of flags and values** 5800 5801``` 5802 1. Those set on the current target (not in a config). 5803 2. Those set on the "configs" on the target in order that the 5804 configs appear in the list. 5805 3. Those set on the "all_dependent_configs" on the target in order 5806 that the configs appear in the list. 5807 4. Those set on the "public_configs" on the target in order that 5808 those configs appear in the list. 5809 5. all_dependent_configs pulled from dependencies, in the order of 5810 the "deps" list. This is done recursively. If a config appears 5811 more than once, only the first occurrence will be used. 5812 6. public_configs pulled from dependencies, in the order of the 5813 "deps" list. If a dependency is public, they will be applied 5814 recursively. 5815 5816 For "libs" and "lib_dirs" only, the values propagated from 5817 dependencies (as described above) are applied last assuming they 5818 are not already in the list. 5819``` 5820 5821#### **Examples** 5822 5823``` 5824 On Windows: 5825 libs = [ "ctl3d.lib" ] 5826 5827 On Linux: 5828 libs = [ "ld" ] 5829``` 5830### <a name="var_metadata"></a>**metadata**: Metadata of this target. 5831 5832``` 5833 Metadata is a collection of keys and values relating to a particular target. 5834 Values must be lists, allowing for sane and predictable collection behavior. 5835 Generally, these keys will include three types of lists: lists of ordinary 5836 strings, lists of filenames intended to be rebased according to their 5837 particular source directory, and lists of target labels intended to be used 5838 as barriers to the walk. Verification of these categories occurs at walk time, 5839 not creation time (since it is not clear until the walk which values are 5840 intended for which purpose). 5841``` 5842 5843#### **Example** 5844 5845``` 5846 group("doom_melon") { 5847 metadata = { 5848 # These keys are not built in to GN but are interpreted when consuming 5849 # metadata. 5850 my_barrier = [] 5851 my_files = [ "a.txt", "b.txt" ] 5852 } 5853 } 5854``` 5855### <a name="var_module_name"></a>**module_name**: [string] The name for the compiled module. 5856 5857``` 5858 Valid for binary targets that contain Swift sources. 5859 5860 If module_name is not set, then this rule will use the target name. 5861``` 5862### <a name="var_output_conversion"></a>**output_conversion**: Data format for generated_file targets. 5863 5864``` 5865 Controls how the "contents" of a generated_file target is formatted. 5866 See `gn help io_conversion`. 5867``` 5868### <a name="var_output_dir"></a>**output_dir**: [directory] Directory to put output file in. 5869 5870``` 5871 For library and executable targets, overrides the directory for the final 5872 output. This must be in the root_build_dir or a child thereof. 5873 5874 This should generally be in the root_out_dir or a subdirectory thereof (the 5875 root_out_dir will be the same as the root_build_dir for the default 5876 toolchain, and will be a subdirectory for other toolchains). Not putting the 5877 output in a subdirectory of root_out_dir can result in collisions between 5878 different toolchains, so you will need to take steps to ensure that your 5879 target is only present in one toolchain. 5880 5881 Normally the toolchain specifies the output directory for libraries and 5882 executables (see "gn help tool"). You will have to consult that for the 5883 default location. The default location will be used if output_dir is 5884 undefined or empty. 5885``` 5886 5887#### **Example** 5888 5889``` 5890 shared_library("doom_melon") { 5891 output_dir = "$root_out_dir/plugin_libs" 5892 ... 5893 } 5894``` 5895### <a name="var_output_extension"></a>**output_extension**: Value to use for the output's file extension. 5896 5897``` 5898 Normally the file extension for a target is based on the target type and the 5899 operating system, but in rare cases you will need to override the name (for 5900 example to use "libfreetype.so.6" instead of libfreetype.so on Linux). 5901 5902 This value should not include a leading dot. If undefined, the default 5903 specified on the tool will be used. If set to the empty string, no output 5904 extension will be used. 5905 5906 The output_extension will be used to set the "{{output_extension}}" expansion 5907 which the linker tool will generally use to specify the output file name. See 5908 "gn help tool". 5909``` 5910 5911#### **Example** 5912 5913``` 5914 shared_library("freetype") { 5915 if (is_linux) { 5916 # Call the output "libfreetype.so.6" 5917 output_extension = "so.6" 5918 } 5919 ... 5920 } 5921 5922 # On Windows, generate a "mysettings.cpl" control panel applet. Control panel 5923 # applets are actually special shared libraries. 5924 if (is_win) { 5925 shared_library("mysettings") { 5926 output_extension = "cpl" 5927 ... 5928 } 5929 } 5930``` 5931### <a name="var_output_name"></a>**output_name**: Define a name for the output file other than the default. 5932 5933``` 5934 Normally the output name of a target will be based on the target name, so the 5935 target "//foo/bar:bar_unittests" will generate an output file such as 5936 "bar_unittests.exe" (using Windows as an example). 5937 5938 Sometimes you will want an alternate name to avoid collisions or if the 5939 internal name isn't appropriate for public distribution. 5940 5941 The output name should have no extension or prefixes, these will be added 5942 using the default system rules. For example, on Linux an output name of "foo" 5943 will produce a shared library "libfoo.so". There is no way to override the 5944 output prefix of a linker tool on a per- target basis. If you need more 5945 flexibility, create a copy target to produce the file you want. 5946 5947 This variable is valid for all binary output target types. 5948``` 5949 5950#### **Example** 5951 5952``` 5953 static_library("doom_melon") { 5954 output_name = "fluffy_bunny" 5955 } 5956``` 5957### <a name="var_output_prefix_override"></a>**output_prefix_override**: Don't use prefix for output name. 5958 5959``` 5960 A boolean that overrides the output prefix for a target. Defaults to false. 5961 5962 Some systems use prefixes for the names of the final target output file. The 5963 normal example is "libfoo.so" on Linux for a target named "foo". 5964 5965 The output prefix for a given target type is specified on the linker tool 5966 (see "gn help tool"). Sometimes this prefix is undesired. 5967 5968 See also "gn help output_extension". 5969``` 5970 5971#### **Example** 5972 5973``` 5974 shared_library("doom_melon") { 5975 # Normally this will produce "libdoom_melon.so" on Linux. Setting this flag 5976 # will produce "doom_melon.so". 5977 output_prefix_override = true 5978 ... 5979 } 5980``` 5981### <a name="var_outputs"></a>**outputs**: Output files for actions and copy targets. 5982 5983``` 5984 Outputs is valid for "copy", "action", and "action_foreach" target types and 5985 indicates the resulting files. Outputs must always refer to files in the 5986 build directory. 5987 5988 copy 5989 Copy targets should have exactly one entry in the outputs list. If there is 5990 exactly one source, this can be a literal file name or a source expansion. 5991 If there is more than one source, this must contain a source expansion to 5992 map a single input name to a single output name. See "gn help copy". 5993 5994 action_foreach 5995 Action_foreach targets must always use source expansions to map input files 5996 to output files. There can be more than one output, which means that each 5997 invocation of the script will produce a set of files (presumably based on 5998 the name of the input file). See "gn help action_foreach". 5999 6000 action 6001 Action targets (excluding action_foreach) must list literal output file(s) 6002 with no source expansions. See "gn help action". 6003``` 6004### <a name="var_partial_info_plist"></a>**partial_info_plist**: [filename] Path plist from asset catalog compiler. 6005 6006``` 6007 Valid for create_bundle target, corresponds to the path for the partial 6008 Info.plist created by the asset catalog compiler that needs to be merged 6009 with the application Info.plist (usually done by the code signing script). 6010 6011 The file will be generated regardless of whether the asset compiler has 6012 been invoked or not. See "gn help create_bundle". 6013``` 6014### <a name="var_pool"></a>**pool**: Label of the pool used by the action. 6015 6016``` 6017 A fully-qualified label representing the pool that will be used for the 6018 action. Pools are defined using the pool() {...} declaration. 6019``` 6020 6021#### **Example** 6022 6023``` 6024 action("action") { 6025 pool = "//build:custom_pool" 6026 ... 6027 } 6028``` 6029### <a name="var_precompiled_header"></a>**precompiled_header**: [string] Header file to precompile. 6030 6031``` 6032 Precompiled headers will be used when a target specifies this value, or a 6033 config applying to this target specifies this value. In addition, the tool 6034 corresponding to the source files must also specify precompiled headers (see 6035 "gn help tool"). The tool will also specify what type of precompiled headers 6036 to use, by setting precompiled_header_type to either "gcc" or "msvc". 6037 6038 The precompiled header/source variables can be specified on a target or a 6039 config, but must be the same for all configs applying to a given target since 6040 a target can only have one precompiled header. 6041 6042 If you use both C and C++ sources, the precompiled header and source file 6043 will be compiled once per language. You will want to make sure to wrap C++ 6044 includes in __cplusplus #ifdefs so the file will compile in C mode. 6045``` 6046 6047#### **GCC precompiled headers** 6048 6049``` 6050 When using GCC-style precompiled headers, "precompiled_source" contains the 6051 path of a .h file that is precompiled and then included by all source files 6052 in targets that set "precompiled_source". 6053 6054 The value of "precompiled_header" is not used with GCC-style precompiled 6055 headers. 6056``` 6057 6058#### **MSVC precompiled headers** 6059 6060``` 6061 When using MSVC-style precompiled headers, the "precompiled_header" value is 6062 a string corresponding to the header. This is NOT a path to a file that GN 6063 recognises, but rather the exact string that appears in quotes after 6064 an #include line in source code. The compiler will match this string against 6065 includes or forced includes (/FI). 6066 6067 MSVC also requires a source file to compile the header with. This must be 6068 specified by the "precompiled_source" value. In contrast to the header value, 6069 this IS a GN-style file name, and tells GN which source file to compile to 6070 make the .pch file used for subsequent compiles. 6071 6072 For example, if the toolchain specifies MSVC headers: 6073 6074 toolchain("vc_x64") { 6075 ... 6076 tool("cxx") { 6077 precompiled_header_type = "msvc" 6078 ... 6079 6080 You might make a config like this: 6081 6082 config("use_precompiled_headers") { 6083 precompiled_header = "build/precompile.h" 6084 precompiled_source = "//build/precompile.cc" 6085 6086 # Either your source files should #include "build/precompile.h" 6087 # first, or you can do this to force-include the header. 6088 cflags = [ "/FI$precompiled_header" ] 6089 } 6090 6091 And then define a target that uses the config: 6092 6093 executable("doom_melon") { 6094 configs += [ ":use_precompiled_headers" ] 6095 ... 6096``` 6097### <a name="var_precompiled_header_type"></a>**precompiled_header_type**: [string] "gcc" or "msvc". 6098 6099``` 6100 See "gn help precompiled_header". 6101``` 6102### <a name="var_precompiled_source"></a>**precompiled_source**: [file name] Source file to precompile. 6103 6104``` 6105 The source file that goes along with the precompiled_header when using 6106 "msvc"-style precompiled headers. It will be implicitly added to the sources 6107 of the target. See "gn help precompiled_header". 6108``` 6109### <a name="var_product_type"></a>**product_type**: Product type for Xcode projects. 6110 6111``` 6112 Correspond to the type of the product of a create_bundle target. Only 6113 meaningful to Xcode (used as part of the Xcode project generation). 6114 6115 When generating Xcode project files, only create_bundle target with a 6116 non-empty product_type will have a corresponding target in Xcode project. 6117``` 6118### <a name="var_public"></a>**public**: Declare public header files for a target. 6119 6120``` 6121 A list of files that other targets can include. These permissions are checked 6122 via the "check" command (see "gn help check"). 6123 6124 If no public files are declared, other targets (assuming they have visibility 6125 to depend on this target) can include any file in the sources list. If this 6126 variable is defined on a target, dependent targets may only include files on 6127 this whitelist unless that target is marked as a friend (see "gn help 6128 friend"). 6129 6130 Header file permissions are also subject to visibility. A target must be 6131 visible to another target to include any files from it at all and the public 6132 headers indicate which subset of those files are permitted. See "gn help 6133 visibility" for more. 6134 6135 Public files are inherited through the dependency tree. So if there is a 6136 dependency A -> B -> C, then A can include C's public headers. However, the 6137 same is NOT true of visibility, so unless A is in C's visibility list, the 6138 include will be rejected. 6139 6140 GN only knows about files declared in the "sources" and "public" sections of 6141 targets. If a file is included that is not known to the build, it will be 6142 allowed. 6143 6144 It is common for test targets to need to include private headers for their 6145 associated code. In this case, list the test target in the "friend" list of 6146 the target that owns the private header to allow the inclusion. See 6147 "gn help friend" for more. 6148 6149 When a binary target has no explicit or implicit public headers (a "public" 6150 list is defined but is empty), GN assumes that the target can not propagate 6151 any compile-time dependencies up the dependency tree. In this case, the build 6152 can be parallelized more efficiently. 6153 Say there are dependencies: 6154 A (shared library) -> B (shared library) -> C (action). 6155 Normally C must complete before any source files in A can compile (because 6156 there might be generated includes). But when B explicitly declares no public 6157 headers, C can execute in parallel with A's compile steps. C must still be 6158 complete before any dependents link. 6159``` 6160 6161#### **Examples** 6162 6163``` 6164 These exact files are public: 6165 public = [ "foo.h", "bar.h" ] 6166 6167 No files are public (no targets may include headers from this one): 6168 # This allows starting compilation in dependent targets earlier. 6169 public = [] 6170``` 6171### <a name="var_public_configs"></a>**public_configs**: Configs to be applied on dependents. 6172 6173``` 6174 A list of config labels. 6175 6176 Targets directly depending on this one will have the configs listed in this 6177 variable added to them. These configs will also apply to the current target. 6178 Generally, public configs are used to apply defines and include directories 6179 necessary to compile this target's header files. 6180 6181 See also "gn help all_dependent_configs". 6182``` 6183 6184#### **Propagation of public configs** 6185 6186``` 6187 Public configs are applied to all targets that depend directly on this one. 6188 These dependent targets can further push this target's public configs 6189 higher in the dependency tree by depending on it via public_deps (see "gn 6190 help public_deps"). 6191 6192 static_library("toplevel") { 6193 # This target will get "my_config" applied to it. However, since this 6194 # target uses "deps" and not "public_deps", targets that depend on this 6195 # one won't get it. 6196 deps = [ ":intermediate" ] 6197 } 6198 6199 static_library("intermediate") { 6200 # Depending on "lower" in any way will apply "my_config" to this target. 6201 # Additionall, since this target depends on "lower" via public_deps, 6202 # targets that depend on this one will also get "my_config". 6203 public_deps = [ ":lower" ] 6204 } 6205 6206 static_library("lower") { 6207 # This will get applied to all targets that depend on this one. 6208 public_configs = [ ":my_config" ] 6209 } 6210 6211 Public config propagation happens in a second phase once a target and all of 6212 its dependencies have been resolved. Therefore, a target will not see these 6213 force-added configs in their "configs" variable while the script is running, 6214 and they can not be removed. As a result, this capability should generally 6215 only be used to add defines and include directories rather than setting 6216 complicated flags that some targets may not want. 6217 6218 Public configs may or may not be propagated across toolchain boundaries 6219 depending on the value of the propagates_configs flag (see "gn help 6220 toolchain") on the toolchain of the target declaring the public_config. 6221``` 6222 6223#### **Avoiding applying public configs to this target** 6224 6225``` 6226 If you want the config to apply to targets that depend on this one, but NOT 6227 this one, define an extra layer of indirection using a group: 6228 6229 # External targets depend on this group. 6230 group("my_target") { 6231 # Config to apply to all targets that depend on this one. 6232 public_configs = [ ":external_settings" ] 6233 deps = [ ":internal_target" ] 6234 } 6235 6236 # Internal target to actually compile the sources. 6237 static_library("internal_target") { 6238 # Force all external targets to depend on the group instead of directly 6239 # on this so the "external_settings" config will get applied. 6240 visibility = [ ":my_target" ] 6241 ... 6242 } 6243``` 6244 6245#### **Ordering of flags and values** 6246 6247``` 6248 1. Those set on the current target (not in a config). 6249 2. Those set on the "configs" on the target in order that the 6250 configs appear in the list. 6251 3. Those set on the "all_dependent_configs" on the target in order 6252 that the configs appear in the list. 6253 4. Those set on the "public_configs" on the target in order that 6254 those configs appear in the list. 6255 5. all_dependent_configs pulled from dependencies, in the order of 6256 the "deps" list. This is done recursively. If a config appears 6257 more than once, only the first occurrence will be used. 6258 6. public_configs pulled from dependencies, in the order of the 6259 "deps" list. If a dependency is public, they will be applied 6260 recursively. 6261``` 6262### <a name="var_public_deps"></a>**public_deps**: Declare public dependencies. 6263 6264``` 6265 Public dependencies are like private dependencies (see "gn help deps") but 6266 additionally express that the current target exposes the listed deps as part 6267 of its public API. 6268 6269 This has several ramifications: 6270 6271 - public_configs that are part of the dependency are forwarded to direct 6272 dependents. 6273 6274 - Public headers in the dependency are usable by dependents (includes do 6275 not require a direct dependency or visibility). 6276 6277 - If the current target is a shared library, other shared libraries that it 6278 publicly depends on (directly or indirectly) are propagated up the 6279 dependency tree to dependents for linking. 6280 6281 See also "gn help public_configs". 6282``` 6283 6284#### **Discussion** 6285 6286``` 6287 Say you have three targets: A -> B -> C. C's visibility may allow B to depend 6288 on it but not A. Normally, this would prevent A from including any headers 6289 from C, and C's public_configs would apply only to B. 6290 6291 If B lists C in its public_deps instead of regular deps, A will now inherit 6292 C's public_configs and the ability to include C's public headers. 6293 6294 Generally if you are writing a target B and you include C's headers as part 6295 of B's public headers, or targets depending on B should consider B and C to 6296 be part of a unit, you should use public_deps instead of deps. 6297``` 6298 6299#### **Example** 6300 6301``` 6302 # This target can include files from "c" but not from 6303 # "super_secret_implementation_details". 6304 executable("a") { 6305 deps = [ ":b" ] 6306 } 6307 6308 shared_library("b") { 6309 deps = [ ":super_secret_implementation_details" ] 6310 public_deps = [ ":c" ] 6311 } 6312``` 6313### <a name="var_rebase"></a>**rebase**: Rebase collected metadata as files. 6314 6315``` 6316 A boolean that triggers a rebase of collected metadata strings based on their 6317 declared file. Defaults to false. 6318 6319 Metadata generally declares files as strings relative to the local build file. 6320 However, this data is often used in other contexts, and so setting this flag 6321 will force the metadata collection to be rebased according to the local build 6322 file's location and thus allow the filename to be used anywhere. 6323 6324 Setting this flag will raise an error if any target's specified metadata is 6325 not a string value. 6326 6327 See also "gn help generated_file". 6328``` 6329### <a name="var_response_file_contents"></a>**response_file_contents**: Contents of a response file for actions. 6330 6331``` 6332 Sometimes the arguments passed to a script can be too long for the system's 6333 command-line capabilities. This is especially the case on Windows where the 6334 maximum command-line length is less than 8K. A response file allows you to 6335 pass an unlimited amount of data to a script in a temporary file for an 6336 action or action_foreach target. 6337 6338 If the response_file_contents variable is defined and non-empty, the list 6339 will be treated as script args (including possibly substitution patterns) 6340 that will be written to a temporary file at build time. The name of the 6341 temporary file will be substituted for "{{response_file_name}}" in the script 6342 args. 6343 6344 The response file contents will always be quoted and escaped according to 6345 Unix shell rules. To parse the response file, the Python script should use 6346 "shlex.split(file_contents)". 6347``` 6348 6349#### **Example** 6350 6351``` 6352 action("process_lots_of_files") { 6353 script = "process.py", 6354 inputs = [ ... huge list of files ... ] 6355 6356 # Write all the inputs to a response file for the script. Also, 6357 # make the paths relative to the script working directory. 6358 response_file_contents = rebase_path(inputs, root_build_dir) 6359 6360 # The script expects the name of the response file in --file-list. 6361 args = [ 6362 "--enable-foo", 6363 "--file-list={{response_file_name}}", 6364 ] 6365 } 6366``` 6367### <a name="var_script"></a>**script**: Script file for actions. 6368 6369``` 6370 An absolute or buildfile-relative file name of a Python script to run for a 6371 action and action_foreach targets (see "gn help action" and "gn help 6372 action_foreach"). 6373``` 6374### <a name="var_sources"></a>**sources**: Source files for a target 6375 6376``` 6377 A list of files. Non-absolute paths will be resolved relative to the current 6378 build file. 6379``` 6380 6381#### **Sources for binary targets** 6382 6383``` 6384 For binary targets (source sets, executables, and libraries), the known file 6385 types will be compiled with the associated tools. Unknown file types and 6386 headers will be skipped. However, you should still list all C/C+ header files 6387 so GN knows about the existence of those files for the purposes of include 6388 checking. 6389 6390 As a special case, a file ending in ".def" will be treated as a Windows 6391 module definition file. It will be appended to the link line with a 6392 preceding "/DEF:" string. There must be at most one .def file in a target 6393 and they do not cross dependency boundaries (so specifying a .def file in a 6394 static library or source set will have no effect on the executable or shared 6395 library they're linked into). 6396 6397 For Rust targets that do not specify a crate_root, then the crate_root will 6398 look for a lib.rs file (or main.rs for executable) or a single file in 6399 sources, if sources contains only one file. 6400``` 6401 6402#### **Sources for non-binary targets** 6403 6404``` 6405 action_foreach 6406 The sources are the set of files that the script will be executed over. The 6407 script will run once per file. 6408 6409 action 6410 The sources will be treated the same as inputs. See "gn help inputs" for 6411 more information and usage advice. 6412 6413 copy 6414 The source are the source files to copy. 6415``` 6416### <a name="var_swiftflags"></a>**swiftflags**: Flags passed to the swift compiler. 6417 6418``` 6419 A list of strings. 6420 6421 "swiftflags" are passed to any invocation of a tool that takes an .swift 6422 file as input. 6423``` 6424 6425#### **Ordering of flags and values** 6426 6427``` 6428 1. Those set on the current target (not in a config). 6429 2. Those set on the "configs" on the target in order that the 6430 configs appear in the list. 6431 3. Those set on the "all_dependent_configs" on the target in order 6432 that the configs appear in the list. 6433 4. Those set on the "public_configs" on the target in order that 6434 those configs appear in the list. 6435 5. all_dependent_configs pulled from dependencies, in the order of 6436 the "deps" list. This is done recursively. If a config appears 6437 more than once, only the first occurrence will be used. 6438 6. public_configs pulled from dependencies, in the order of the 6439 "deps" list. If a dependency is public, they will be applied 6440 recursively. 6441``` 6442### <a name="var_testonly"></a>**testonly**: Declares a target must only be used for testing. 6443 6444``` 6445 Boolean. Defaults to false. 6446 6447 When a target is marked "testonly = true", it must only be depended on by 6448 other test-only targets. Otherwise, GN will issue an error that the 6449 depenedency is not allowed. 6450 6451 This feature is intended to prevent accidentally shipping test code in a 6452 final product. 6453``` 6454 6455#### **Example** 6456 6457``` 6458 source_set("test_support") { 6459 testonly = true 6460 ... 6461 } 6462``` 6463### <a name="var_visibility"></a>**visibility**: A list of labels that can depend on a target. 6464 6465``` 6466 A list of labels and label patterns that define which targets can depend on 6467 the current one. These permissions are checked via the "check" command (see 6468 "gn help check"). 6469 6470 If visibility is not defined, it defaults to public ("*"). 6471 6472 If visibility is defined, only the targets with labels that match it can 6473 depend on the current target. The empty list means no targets can depend on 6474 the current target. 6475 6476 Tip: Often you will want the same visibility for all targets in a BUILD file. 6477 In this case you can just put the definition at the top, outside of any 6478 target, and the targets will inherit that scope and see the definition. 6479``` 6480 6481#### **Patterns** 6482 6483``` 6484 See "gn help label_pattern" for more details on what types of patterns are 6485 supported. If a toolchain is specified, only targets in that toolchain will 6486 be matched. If a toolchain is not specified on a pattern, targets in all 6487 toolchains will be matched. 6488``` 6489 6490#### **Examples** 6491 6492``` 6493 Only targets in the current buildfile ("private"): 6494 visibility = [ ":*" ] 6495 6496 No targets (used for targets that should be leaf nodes): 6497 visibility = [] 6498 6499 Any target ("public", the default): 6500 visibility = [ "*" ] 6501 6502 All targets in the current directory and any subdirectory: 6503 visibility = [ "./*" ] 6504 6505 Any target in "//bar/BUILD.gn": 6506 visibility = [ "//bar:*" ] 6507 6508 Any target in "//bar/" or any subdirectory thereof: 6509 visibility = [ "//bar/*" ] 6510 6511 Just these specific targets: 6512 visibility = [ ":mything", "//foo:something_else" ] 6513 6514 Any target in the current directory and any subdirectory thereof, plus 6515 any targets in "//bar/" and any subdirectory thereof. 6516 visibility = [ "./*", "//bar/*" ] 6517``` 6518### <a name="var_walk_keys"></a>**walk_keys**: Key(s) for managing the metadata collection walk. 6519 6520``` 6521 Defaults to [""]. 6522 6523 These keys are used to control the next step in a collection walk, acting as 6524 barriers. If a specified key is defined in a target's metadata, the walk will 6525 use the targets listed in that value to determine which targets are walked. 6526 6527 If no walk_keys are specified for a generated_file target (i.e. "[""]"), the 6528 walk will touch all deps and data_deps of the specified target recursively. 6529 6530 See "gn help generated_file". 6531``` 6532### <a name="var_weak_frameworks"></a>**weak_frameworks**: [name list] Name of frameworks that must be weak linked. 6533 6534``` 6535 A list of framework names. 6536 6537 The frameworks named in that list will be weak linked with any dynamic link 6538 type target. Weak linking instructs the dynamic loader to attempt to load 6539 the framework, but if it is not able to do so, it leaves any imported symbols 6540 unresolved. This is typically used when a framework is present in a new 6541 version of an SDK but not on older versions of the OS that the software runs 6542 on. 6543``` 6544 6545#### **Ordering of flags and values** 6546 6547``` 6548 1. Those set on the current target (not in a config). 6549 2. Those set on the "configs" on the target in order that the 6550 configs appear in the list. 6551 3. Those set on the "all_dependent_configs" on the target in order 6552 that the configs appear in the list. 6553 4. Those set on the "public_configs" on the target in order that 6554 those configs appear in the list. 6555 5. all_dependent_configs pulled from dependencies, in the order of 6556 the "deps" list. This is done recursively. If a config appears 6557 more than once, only the first occurrence will be used. 6558 6. public_configs pulled from dependencies, in the order of the 6559 "deps" list. If a dependency is public, they will be applied 6560 recursively. 6561``` 6562 6563#### **Example** 6564 6565``` 6566 weak_frameworks = [ "OnlyOnNewerOSes.framework" ] 6567``` 6568### <a name="var_write_runtime_deps"></a>**write_runtime_deps**: Writes the target's runtime_deps to the given path. 6569 6570``` 6571 Does not synchronously write the file, but rather schedules it to be written 6572 at the end of generation. 6573 6574 If the file exists and the contents are identical to that being written, the 6575 file will not be updated. This will prevent unnecessary rebuilds of targets 6576 that depend on this file. 6577 6578 Path must be within the output directory. 6579 6580 See "gn help runtime_deps" for how the runtime dependencies are computed. 6581 6582 The format of this file will list one file per line with no escaping. The 6583 files will be relative to the root_build_dir. The first line of the file will 6584 be the main output file of the target itself. The file contents will be the 6585 same as requesting the runtime deps be written on the command line (see "gn 6586 help --runtime-deps-list-file"). 6587``` 6588### <a name="var_xcasset_compiler_flags"></a>**xcasset_compiler_flags**: Flags passed to xcassets compiler. 6589 6590``` 6591 A list of strings. 6592 6593 Valid for create_bundle target. Those flags are directly passed to 6594 xcassets compiler, corresponding to {{xcasset_compiler_flags}} substitution 6595 in compile_xcassets tool. 6596``` 6597### <a name="var_xcode_extra_attributes"></a>**xcode_extra_attributes**: [scope] Extra attributes for Xcode projects. 6598 6599``` 6600 The value defined in this scope will be copied to the EXTRA_ATTRIBUTES 6601 property of the generated Xcode project. They are only meaningful when 6602 generating with --ide=xcode. 6603 6604 See "gn help create_bundle" for more information. 6605``` 6606### <a name="var_xcode_test_application_name"></a>**xcode_test_application_name**: Name for Xcode test target. 6607 6608``` 6609 Each unit and ui test target must have a test application target, and this 6610 value is used to specify the relationship. Only meaningful to Xcode (used as 6611 part of the Xcode project generation). 6612 6613 See "gn help create_bundle" for more information. 6614``` 6615 6616#### **Example** 6617 6618``` 6619 create_bundle("chrome_xctest") { 6620 test_application_name = "chrome" 6621 ... 6622 } 6623``` 6624## <a name="other"></a>Other help topics 6625 6626### <a name="buildargs"></a>**Build Arguments Overview** 6627 6628``` 6629 Build arguments are variables passed in from outside of the build that build 6630 files can query to determine how the build works. 6631``` 6632 6633#### **How build arguments are set** 6634 6635``` 6636 First, system default arguments are set based on the current system. The 6637 built-in arguments are: 6638 - host_cpu 6639 - host_os 6640 - current_cpu 6641 - current_os 6642 - target_cpu 6643 - target_os 6644 6645 Next, project-specific overrides are applied. These are specified inside 6646 the default_args variable of //.gn. See "gn help dotfile" for more. 6647 6648 If specified, arguments from the --args command line flag are used. If that 6649 flag is not specified, args from previous builds in the build directory will 6650 be used (this is in the file args.gn in the build directory). 6651 6652 Last, for targets being compiled with a non-default toolchain, the toolchain 6653 overrides are applied. These are specified in the toolchain_args section of a 6654 toolchain definition. The use-case for this is that a toolchain may be 6655 building code for a different platform, and that it may want to always 6656 specify Posix, for example. See "gn help toolchain" for more. 6657 6658 If you specify an override for a build argument that never appears in a 6659 "declare_args" call, a nonfatal error will be displayed. 6660``` 6661 6662#### **Examples** 6663 6664``` 6665 gn args out/FooBar 6666 Create the directory out/FooBar and open an editor. You would type 6667 something like this into that file: 6668 enable_doom_melon=false 6669 os="android" 6670 6671 gn gen out/FooBar --args="enable_doom_melon=true os=\"android\"" 6672 This will overwrite the build directory with the given arguments. (Note 6673 that the quotes inside the args command will usually need to be escaped 6674 for your shell to pass through strings values.) 6675``` 6676 6677#### **How build arguments are used** 6678 6679``` 6680 If you want to use an argument, you use declare_args() and specify default 6681 values. These default values will apply if none of the steps listed in the 6682 "How build arguments are set" section above apply to the given argument, but 6683 the defaults will not override any of these. 6684 6685 Often, the root build config file will declare global arguments that will be 6686 passed to all buildfiles. Individual build files can also specify arguments 6687 that apply only to those files. It is also useful to specify build args in an 6688 "import"-ed file if you want such arguments to apply to multiple buildfiles. 6689``` 6690### <a name="dotfile"></a>**.gn file** 6691 6692``` 6693 When gn starts, it will search the current directory and parent directories 6694 for a file called ".gn". This indicates the source root. You can override 6695 this detection by using the --root command-line argument 6696 6697 The .gn file in the source root will be executed. The syntax is the same as a 6698 buildfile, but with very limited build setup-specific meaning. 6699 6700 If you specify --root, by default GN will look for the file .gn in that 6701 directory. If you want to specify a different file, you can additionally pass 6702 --dotfile: 6703 6704 gn gen out/Debug --root=/home/build --dotfile=/home/my_gn_file.gn 6705``` 6706 6707#### **Variables** 6708 6709``` 6710 arg_file_template [optional] 6711 Path to a file containing the text that should be used as the default 6712 args.gn content when you run `gn args`. 6713 6714 buildconfig [required] 6715 Path to the build config file. This file will be used to set up the 6716 build file execution environment for each toolchain. 6717 6718 check_targets [optional] 6719 A list of labels and label patterns that should be checked when running 6720 "gn check" or "gn gen --check". If neither check_targets or 6721 no_check_targets (see below) is specified, all targets will be checked. 6722 It is an error to specify both check_targets and no_check_targets. If it 6723 is the empty list, no targets will be checked. To bypass this list, 6724 request an explicit check of targets, like "//*". 6725 6726 The format of this list is identical to that of "visibility" so see "gn 6727 help visibility" for examples. 6728 6729 no_check_targets [optional] 6730 A list of labels and label patterns that should *not* be checked when 6731 running "gn check" or "gn gen --check". All other targets will be checked. 6732 If neither check_targets (see above) or no_check_targets is specified, all 6733 targets will be checked. It is an error to specify both check_targets and 6734 no_check_targets. 6735 6736 The format of this list is identical to that of "visibility" so see "gn 6737 help visibility" for examples. 6738 6739 check_system_includes [optional] 6740 Boolean to control whether system style includes are checked by default 6741 when running "gn check" or "gn gen --check". System style includes are 6742 includes that use angle brackets <> instead of double quotes "". If this 6743 setting is omitted or set to false, these includes will be ignored by 6744 default. They can be checked explicitly by running 6745 "gn check --check-system" or "gn gen --check=system" 6746 6747 exec_script_whitelist [optional] 6748 A list of .gn/.gni files (not labels) that have permission to call the 6749 exec_script function. If this list is defined, calls to exec_script will 6750 be checked against this list and GN will fail if the current file isn't 6751 in the list. 6752 6753 This is to allow the use of exec_script to be restricted since is easy to 6754 use inappropriately. Wildcards are not supported. Files in the 6755 secondary_source tree (if defined) should be referenced by ignoring the 6756 secondary tree and naming them as if they are in the main tree. 6757 6758 If unspecified, the ability to call exec_script is unrestricted. 6759 6760 Example: 6761 exec_script_whitelist = [ 6762 "//base/BUILD.gn", 6763 "//build/my_config.gni", 6764 ] 6765 6766 root [optional] 6767 Label of the root build target. The GN build will start by loading the 6768 build file containing this target name. This defaults to "//:" which will 6769 cause the file //BUILD.gn to be loaded. Note that build_file_extension 6770 applies to the default case as well. 6771 6772 The command-line switch --root-target will override this value (see "gn 6773 help --root-target"). 6774 6775 script_executable [optional] 6776 Path to specific Python executable or other interpreter to use in 6777 action targets and exec_script calls. By default GN searches the 6778 PATH for Python to execute these scripts. 6779 6780 If set to the empty string, the path specified in action targets 6781 and exec_script calls will be executed directly. 6782 6783 secondary_source [optional] 6784 Label of an alternate directory tree to find input files. When searching 6785 for a BUILD.gn file (or the build config file discussed above), the file 6786 will first be looked for in the source root. If it's not found, the 6787 secondary source root will be checked (which would contain a parallel 6788 directory hierarchy). 6789 6790 This behavior is intended to be used when BUILD.gn files can't be checked 6791 in to certain source directories for whatever reason. 6792 6793 The secondary source root must be inside the main source tree. 6794 6795 default_args [optional] 6796 Scope containing the default overrides for declared arguments. These 6797 overrides take precedence over the default values specified in the 6798 declare_args() block, but can be overridden using --args or the 6799 args.gn file. 6800 6801 This is intended to be used when subprojects declare arguments with 6802 default values that need to be changed for whatever reason. 6803 6804 build_file_extension [optional] 6805 If set to a non-empty string, this is added to the name of all build files 6806 to load. 6807 GN will look for build files named "BUILD.$build_file_extension.gn". 6808 This is intended to be used during migrations or other situations where 6809 there are two independent GN builds in the same directories. 6810 6811 ninja_required_version [optional] 6812 When set specifies the minimum required version of Ninja. The default 6813 required version is 1.7.2. Specifying a higher version might enable the 6814 use of some of newer features that can make the build more efficient. 6815``` 6816 6817#### **Example .gn file contents** 6818 6819``` 6820 buildconfig = "//build/config/BUILDCONFIG.gn" 6821 6822 check_targets = [ 6823 "//doom_melon/*", # Check everything in this subtree. 6824 "//tools:mind_controlling_ant", # Check this specific target. 6825 ] 6826 6827 root = "//:root" 6828 6829 secondary_source = "//build/config/temporary_buildfiles/" 6830 6831 default_args = { 6832 # Default to release builds for this project. 6833 is_debug = false 6834 is_component_build = false 6835 } 6836``` 6837### <a name="execution"></a>**Build graph and execution overview** 6838 6839#### **Overall build flow** 6840 6841``` 6842 1. Look for ".gn" file (see "gn help dotfile") in the current directory and 6843 walk up the directory tree until one is found. Set this directory to be 6844 the "source root" and interpret this file to find the name of the build 6845 config file. 6846 6847 2. Execute the build config file identified by .gn to set up the global 6848 variables and default toolchain name. Any arguments, variables, defaults, 6849 etc. set up in this file will be visible to all files in the build. 6850 6851 3. Load the //BUILD.gn (in the source root directory). 6852 6853 4. Recursively evaluate rules and load BUILD.gn in other directories as 6854 necessary to resolve dependencies. If a BUILD file isn't found in the 6855 specified location, GN will look in the corresponding location inside 6856 the secondary_source defined in the dotfile (see "gn help dotfile"). 6857 6858 5. When a target's dependencies are resolved, write out the `.ninja` 6859 file to disk. 6860 6861 6. When all targets are resolved, write out the root build.ninja file. 6862 6863 Note that the BUILD.gn file name may be modulated by .gn arguments such as 6864 build_file_extension. 6865``` 6866 6867#### **Executing target definitions and templates** 6868 6869``` 6870 Build files are loaded in parallel. This means it is impossible to 6871 interrogate a target from GN code for any information not derivable from its 6872 label (see "gn help label"). The exception is the get_target_outputs() 6873 function which requires the target being interrogated to have been defined 6874 previously in the same file. 6875 6876 Targets are declared by their type and given a name: 6877 6878 static_library("my_static_library") { 6879 ... target parameter definitions ... 6880 } 6881 6882 There is also a generic "target" function for programmatically defined types 6883 (see "gn help target"). You can define new types using templates (see "gn 6884 help template"). A template defines some custom code that expands to one or 6885 more other targets. 6886 6887 Before executing the code inside the target's { }, the target defaults are 6888 applied (see "gn help set_defaults"). It will inject implicit variable 6889 definitions that can be overridden by the target code as necessary. Typically 6890 this mechanism is used to inject a default set of configs that define the 6891 global compiler and linker flags. 6892``` 6893 6894#### **Which targets are built** 6895 6896``` 6897 All targets encountered in the default toolchain (see "gn help toolchain") 6898 will have build rules generated for them, even if no other targets reference 6899 them. Their dependencies must resolve and they will be added to the implicit 6900 "all" rule (see "gn help ninja_rules"). 6901 6902 Targets in non-default toolchains will only be generated when they are 6903 required (directly or transitively) to build a target in the default 6904 toolchain. 6905 6906 See also "gn help ninja_rules". 6907``` 6908 6909#### **Dependencies** 6910 6911``` 6912 The only difference between "public_deps" and "deps" except for pushing 6913 configs around the build tree and allowing includes for the purposes of "gn 6914 check". 6915 6916 A target's "data_deps" are guaranteed to be built whenever the target is 6917 built, but the ordering is not defined. The meaning of this is dependencies 6918 required at runtime. Currently data deps will be complete before the target 6919 is linked, but this is not semantically guaranteed and this is undesirable 6920 from a build performance perspective. Since we hope to change this in the 6921 future, do not rely on this behavior. 6922``` 6923### <a name="grammar"></a>**Language and grammar for GN build files** 6924 6925#### **Tokens** 6926 6927``` 6928 GN build files are read as sequences of tokens. While splitting the file 6929 into tokens, the next token is the longest sequence of characters that form a 6930 valid token. 6931``` 6932 6933#### **White space and comments** 6934 6935``` 6936 White space is comprised of spaces (U+0020), horizontal tabs (U+0009), 6937 carriage returns (U+000D), and newlines (U+000A). 6938 6939 Comments start at the character "#" and stop at the next newline. 6940 6941 White space and comments are ignored except that they may separate tokens 6942 that would otherwise combine into a single token. 6943``` 6944 6945#### **Identifiers** 6946 6947``` 6948 Identifiers name variables and functions. 6949 6950 identifier = letter { letter | digit } . 6951 letter = "A" ... "Z" | "a" ... "z" | "_" . 6952 digit = "0" ... "9" . 6953``` 6954 6955#### **Keywords** 6956 6957``` 6958 The following keywords are reserved and may not be used as identifiers: 6959 6960 else false if true 6961``` 6962 6963#### **Integer literals** 6964 6965``` 6966 An integer literal represents a decimal integer value. 6967 6968 integer = [ "-" ] digit { digit } . 6969 6970 Leading zeros and negative zero are disallowed. 6971``` 6972 6973#### **String literals** 6974 6975``` 6976 A string literal represents a string value consisting of the quoted 6977 characters with possible escape sequences and variable expansions. 6978 6979 string = `"` { char | escape | expansion } `"` . 6980 escape = `\` ( "$" | `"` | char ) . 6981 BracketExpansion = "{" ( identifier | ArrayAccess | ScopeAccess ) "}" . 6982 Hex = "0x" [0-9A-Fa-f][0-9A-Fa-f] 6983 expansion = "$" ( identifier | BracketExpansion | Hex ) . 6984 char = /* any character except "$", `"`, or newline */ . 6985 6986 After a backslash, certain sequences represent special characters: 6987 6988 \" U+0022 quotation mark 6989 \$ U+0024 dollar sign 6990 \\ U+005C backslash 6991 6992 All other backslashes represent themselves. 6993 6994 To insert an arbitrary byte value, use $0xFF. For example, to insert a 6995 newline character: "Line one$0x0ALine two". 6996 6997 An expansion will evaluate the variable following the '$' and insert a 6998 stringified version of it into the result. For example, to concat two path 6999 components with a slash separating them: 7000 "$var_one/$var_two" 7001 Use the "${var_one}" format to be explicitly deliniate the variable for 7002 otherwise-ambiguous cases. 7003``` 7004 7005#### **Punctuation** 7006 7007``` 7008 The following character sequences represent punctuation: 7009 7010 + += == != ( ) 7011 - -= < <= [ ] 7012 ! = > >= { } 7013 && || . , 7014``` 7015 7016#### **Grammar** 7017 7018``` 7019 The input tokens form a syntax tree following a context-free grammar: 7020 7021 File = StatementList . 7022 7023 Statement = Assignment | Call | Condition . 7024 LValue = identifier | ArrayAccess | ScopeAccess . 7025 Assignment = LValue AssignOp Expr . 7026 Call = identifier "(" [ ExprList ] ")" [ Block ] . 7027 Condition = "if" "(" Expr ")" Block 7028 [ "else" ( Condition | Block ) ] . 7029 Block = "{" StatementList "}" . 7030 StatementList = { Statement } . 7031 7032 ArrayAccess = identifier "[" Expr "]" . 7033 ScopeAccess = identifier "." identifier . 7034 Expr = UnaryExpr | Expr BinaryOp Expr . 7035 UnaryExpr = PrimaryExpr | UnaryOp UnaryExpr . 7036 PrimaryExpr = identifier | integer | string | Call 7037 | ArrayAccess | ScopeAccess | Block 7038 | "(" Expr ")" 7039 | "[" [ ExprList [ "," ] ] "]" . 7040 ExprList = Expr { "," Expr } . 7041 7042 AssignOp = "=" | "+=" | "-=" . 7043 UnaryOp = "!" . 7044 BinaryOp = "+" | "-" // highest priority 7045 | "<" | "<=" | ">" | ">=" 7046 | "==" | "!=" 7047 | "&&" 7048 | "||" . // lowest priority 7049 7050 All binary operators are left-associative. 7051``` 7052 7053#### **Types** 7054 7055``` 7056 The GN language is dynamically typed. The following types are used: 7057 7058 - Boolean: Uses the keywords "true" and "false". There is no implicit 7059 conversion between booleans and integers. 7060 7061 - Integers: All numbers in GN are signed 64-bit integers. 7062 7063 - Strings: Strings are 8-bit with no enforced encoding. When a string is 7064 used to interact with other systems with particular encodings (like the 7065 Windows and Mac filesystems) it is assumed to be UTF-8. See "String 7066 literals" above for more. 7067 7068 - Lists: Lists are arbitrary-length ordered lists of values. See "Lists" 7069 below for more. 7070 7071 - Scopes: Scopes are like dictionaries that use variable names for keys. See 7072 "Scopes" below for more. 7073``` 7074 7075#### **Lists** 7076 7077``` 7078 Lists are created with [] and using commas to separate items: 7079 7080 mylist = [ 0, 1, 2, "some string" ] 7081 7082 A comma after the last item is optional. Lists are dereferenced using 0-based 7083 indexing: 7084 7085 mylist[0] += 1 7086 var = mylist[2] 7087 7088 Lists can be concatenated using the '+' and '+=' operators. Bare values can 7089 not be concatenated with lists, to add a single item, it must be put into a 7090 list of length one. 7091 7092 Items can be removed from lists using the '-' and '-=' operators. This will 7093 remove all occurrences of every item in the right-hand list from the 7094 left-hand list. It is an error to remove an item not in the list. This is to 7095 prevent common typos and to detect dead code that is removing things that no 7096 longer apply. 7097 7098 It is an error to use '=' to replace a nonempty list with another nonempty 7099 list. This is to prevent accidentally overwriting data when in most cases 7100 '+=' was intended. To overwrite a list on purpose, first assign it to the 7101 empty list: 7102 7103 mylist = [] 7104 mylist = otherlist 7105``` 7106 7107#### **Scopes** 7108 7109``` 7110 All execution happens in the context of a scope which holds the current state 7111 (like variables). With the exception of loops and conditions, '{' introduces 7112 a new scope that has a parent reference to the old scope. 7113 7114 Variable reads recursively search all nested scopes until the variable is 7115 found or there are no more scopes. Variable writes always go into the current 7116 scope. This means that after the closing '}' (again excepting loops and 7117 conditions), all local variables will be restored to the previous values. 7118 This also means that "foo = foo" can do useful work by copying a variable 7119 into the current scope that was defined in a containing scope. 7120 7121 Scopes can also be assigned to variables. Such scopes can be created by 7122 functions like exec_script, when invoking a template (the template code 7123 refers to the variables set by the invoking code by the implicitly-created 7124 "invoker" scope), or explicitly like: 7125 7126 empty_scope = {} 7127 myvalues = { 7128 foo = 21 7129 bar = "something" 7130 } 7131 7132 Inside such a scope definition can be any GN code including conditionals and 7133 function calls. After the close of the scope, it will contain all variables 7134 explicitly set by the code contained inside it. After this, the values can be 7135 read, modified, or added to: 7136 7137 myvalues.foo += 2 7138 empty_scope.new_thing = [ 1, 2, 3 ] 7139 7140 Scope equality is defined as single-level scopes identical within the current 7141 scope. That is, all values in the first scope must be present and identical 7142 within the second, and vice versa. Note that this means inherited scopes are 7143 always unequal by definition. 7144``` 7145### <a name="io_conversion"></a>**Input and output conversion** 7146 7147``` 7148 Input and output conversions are arguments to file and process functions 7149 that specify how to convert data to or from external formats. The possible 7150 values for parameters specifying conversions are: 7151 7152 "" (the default) 7153 input: Discard the result and return None. 7154 7155 output: If value is a list, then "list lines"; otherwise "value". 7156 7157 "list lines" 7158 input: 7159 Return the file contents as a list, with a string for each line. The 7160 newlines will not be present in the result. The last line may or may 7161 not end in a newline. 7162 7163 After splitting, each individual line will be trimmed of whitespace on 7164 both ends. 7165 7166 output: 7167 Renders the value contents as a list, with a string for each line. The 7168 newlines will not be present in the result. The last line will end in 7169 with a newline. 7170 7171 "scope" 7172 input: 7173 Execute the block as GN code and return a scope with the resulting 7174 values in it. If the input was: 7175 a = [ "hello.cc", "world.cc" ] 7176 b = 26 7177 and you read the result into a variable named "val", then you could 7178 access contents the "." operator on "val": 7179 sources = val.a 7180 some_count = val.b 7181 7182 output: 7183 Renders the value contents as a GN code block, reversing the input 7184 result above. 7185 7186 "string" 7187 input: Return the file contents into a single string. 7188 7189 output: 7190 Render the value contents into a single string. The output is: 7191 a string renders with quotes, e.g. "str" 7192 an integer renders as a stringified integer, e.g. "6" 7193 a boolean renders as the associated string, e.g. "true" 7194 a list renders as a representation of its contents, e.g. "[\"str\", 6]" 7195 a scope renders as a GN code block of its values. If the Value was: 7196 Value val; 7197 val.a = [ "hello.cc", "world.cc" ]; 7198 val.b = 26 7199 the resulting output would be: 7200 "{ 7201 a = [ \"hello.cc\", \"world.cc\" ] 7202 b = 26 7203 }" 7204 7205 "value" 7206 input: 7207 Parse the input as if it was a literal rvalue in a buildfile. Examples of 7208 typical program output using this mode: 7209 [ "foo", "bar" ] (result will be a list) 7210 or 7211 "foo bar" (result will be a string) 7212 or 7213 5 (result will be an integer) 7214 7215 Note that if the input is empty, the result will be a null value which 7216 will produce an error if assigned to a variable. 7217 7218 output: 7219 Render the value contents as a literal rvalue. Strings render with 7220 escaped quotes. 7221 7222 "json" 7223 input: Parse the input as a JSON and convert it to equivalent GN rvalue. 7224 7225 output: Convert the Value to equivalent JSON value. 7226 7227 The data type mapping is: 7228 a string in JSON maps to string in GN 7229 an integer in JSON maps to integer in GN 7230 a float in JSON is unsupported and will result in an error 7231 an object in JSON maps to scope in GN 7232 an array in JSON maps to list in GN 7233 a boolean in JSON maps to boolean in GN 7234 a null in JSON is unsupported and will result in an error 7235 7236 Nota that the input dictionary keys have to be valid GN identifiers 7237 otherwise they will produce an error. 7238 7239 "trim ..." (input only) 7240 Prefixing any of the other transformations with the word "trim" will 7241 result in whitespace being trimmed from the beginning and end of the 7242 result before processing. 7243 7244 Examples: "trim string" or "trim list lines" 7245 7246 Note that "trim value" is useless because the value parser skips 7247 whitespace anyway. 7248``` 7249### <a name="file_pattern"></a>**File patterns** 7250 7251``` 7252 File patterns are VERY limited regular expressions. They must match the 7253 entire input string to be counted as a match. In regular expression parlance, 7254 there is an implicit "^...$" surrounding your input. If you want to match a 7255 substring, you need to use wildcards at the beginning and end. 7256 7257 There are only two special tokens understood by the pattern matcher. 7258 Everything else is a literal. 7259 7260 - "*" Matches zero or more of any character. It does not depend on the 7261 preceding character (in regular expression parlance it is equivalent to 7262 ".*"). 7263 7264 - "\b" Matches a path boundary. This will match the beginning or end of a 7265 string, or a slash. 7266``` 7267 7268#### **Pattern examples** 7269 7270``` 7271 "*asdf*" 7272 Matches a string containing "asdf" anywhere. 7273 7274 "asdf" 7275 Matches only the exact string "asdf". 7276 7277 "*.cc" 7278 Matches strings ending in the literal ".cc". 7279 7280 "\bwin/*" 7281 Matches "win/foo" and "foo/win/bar.cc" but not "iwin/foo". 7282``` 7283### <a name="label_pattern"></a>**Label patterns** 7284 7285``` 7286 A label pattern is a way of expressing one or more labels in a portion of the 7287 source tree. They are not general regular expressions. 7288 7289 They can take the following forms only: 7290 7291 - Explicit (no wildcard): 7292 "//foo/bar:baz" 7293 ":baz" 7294 7295 - Wildcard target names: 7296 "//foo/bar:*" (all targets in the //foo/bar/BUILD.gn file) 7297 ":*" (all targets in the current build file) 7298 7299 - Wildcard directory names ("*" is only supported at the end) 7300 "*" (all targets) 7301 "//foo/bar/*" (all targets in any subdir of //foo/bar) 7302 "./*" (all targets in the current build file or sub dirs) 7303 7304 Any of the above forms can additionally take an explicit toolchain 7305 in parenthesis at the end of the label pattern. In this case, the 7306 toolchain must be fully qualified (no wildcards are supported in the 7307 toolchain name). 7308 7309 "//foo:bar(//build/toolchain:mac)" 7310 An explicit target in an explicit toolchain. 7311 7312 ":*(//build/toolchain/linux:32bit)" 7313 All targets in the current build file using the 32-bit Linux toolchain. 7314 7315 "//foo/*(//build/toolchain:win)" 7316 All targets in //foo and any subdirectory using the Windows 7317 toolchain. 7318``` 7319### <a name="labels"></a>**About labels** 7320 7321``` 7322 Everything that can participate in the dependency graph (targets, configs, 7323 and toolchains) are identified by labels. A common label looks like: 7324 7325 //base/test:test_support 7326 7327 This consists of a source-root-absolute path, a colon, and a name. This means 7328 to look for the thing named "test_support" in "base/test/BUILD.gn". 7329 7330 You can also specify system absolute paths if necessary. Typically such 7331 paths would be specified via a build arg so the developer can specify where 7332 the component is on their system. 7333 7334 /usr/local/foo:bar (Posix) 7335 /C:/Program Files/MyLibs:bar (Windows) 7336``` 7337 7338#### **Toolchains** 7339 7340``` 7341 A canonical label includes the label of the toolchain being used. Normally, 7342 the toolchain label is implicitly inherited from the current execution 7343 context, but you can override this to specify cross-toolchain dependencies: 7344 7345 //base/test:test_support(//build/toolchain/win:msvc) 7346 7347 Here GN will look for the toolchain definition called "msvc" in the file 7348 "//build/toolchain/win" to know how to compile this target. 7349``` 7350 7351#### **Relative labels** 7352 7353``` 7354 If you want to refer to something in the same buildfile, you can omit 7355 the path name and just start with a colon. This format is recommended for 7356 all same-file references. 7357 7358 :base 7359 7360 Labels can be specified as being relative to the current directory. 7361 Stylistically, we prefer to use absolute paths for all non-file-local 7362 references unless a build file needs to be run in different contexts (like a 7363 project needs to be both standalone and pulled into other projects in 7364 difference places in the directory hierarchy). 7365 7366 source/plugin:myplugin 7367 ../net:url_request 7368``` 7369 7370#### **Implicit names** 7371 7372``` 7373 If a name is unspecified, it will inherit the directory name. Stylistically, 7374 we prefer to omit the colon and name when possible: 7375 7376 //net -> //net:net 7377 //tools/gn -> //tools/gn:gn 7378``` 7379### <a name="metadata_collection"></a>**Metadata Collection** 7380 7381``` 7382 Metadata is information attached to targets throughout the dependency tree. GN 7383 allows for the collection of this data into files written during the generation 7384 step, enabling users to expose and aggregate this data based on the dependency 7385 tree. 7386``` 7387 7388#### **generated_file targets** 7389 7390``` 7391 Similar to the write_file() function, the generated_file target type 7392 creates a file in the specified location with the specified content. The 7393 primary difference between write_file() and this target type is that the 7394 write_file function does the file write at parse time, while the 7395 generated_file target type writes at target resolution time. See 7396 "gn help generated_file" for more detail. 7397 7398 When written at target resolution time, generated_file enables GN to 7399 collect and write aggregated metadata from dependents. 7400 7401 A generated_file target can declare either 'contents' to write statically 7402 known contents to a file or 'data_keys' to aggregate metadata and write the 7403 result to a file. It can also specify 'walk_keys' (to restrict the metadata 7404 collection), 'output_conversion', and 'rebase'. 7405``` 7406 7407#### **Collection and Aggregation** 7408 7409``` 7410 Targets can declare a 'metadata' variable containing a scope, and this 7411 metadata may be collected and written out to a file specified by 7412 generated_file aggregation targets. The 'metadata' scope must contain 7413 only list values since the aggregation step collects a list of these values. 7414 7415 During the target resolution, generated_file targets will walk their 7416 dependencies recursively, collecting metadata based on the specified 7417 'data_keys'. 'data_keys' is specified as a list of strings, used by the walk 7418 to identify which variables in dependencies' 'metadata' scopes to collect. 7419 7420 The walk begins with the listed dependencies of the 'generated_file' target. 7421 The 'metadata' scope for each dependency is inspected for matching elements 7422 of the 'generated_file' target's 'data_keys' list. If a match is found, the 7423 data from the dependent's matching key list is appended to the aggregate walk 7424 list. Note that this means that if more than one walk key is specified, the 7425 data in all of them will be aggregated into one list. From there, the walk 7426 will then recurse into the dependencies of each target it encounters, 7427 collecting the specified metadata for each. 7428 7429 For example: 7430 7431 group("a") { 7432 metadata = { 7433 doom_melon = [ "enable" ] 7434 my_files = [ "foo.cpp" ] 7435 my_extra_files = [ "bar.cpp" ] 7436 } 7437 7438 deps = [ ":b" ] 7439 } 7440 7441 group("b") { 7442 metadata = { 7443 my_files = [ "baz.cpp" ] 7444 } 7445 } 7446 7447 generated_file("metadata") { 7448 outputs = [ "$root_build_dir/my_files.json" ] 7449 data_keys = [ "my_files", "my_extra_files" ] 7450 7451 deps = [ ":a" ] 7452 } 7453 7454 The above will produce the following file data: 7455 7456 foo.cpp 7457 bar.cpp 7458 baz.cpp 7459 7460 The dependency walk can be limited by using the 'walk_keys'. This is a list of 7461 labels that should be included in the walk. All labels specified here should 7462 also be in one of the deps lists. These keys act as barriers, where the walk 7463 will only recurse into the targets listed. An empty list in all specified 7464 barriers will end that portion of the walk. 7465 7466 group("a") { 7467 metadata = { 7468 my_files = [ "foo.cpp" ] 7469 my_files_barrier = [ ":b" ] 7470 } 7471 7472 deps = [ ":b", ":c" ] 7473 } 7474 7475 group("b") { 7476 metadata = { 7477 my_files = [ "bar.cpp" ] 7478 } 7479 } 7480 7481 group("c") { 7482 metadata = { 7483 my_files = [ "doom_melon.cpp" ] 7484 } 7485 } 7486 7487 generated_file("metadata") { 7488 outputs = [ "$root_build_dir/my_files.json" ] 7489 data_keys = [ "my_files" ] 7490 walk_keys = [ "my_files_barrier" ] 7491 7492 deps = [ ":a" ] 7493 } 7494 7495 The above will produce the following file data (note that `doom_melon.cpp` is 7496 not included): 7497 7498 foo.cpp 7499 bar.cpp 7500 7501 A common example of this sort of barrier is in builds that have host tools 7502 built as part of the tree, but do not want the metadata from those host tools 7503 to be collected with the target-side code. 7504``` 7505 7506#### **Common Uses** 7507 7508``` 7509 Metadata can be used to collect information about the different targets in the 7510 build, and so a common use is to provide post-build tooling with a set of data 7511 necessary to do aggregation tasks. For example, if each test target specifies 7512 the output location of its binary to run in a metadata field, that can be 7513 collected into a single file listing the locations of all tests in the 7514 dependency tree. A local build tool (or continuous integration infrastructure) 7515 can then use that file to know which tests exist, and where, and run them 7516 accordingly. 7517 7518 Another use is in image creation, where a post-build image tool needs to know 7519 various pieces of information about the components it should include in order 7520 to put together the correct image. 7521``` 7522### <a name="ninja_rules"></a>**Ninja build rules** 7523 7524#### **The "all" and "default" rules** 7525 7526``` 7527 All generated targets (see "gn help execution") will be added to an implicit 7528 build rule called "all" so "ninja all" will always compile everything. The 7529 default rule will be used by Ninja if no specific target is specified (just 7530 typing "ninja"). If there is a target named "default" in the root build file, 7531 it will be the default build rule, otherwise the implicit "all" rule will be 7532 used. 7533``` 7534 7535#### **Phony rules** 7536 7537``` 7538 GN generates Ninja "phony" rules for targets in the default toolchain. The 7539 phony rules can collide with each other and with the names of generated files 7540 so are generated with the following priority: 7541 7542 1. Actual files generated by the build always take precedence. 7543 7544 2. Targets in the toplevel //BUILD.gn file. 7545 7546 3. Targets in toplevel directories matching the names of the directories. 7547 So "ninja foo" can be used to compile "//foo:foo". This only applies to 7548 the first level of directories since usually these are the most 7549 important (so this won't apply to "//foo/bar:bar"). 7550 7551 4. The short names of executables if there is only one executable with that 7552 short name. Use "ninja doom_melon" to compile the 7553 "//tools/fruit:doom_melon" executable. 7554 7555 5. The short names of all targets if there is only one target with that 7556 short name. 7557 7558 6. Full label name with no leading slashes. So you can use 7559 "ninja tools/fruit:doom_melon" to build "//tools/fruit:doom_melon". 7560 7561 7. Labels with an implicit name part (when the short names match the 7562 directory). So you can use "ninja foo/bar" to compile "//foo/bar:bar". 7563 7564 These "phony" rules are provided only for running Ninja since this matches 7565 people's historical expectations for building. For consistency with the rest 7566 of the program, GN introspection commands accept explicit labels. 7567 7568 To explicitly compile a target in a non-default toolchain, you must give 7569 Ninja the exact name of the output file relative to the build directory. 7570``` 7571### <a name="nogncheck"></a>**nogncheck**: Skip an include line from checking. 7572 7573``` 7574 GN's header checker helps validate that the includes match the build 7575 dependency graph. Sometimes an include might be conditional or otherwise 7576 problematic, but you want to specifically allow it. In this case, it can be 7577 whitelisted. 7578 7579 Include lines containing the substring "nogncheck" will be excluded from 7580 header checking. The most common case is a conditional include: 7581 7582 #if defined(ENABLE_DOOM_MELON) 7583 #include "tools/doom_melon/doom_melon.h" // nogncheck 7584 #endif 7585 7586 If the build file has a conditional dependency on the corresponding target 7587 that matches the conditional include, everything will always link correctly: 7588 7589 source_set("mytarget") { 7590 ... 7591 if (enable_doom_melon) { 7592 defines = [ "ENABLE_DOOM_MELON" ] 7593 deps += [ "//tools/doom_melon" ] 7594 } 7595 7596 But GN's header checker does not understand preprocessor directives, won't 7597 know it matches the build dependencies, and will flag this include as 7598 incorrect when the condition is false. 7599``` 7600 7601#### **More information** 7602 7603``` 7604 The topic "gn help check" has general information on how checking works and 7605 advice on fixing problems. Targets can also opt-out of checking, see 7606 "gn help check_includes". 7607``` 7608### <a name="runtime_deps"></a>**Runtime dependencies** 7609 7610``` 7611 Runtime dependencies of a target are exposed via the "runtime_deps" category 7612 of "gn desc" (see "gn help desc") or they can be written at build generation 7613 time via write_runtime_deps(), or --runtime-deps-list-file (see "gn help 7614 --runtime-deps-list-file"). 7615 7616 To a first approximation, the runtime dependencies of a target are the set of 7617 "data" files, data directories, and the shared libraries from all transitive 7618 dependencies. Executables, shared libraries, and loadable modules are 7619 considered runtime dependencies of themselves. 7620``` 7621 7622#### **Executables** 7623 7624``` 7625 Executable targets and those executable targets' transitive dependencies are 7626 not considered unless that executable is listed in "data_deps". Otherwise, GN 7627 assumes that the executable (and everything it requires) is a build-time 7628 dependency only. 7629``` 7630 7631#### **Actions and copies** 7632 7633``` 7634 Action and copy targets that are listed as "data_deps" will have all of their 7635 outputs and data files considered as runtime dependencies. Action and copy 7636 targets that are "deps" or "public_deps" will have only their data files 7637 considered as runtime dependencies. These targets can list an output file in 7638 both the "outputs" and "data" lists to force an output file as a runtime 7639 dependency in all cases. 7640 7641 The different rules for deps and data_deps are to express build-time (deps) 7642 vs. run-time (data_deps) outputs. If GN counted all build-time copy steps as 7643 data dependencies, there would be a lot of extra stuff, and if GN counted all 7644 run-time dependencies as regular deps, the build's parallelism would be 7645 unnecessarily constrained. 7646 7647 This rule can sometimes lead to unintuitive results. For example, given the 7648 three targets: 7649 A --[data_deps]--> B --[deps]--> ACTION 7650 GN would say that A does not have runtime deps on the result of the ACTION, 7651 which is often correct. But the purpose of the B target might be to collect 7652 many actions into one logic unit, and the "data"-ness of A's dependency is 7653 lost. Solutions: 7654 7655 - List the outputs of the action in its data section (if the results of 7656 that action are always runtime files). 7657 - Have B list the action in data_deps (if the outputs of the actions are 7658 always runtime files). 7659 - Have B list the action in both deps and data deps (if the outputs might be 7660 used in both contexts and you don't care about unnecessary entries in the 7661 list of files required at runtime). 7662 - Split B into run-time and build-time versions with the appropriate "deps" 7663 for each. 7664``` 7665 7666#### **Static libraries and source sets** 7667 7668``` 7669 The results of static_library or source_set targets are not considered 7670 runtime dependencies since these are assumed to be intermediate targets only. 7671 If you need to list a static library as a runtime dependency, you can 7672 manually compute the .a/.lib file name for the current platform and list it 7673 in the "data" list of a target (possibly on the static library target 7674 itself). 7675``` 7676 7677#### **Multiple outputs** 7678 7679``` 7680 Linker tools can specify which of their outputs should be considered when 7681 computing the runtime deps by setting runtime_outputs. If this is unset on 7682 the tool, the default will be the first output only. 7683``` 7684### <a name="source_expansion"></a>**How Source Expansion Works** 7685 7686``` 7687 Source expansion is used for the action_foreach and copy target types to map 7688 source file names to output file names or arguments. 7689 7690 To perform source expansion in the outputs, GN maps every entry in the 7691 sources to every entry in the outputs list, producing the cross product of 7692 all combinations, expanding placeholders (see below). 7693 7694 Source expansion in the args works similarly, but performing the placeholder 7695 substitution produces a different set of arguments for each invocation of the 7696 script. 7697 7698 If no placeholders are found, the outputs or args list will be treated as a 7699 static list of literal file names that do not depend on the sources. 7700 7701 See "gn help copy" and "gn help action_foreach" for more on how this is 7702 applied. 7703``` 7704 7705#### **Placeholders** 7706 7707``` 7708 This section discusses only placeholders for actions. There are other 7709 placeholders used in the definition of tools. See "gn help tool" for those. 7710 7711 {{source}} 7712 The name of the source file including directory (*). This will generally 7713 be used for specifying inputs to a script in the "args" variable. 7714 "//foo/bar/baz.txt" => "../../foo/bar/baz.txt" 7715 7716 {{source_file_part}} 7717 The file part of the source including the extension. 7718 "//foo/bar/baz.txt" => "baz.txt" 7719 7720 {{source_name_part}} 7721 The filename part of the source file with no directory or extension. This 7722 will generally be used for specifying a transformation from a source file 7723 to a destination file with the same name but different extension. 7724 "//foo/bar/baz.txt" => "baz" 7725 7726 {{source_dir}} 7727 The directory (*) containing the source file with no trailing slash. 7728 "//foo/bar/baz.txt" => "../../foo/bar" 7729 7730 {{source_root_relative_dir}} 7731 The path to the source file's directory relative to the source root, with 7732 no leading "//" or trailing slashes. If the path is system-absolute, 7733 (beginning in a single slash) this will just return the path with no 7734 trailing slash. This value will always be the same, regardless of whether 7735 it appears in the "outputs" or "args" section. 7736 "//foo/bar/baz.txt" => "foo/bar" 7737 7738 {{source_gen_dir}} 7739 The generated file directory (*) corresponding to the source file's path. 7740 This will be different than the target's generated file directory if the 7741 source file is in a different directory than the BUILD.gn file. 7742 "//foo/bar/baz.txt" => "gen/foo/bar" 7743 7744 {{source_out_dir}} 7745 The object file directory (*) corresponding to the source file's path, 7746 relative to the build directory. this us be different than the target's 7747 out directory if the source file is in a different directory than the 7748 build.gn file. 7749 "//foo/bar/baz.txt" => "obj/foo/bar" 7750 7751 {{source_target_relative}} 7752 The path to the source file relative to the target's directory. This will 7753 generally be used for replicating the source directory layout in the 7754 output directory. This can only be used in actions and bundle_data 7755 targets. It is an error to use in process_file_template where there is no 7756 "target". 7757 "//foo/bar/baz.txt" => "baz.txt" 7758``` 7759 7760#### **(*) Note on directories** 7761 7762``` 7763 Paths containing directories (except the source_root_relative_dir) will be 7764 different depending on what context the expansion is evaluated in. Generally 7765 it should "just work" but it means you can't concatenate strings containing 7766 these values with reasonable results. 7767 7768 Details: source expansions can be used in the "outputs" variable, the "args" 7769 variable, and in calls to "process_file_template". The "args" are passed to a 7770 script which is run from the build directory, so these directories will 7771 relative to the build directory for the script to find. In the other cases, 7772 the directories will be source- absolute (begin with a "//") because the 7773 results of those expansions will be handled by GN internally. 7774``` 7775 7776#### **Examples** 7777 7778``` 7779 Non-varying outputs: 7780 action("hardcoded_outputs") { 7781 sources = [ "input1.idl", "input2.idl" ] 7782 outputs = [ "$target_out_dir/output1.dat", 7783 "$target_out_dir/output2.dat" ] 7784 } 7785 The outputs in this case will be the two literal files given. 7786 7787 Varying outputs: 7788 action_foreach("varying_outputs") { 7789 sources = [ "input1.idl", "input2.idl" ] 7790 outputs = [ "{{source_gen_dir}}/{{source_name_part}}.h", 7791 "{{source_gen_dir}}/{{source_name_part}}.cc" ] 7792 } 7793 Performing source expansion will result in the following output names: 7794 //out/Debug/obj/mydirectory/input1.h 7795 //out/Debug/obj/mydirectory/input1.cc 7796 //out/Debug/obj/mydirectory/input2.h 7797 //out/Debug/obj/mydirectory/input2.cc 7798``` 7799### <a name="switch_list"></a>**Available global switches** 7800 7801``` 7802 Do "gn help --the_switch_you_want_help_on" for more. Individual commands may 7803 take command-specific switches not listed here. See the help on your specific 7804 command for more. 7805``` 7806``` 7807 * --args: Specifies build arguments overrides. 7808 * --color: Force colored output. 7809 * --dotfile: Override the name of the ".gn" file. 7810 * --fail-on-unused-args: Treat unused build args as fatal errors. 7811 * --markdown: Write help output in the Markdown format. 7812 * --ninja-executable: Set the Ninja executable. 7813 * --nocolor: Force non-colored output. 7814 * -q: Quiet mode. Don't print output on success. 7815 * --root: Explicitly specify source root. 7816 * --root-target: Override the root target. 7817 * --runtime-deps-list-file: Save runtime dependencies for targets in file. 7818 * --script-executable: Set the executable used to execute scripts. 7819 * --threads: Specify number of worker threads. 7820 * --time: Outputs a summary of how long everything took. 7821 * --tracelog: Writes a Chrome-compatible trace log to the given file. 7822 * -v: Verbose logging. 7823 * --version: Prints the GN version number and exits. 7824``` 7825 7826