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