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