blob: ea95bc801fec5d784f7d4a46d77252e7dac6ecdc [file] [log] [blame] [view]
Brett Wilson796ed472018-07-16 15:11:09 -07001# GN Reference
2
3*This page is automatically generated from* `gn help --markdown all`.
4
5## Contents
6
7* [Commands](#commands)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08008 * [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)
RJ Ascani4e260f12020-10-19 17:41:51 -070012 * [clean_stale: Cleans the stale output files from the output directory.](#cmd_clean_stale)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080013 * [desc: Show lots of insightful information about a target or config.](#cmd_desc)
Julie Hockettd69a9c32019-01-23 14:36:18 -080014 * [format: Format .gn files.](#cmd_format)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080015 * [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)
Brett Wilson74397092020-03-18 16:34:14 -070019 * [outputs: Which files a source/target make.](#cmd_outputs)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080020 * [path: Find paths between two targets.](#cmd_path)
21 * [refs: Find stuff referencing a target or file.](#cmd_refs)
Brett Wilson796ed472018-07-16 15:11:09 -070022* [Target declarations](#targets)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080023 * [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)
Julie Hockettce1fa072019-05-07 17:44:37 -070032 * [rust_library: Declare a Rust library target.](#func_rust_library)
Petr Hosekfe36c7c2019-11-26 14:38:08 -080033 * [rust_proc_macro: Declare a Rust procedural macro target.](#func_rust_proc_macro)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080034 * [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)
Antonio Sartoriecaaf4b2022-07-01 05:57:08 +000037 * [target: Declare a target with the given programmatic type.](#func_target)
Brett Wilson796ed472018-07-16 15:11:09 -070038* [Buildfile functions](#functions)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080039 * [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)
Sylvain Defresneaff489a2020-03-11 18:27:43 +010044 * [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)
Aaron Woode05c0aa2024-02-14 13:40:53 -080046 * [filter_labels_exclude: Remove labels that match a set of patterns.](#func_filter_labels_exclude)
47 * [filter_labels_include: Remove labels that do not match a set of patterns.](#func_filter_labels_include)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080048 * [foreach: Iterate over a list.](#func_foreach)
49 * [forward_variables_from: Copies variables from a different scope.](#func_forward_variables_from)
50 * [get_label_info: Get an attribute from a target's label.](#func_get_label_info)
51 * [get_path_info: Extract parts of a file or directory name.](#func_get_path_info)
52 * [get_target_outputs: [file list] Get the list of outputs from a target.](#func_get_target_outputs)
53 * [getenv: Get an environment variable.](#func_getenv)
54 * [import: Import a file into the current scope.](#func_import)
Aaron Woode05c0aa2024-02-14 13:40:53 -080055 * [label_matches: Returns whether a label matches any of a list of patterns.](#func_label_matches)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080056 * [not_needed: Mark variables from scope as not needed.](#func_not_needed)
Andrew Grievef98b6d72025-02-25 08:54:51 -080057 * [path_exists: Returns whether the given path exists.](#func_path_exists)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080058 * [pool: Defines a pool object.](#func_pool)
59 * [print: Prints to the console.](#func_print)
Aaron Wood24062bb2022-04-25 20:37:48 -070060 * [print_stack_trace: Prints a stack trace.](#func_print_stack_trace)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080061 * [process_file_template: Do template expansion over a list of files.](#func_process_file_template)
62 * [read_file: Read a file into a variable.](#func_read_file)
63 * [rebase_path: Rebase a file or directory to another location.](#func_rebase_path)
64 * [set_default_toolchain: Sets the default toolchain name.](#func_set_default_toolchain)
65 * [set_defaults: Set default values for a target type.](#func_set_defaults)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080066 * [split_list: Splits a list into N different sub-lists.](#func_split_list)
Keir Mierle6ae63302019-11-08 23:02:18 -080067 * [string_join: Concatenates a list of strings with a separator.](#func_string_join)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080068 * [string_replace: Replaces substring in the given string.](#func_string_replace)
Keir Mierle6ae63302019-11-08 23:02:18 -080069 * [string_split: Split string into a list of strings.](#func_string_split)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080070 * [template: Define a template rule.](#func_template)
71 * [tool: Specify arguments to a toolchain tool.](#func_tool)
72 * [toolchain: Defines a toolchain.](#func_toolchain)
73 * [write_file: Write a file to disk.](#func_write_file)
Brett Wilson796ed472018-07-16 15:11:09 -070074* [Built-in predefined variables](#predefined_variables)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080075 * [current_cpu: [string] The processor architecture of the current toolchain.](#var_current_cpu)
76 * [current_os: [string] The operating system of the current toolchain.](#var_current_os)
77 * [current_toolchain: [string] Label of the current toolchain.](#var_current_toolchain)
78 * [default_toolchain: [string] Label of the default toolchain.](#var_default_toolchain)
James Robinson61377e32020-02-13 15:20:07 -080079 * [gn_version: [number] The version of gn.](#var_gn_version)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080080 * [host_cpu: [string] The processor architecture that GN is running on.](#var_host_cpu)
81 * [host_os: [string] The operating system that GN is running on.](#var_host_os)
82 * [invoker: [string] The invoking scope inside a template.](#var_invoker)
83 * [python_path: [string] Absolute path of Python.](#var_python_path)
84 * [root_build_dir: [string] Directory where build commands are run.](#var_root_build_dir)
85 * [root_gen_dir: [string] Directory for the toolchain's generated files.](#var_root_gen_dir)
86 * [root_out_dir: [string] Root directory for toolchain output files.](#var_root_out_dir)
87 * [target_cpu: [string] The desired cpu architecture for the build.](#var_target_cpu)
88 * [target_gen_dir: [string] Directory for a target's generated files.](#var_target_gen_dir)
89 * [target_name: [string] The name of the current target.](#var_target_name)
90 * [target_os: [string] The desired operating system for the build.](#var_target_os)
91 * [target_out_dir: [string] Directory for target output files.](#var_target_out_dir)
Brett Wilson796ed472018-07-16 15:11:09 -070092* [Variables you set in targets](#target_variables)
Julie Hockettce1fa072019-05-07 17:44:37 -070093 * [aliased_deps: [scope] Set of crate-dependency pairs.](#var_aliased_deps)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080094 * [all_dependent_configs: [label list] Configs to be forced on dependents.](#var_all_dependent_configs)
95 * [allow_circular_includes_from: [label list] Permit includes from deps.](#var_allow_circular_includes_from)
96 * [arflags: [string list] Arguments passed to static_library archiver.](#var_arflags)
97 * [args: [string list] Arguments passed to an action.](#var_args)
98 * [asmflags: [string list] Flags passed to the assembler.](#var_asmflags)
99 * [assert_no_deps: [label pattern list] Ensure no deps on these targets.](#var_assert_no_deps)
Sylvain Defresne89e64252020-08-07 13:01:06 +0200100 * [bridge_header: [string] Path to C/Objective-C compatibility header.](#var_bridge_header)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800101 * [bundle_contents_dir: Expansion of {{bundle_contents_dir}} in create_bundle.](#var_bundle_contents_dir)
102 * [bundle_deps_filter: [label list] A list of labels that are filtered out.](#var_bundle_deps_filter)
103 * [bundle_executable_dir: Expansion of {{bundle_executable_dir}} in create_bundle](#var_bundle_executable_dir)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800104 * [bundle_resources_dir: Expansion of {{bundle_resources_dir}} in create_bundle.](#var_bundle_resources_dir)
105 * [bundle_root_dir: Expansion of {{bundle_root_dir}} in create_bundle.](#var_bundle_root_dir)
106 * [cflags: [string list] Flags passed to all C compiler variants.](#var_cflags)
107 * [cflags_c: [string list] Flags passed to the C compiler.](#var_cflags_c)
108 * [cflags_cc: [string list] Flags passed to the C++ compiler.](#var_cflags_cc)
109 * [cflags_objc: [string list] Flags passed to the Objective C compiler.](#var_cflags_objc)
110 * [cflags_objcc: [string list] Flags passed to the Objective C++ compiler.](#var_cflags_objcc)
111 * [check_includes: [boolean] Controls whether a target's files are checked.](#var_check_includes)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800112 * [complete_static_lib: [boolean] Links all deps into a static library.](#var_complete_static_lib)
113 * [configs: [label list] Configs applying to this target or config.](#var_configs)
114 * [contents: Contents to write to file.](#var_contents)
Julie Hockettce1fa072019-05-07 17:44:37 -0700115 * [crate_name: [string] The name for the compiled crate.](#var_crate_name)
116 * [crate_root: [string] The root source file for a binary or library.](#var_crate_root)
117 * [crate_type: [string] The type of linkage to use on a shared_library.](#var_crate_type)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800118 * [data: [file list] Runtime data file dependencies.](#var_data)
119 * [data_deps: [label list] Non-linked dependencies.](#var_data_deps)
120 * [data_keys: [string list] Keys from which to collect metadata.](#var_data_keys)
121 * [defines: [string list] C preprocessor defines.](#var_defines)
122 * [depfile: [string] File name for input dependencies for actions.](#var_depfile)
123 * [deps: [label list] Private linked dependencies.](#var_deps)
Petr Hoseka1413862020-01-03 12:54:33 -0800124 * [externs: [scope] Set of Rust crate-dependency pairs.](#var_externs)
Sylvain Defresnea09ec162020-01-16 12:36:40 +0100125 * [framework_dirs: [directory list] Additional framework search directories.](#var_framework_dirs)
126 * [frameworks: [name list] Name of frameworks that must be linked.](#var_frameworks)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800127 * [friend: [label pattern list] Allow targets to include private headers.](#var_friend)
Tyler Mandry4a648092022-02-15 19:47:09 +0000128 * [gen_deps: [label list] Declares targets that should generate when this one does.](#var_gen_deps)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800129 * [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)
Joseph Ryanad1e5ce2023-04-26 13:48:01 -0700135 * [mnemonic: [string] Prefix displayed when ninja runs this action.](#var_mnemonic)
Sylvain Defresne89e64252020-08-07 13:01:06 +0200136 * [module_name: [string] The name for the compiled module.](#var_module_name)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800137 * [output_conversion: Data format for generated_file targets.](#var_output_conversion)
138 * [output_dir: [directory] Directory to put output file in.](#var_output_dir)
139 * [output_extension: [string] Value to use for the output's file extension.](#var_output_extension)
140 * [output_name: [string] Name for the output file other than the default.](#var_output_name)
141 * [output_prefix_override: [boolean] Don't use prefix for output name.](#var_output_prefix_override)
142 * [outputs: [file list] Output files for actions and copy targets.](#var_outputs)
143 * [partial_info_plist: [filename] Path plist from asset catalog compiler.](#var_partial_info_plist)
Petr Hosek7a6231e2022-10-22 23:14:18 +0000144 * [pool: [string] Label of the pool used by binary targets and actions.](#var_pool)
Sylvain Defresnef07499a2024-04-04 13:06:37 +0200145 * [post_processing_args: [string list] Args for the post-processing script.](#var_post_processing_args)
Sylvain Defresne19281422025-08-01 10:40:16 +0200146 * [post_processing_manifest: [file] Name of the generated bundle manifest.](#var_post_processing_manifest)
Sylvain Defresnef07499a2024-04-04 13:06:37 +0200147 * [post_processing_outputs: [file list] Outputs of the post-processing step.](#var_post_processing_outputs)
148 * [post_processing_script: [file name] Script for the post-processing step.](#var_post_processing_script)
149 * [post_processing_sources: [file list] Sources for the post-processing step.](#var_post_processing_sources)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800150 * [precompiled_header: [string] Header file to precompile.](#var_precompiled_header)
151 * [precompiled_header_type: [string] "gcc" or "msvc".](#var_precompiled_header_type)
152 * [precompiled_source: [file name] Source file to precompile.](#var_precompiled_source)
Sylvain Defresnee5aee7b2023-06-08 10:08:10 -0400153 * [product_type: [string] Product type for the bundle.](#var_product_type)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800154 * [public: [file list] Declare public header files for a target.](#var_public)
155 * [public_configs: [label list] Configs applied to dependents.](#var_public_configs)
156 * [public_deps: [label list] Declare public dependencies.](#var_public_deps)
157 * [rebase: [boolean] Rebase collected metadata as files.](#var_rebase)
158 * [response_file_contents: [string list] Contents of .rsp file for actions.](#var_response_file_contents)
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +0100159 * [rustflags: [string list] Flags passed to the Rust compiler.](#var_rustflags)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800160 * [script: [file name] Script file for actions.](#var_script)
161 * [sources: [file list] Source files for a target.](#var_sources)
Sylvain Defresne89e64252020-08-07 13:01:06 +0200162 * [swiftflags: [string list] Flags passed to the swift compiler.](#var_swiftflags)
Julie Jeongeun Kimebc8f162025-05-19 11:45:26 +0900163 * [target_xcode_platform: [string] The desired platform for the build.](#var_target_xcode_platform)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800164 * [testonly: [boolean] Declares a target must only be used for testing.](#var_testonly)
Sylvain Defresnee5aee7b2023-06-08 10:08:10 -0400165 * [transparent: [bool] True if the bundle is transparent.](#var_transparent)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800166 * [visibility: [label list] A list of labels that can depend on a target.](#var_visibility)
167 * [walk_keys: [string list] Key(s) for managing the metadata collection walk.](#var_walk_keys)
Robert Sesekd0a6f072020-05-15 11:21:22 -0400168 * [weak_frameworks: [name list] Name of frameworks that must be weak linked.](#var_weak_frameworks)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800169 * [write_runtime_deps: Writes the target's runtime_deps to the given path.](#var_write_runtime_deps)
Harley Li0a9affb2020-06-03 10:38:42 -0400170 * [xcasset_compiler_flags: [string list] Flags passed to xcassets compiler](#var_xcasset_compiler_flags)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800171 * [xcode_extra_attributes: [scope] Extra attributes for Xcode projects.](#var_xcode_extra_attributes)
172 * [xcode_test_application_name: [string] Name for Xcode test target.](#var_xcode_test_application_name)
Brett Wilson796ed472018-07-16 15:11:09 -0700173* [Other help topics](#other)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800174 * all: Print all the help at once
Brett Wilson796ed472018-07-16 15:11:09 -0700175 * [buildargs: How build arguments work.](#buildargs)
176 * [dotfile: Info about the toplevel .gn file.](#dotfile)
177 * [execution: Build graph and execution overview.](#execution)
178 * [grammar: Language and grammar for GN build files.](#grammar)
Julie Hockett81ee1962019-05-13 11:24:42 -0700179 * [input_conversion: Processing input from exec_script and read_file.](#io_conversion)
Sylvain Defresneaff489a2020-03-11 18:27:43 +0100180 * [file_pattern: Matching more than one file.](#file_pattern)
Brett Wilson796ed472018-07-16 15:11:09 -0700181 * [label_pattern: Matching more than one label.](#label_pattern)
182 * [labels: About labels.](#labels)
Julie Hockett152c5142019-07-12 09:53:43 -0600183 * [metadata_collection: About metadata and its collection.](#metadata_collection)
Brett Wilson796ed472018-07-16 15:11:09 -0700184 * [ninja_rules: How Ninja build rules are named.](#ninja_rules)
185 * [nogncheck: Annotating includes for checking.](#nogncheck)
Julie Hockett81ee1962019-05-13 11:24:42 -0700186 * [output_conversion: Specifies how to transform a value to output.](#io_conversion)
Brett Wilson796ed472018-07-16 15:11:09 -0700187 * [runtime_deps: How runtime dependency computation works.](#runtime_deps)
188 * [source_expansion: Map sources to outputs for scripts.](#source_expansion)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800189 * [switches: Show available command-line switches.](#switch_list)
Brett Wilson796ed472018-07-16 15:11:09 -0700190
191## <a name="commands"></a>Commands
192
[email protected]449f3e42024-08-01 21:43:27 +0800193### <a name="cmd_analyze"></a>**gn analyze &lt;out_dir&gt; &lt;input_path&gt; &lt;output_path&gt;**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700194
195```
196 Analyze which targets are affected by a list of files.
197
198 This command takes three arguments:
199
200 out_dir is the path to the build directory.
201
202 input_path is a path to a file containing a JSON object with three fields:
203
204 - "files": A list of the filenames to check.
205
206 - "test_targets": A list of the labels for targets that are needed to run
207 the tests we wish to run.
208
Nico Weberdba01722021-04-06 08:56:46 -0400209 - "additional_compile_targets" (optional): A list of the labels for targets
210 that we wish to rebuild, but aren't necessarily needed for testing. The
211 important difference between this field and "test_targets" is that if an
212 item in the additional_compile_targets list refers to a group, then any
Brett Wilson796ed472018-07-16 15:11:09 -0700213 dependencies of that group will be returned if they are out of date, but
214 the group itself does not need to be. If the dependencies themselves are
215 groups, the same filtering is repeated. This filtering can be used to
216 avoid rebuilding dependencies of a group that are unaffected by the input
217 files. The list may also contain the string "all" to refer to a
218 pseudo-group that contains every root target in the build graph.
219
220 This filtering behavior is also known as "pruning" the list of compile
221 targets.
222
Nico Weberdba01722021-04-06 08:56:46 -0400223 If "additional_compile_targets" is absent, it defaults to the empty list.
224
Keir Mierle45611e32019-11-12 11:18:00 -0800225 If input_path is -, input is read from stdin.
226
Brett Wilson796ed472018-07-16 15:11:09 -0700227 output_path is a path indicating where the results of the command are to be
228 written. The results will be a file containing a JSON object with one or more
229 of following fields:
230
231 - "compile_targets": A list of the labels derived from the input
232 compile_targets list that are affected by the input files. Due to the way
233 the filtering works for compile targets as described above, this list may
234 contain targets that do not appear in the input list.
235
236 - "test_targets": A list of the labels from the input test_targets list that
237 are affected by the input files. This list will be a proper subset of the
238 input list.
239
240 - "invalid_targets": A list of any names from the input that do not exist in
241 the build graph. If this list is non-empty, the "error" field will also be
242 set to "Invalid targets".
243
244 - "status": A string containing one of three values:
245
246 - "Found dependency"
247 - "No dependency"
Sylvain Defresne7b0690e2020-06-26 15:33:01 +0200248 - "Found dependency (all)"
Brett Wilson796ed472018-07-16 15:11:09 -0700249
250 In the first case, the lists returned in compile_targets and test_targets
251 should be passed to ninja to build. In the second case, nothing was
252 affected and no build is necessary. In the third case, GN could not
253 determine the correct answer and returned the input as the output in order
254 to be safe.
255
256 - "error": This will only be present if an error occurred, and will contain
257 a string describing the error. This includes cases where the input file is
258 not in the right format, or contains invalid targets.
259
Keir Mierle45611e32019-11-12 11:18:00 -0800260 If output_path is -, output is written to stdout.
261
Brett Wilson796ed472018-07-16 15:11:09 -0700262 The command returns 1 if it is unable to read the input file or write the
263 output file, or if there is something wrong with the build such that gen
264 would also fail, and 0 otherwise. In particular, it returns 0 even if the
265 "error" key is non-empty and a non-fatal error occurred. In other words, it
266 tries really hard to always write something to the output JSON and convey
267 errors that way rather than via return codes.
268```
[email protected]449f3e42024-08-01 21:43:27 +0800269### <a name="cmd_args"></a>**gn args**: (command-line tool)&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700270
271```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800272 Display or configure arguments declared by the build.
273
274 gn args <out_dir> [--list] [--short] [--args] [--overrides-only]
275
Brett Wilson796ed472018-07-16 15:11:09 -0700276 See also "gn help buildargs" for a more high-level overview of how
277 build arguments work.
278```
279
280#### **Usage**
281
282```
283 gn args <out_dir>
284 Open the arguments for the given build directory in an editor. If the
285 given build directory doesn't exist, it will be created and an empty args
286 file will be opened in the editor. You would type something like this
287 into that file:
288 enable_doom_melon=false
289 os="android"
290
291 To find your editor on Posix, GN will search the environment variables in
292 order: GN_EDITOR, VISUAL, and EDITOR. On Windows GN will open the command
293 associated with .txt files.
294
295 Note: you can edit the build args manually by editing the file "args.gn"
296 in the build directory and then running "gn gen <out_dir>".
297
298 gn args <out_dir> --list[=<exact_arg>] [--short] [--overrides-only] [--json]
299 Lists all build arguments available in the current configuration, or, if
300 an exact_arg is specified for the list flag, just that one build
301 argument.
302
303 The output will list the declaration location, current value for the
304 build, default value (if different than the current value), and comment
305 preceding the declaration.
306
307 If --short is specified, only the names and current values will be
308 printed.
309
310 If --overrides-only is specified, only the names and current values of
311 arguments that have been overridden (i.e. non-default arguments) will
312 be printed. Overrides come from the <out_dir>/args.gn file and //.gn
313
314 If --json is specified, the output will be emitted in json format.
315 JSON schema for output:
316 [
317 {
318 "name": variable_name,
319 "current": {
320 "value": overridden_value,
321 "file": file_name,
322 "line": line_no
323 },
324 "default": {
325 "value": default_value,
326 "file": file_name,
327 "line": line_no
328 },
329 "comment": comment_string
330 },
331 ...
332 ]
333```
334
335#### **Examples**
336
337```
338 gn args out/Debug
339 Opens an editor with the args for out/Debug.
340
341 gn args out/Debug --list --short
342 Prints all arguments with their default values for the out/Debug
343 build.
344
345 gn args out/Debug --list --short --overrides-only
346 Prints overridden arguments for the out/Debug build.
347
348 gn args out/Debug --list=target_cpu
349 Prints information about the "target_cpu" argument for the "
350 "out/Debug
351 build.
352
353 gn args --list --args="os=\"android\" enable_doom_melon=true"
354 Prints all arguments with the default values for a build with the
355 given arguments set (which may affect the values of other
356 arguments).
357```
[email protected]449f3e42024-08-01 21:43:27 +0800358### <a name="cmd_check"></a>**gn check &lt;out_dir&gt; [&lt;label_pattern&gt;] [\--force] [\--check-generated]**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700359
360```
361 GN's include header checker validates that the includes for C-like source
362 files match the build dependency graph.
363
364 "gn check" is the same thing as "gn gen" with the "--check" flag except that
365 this command does not write out any build files. It's intended to be an easy
366 way to manually trigger include file checking.
367
368 The <label_pattern> can take exact labels or patterns that match more than
369 one (although not general regular expressions). If specified, only those
370 matching targets will be checked. See "gn help label_pattern" for details.
371```
372
373#### **Command-specific switches**
374
375```
Joe Armstrong39413942019-03-15 10:34:03 +0800376 --check-generated
377 Generated files are normally not checked since they do not exist
378 until after a build. With this flag, those generated files that
379 can be found on disk are also checked.
James Robinson49f59032020-01-08 14:05:51 -0800380
381 --check-system
382 Check system style includes (using <angle brackets>) in addition to
383 "double quote" includes.
Robert Sesekd0a6f072020-05-15 11:21:22 -0400384
385 --default-toolchain
386 Normally wildcard targets are matched in all toolchains. This
387 switch makes wildcard labels with no explicit toolchain reference
388 only match targets in the default toolchain.
389
390 Non-wildcard inputs with no explicit toolchain specification will
391 always match only a target in the default toolchain if one exists.
392
393 --force
394 Ignores specifications of "check_includes = false" and checks all
395 target's files that match the target label.
Brett Wilson796ed472018-07-16 15:11:09 -0700396```
397
398#### **What gets checked**
399
400```
Nate Fischer8ed01d32019-01-08 17:32:01 -0800401 The .gn file may specify a list of targets to be checked in the list
Erik Staab5d109d72020-06-29 22:53:23 -0700402 check_targets (see "gn help dotfile"). Alternatively, the .gn file may
403 specify a list of targets not to be checked in no_check_targets. If a label
404 pattern is specified on the command line, neither check_targets or
405 no_check_targets is used.
Brett Wilson796ed472018-07-16 15:11:09 -0700406
407 Targets can opt-out from checking with "check_includes = false" (see
408 "gn help check_includes").
409
410 For targets being checked:
411
412 - GN opens all C-like source files in the targets to be checked and scans
413 the top for includes.
414
Joe Armstrong39413942019-03-15 10:34:03 +0800415 - Generated files (that might not exist yet) are ignored unless
416 the --check-generated flag is provided.
417
Brett Wilson796ed472018-07-16 15:11:09 -0700418 - Includes with a "nogncheck" annotation are skipped (see
419 "gn help nogncheck").
420
James Robinson49f59032020-01-08 14:05:51 -0800421 - Includes using "quotes" are always checked.
422 If system style checking is enabled, includes using <angle brackets>
423 are also checked.
Brett Wilson796ed472018-07-16 15:11:09 -0700424
425 - Include paths are assumed to be relative to any of the "include_dirs" for
426 the target (including the implicit current dir).
427
428 - GN does not run the preprocessor so will not understand conditional
429 includes.
430
431 - Only includes matching known files in the build are checked: includes
432 matching unknown paths are ignored.
433
434 For an include to be valid:
435
436 - The included file must be in the current target, or there must be a path
437 following only public dependencies to a target with the file in it
438 ("gn path" is a good way to diagnose problems).
439
440 - There can be multiple targets with an included file: only one needs to be
441 valid for the include to be allowed.
442
443 - If there are only "sources" in a target, all are considered to be public
444 and can be included by other targets with a valid public dependency path.
445
446 - If a target lists files as "public", only those files are able to be
447 included by other targets. Anything in the sources will be considered
448 private and will not be includable regardless of dependency paths.
449
450 - Outputs from actions are treated like public sources on that target.
451
452 - A target can include headers from a target that depends on it if the
453 other target is annotated accordingly. See "gn help
454 allow_circular_includes_from".
455```
456
457#### **Advice on fixing problems**
458
459```
460 If you have a third party project that is difficult to fix or doesn't care
461 about include checks it's generally best to exclude that target from checking
462 altogether via "check_includes = false".
463
464 If you have conditional includes, make sure the build conditions and the
465 preprocessor conditions match, and annotate the line with "nogncheck" (see
466 "gn help nogncheck" for an example).
467
468 If two targets are hopelessly intertwined, use the
469 "allow_circular_includes_from" annotation. Ideally each should have identical
470 dependencies so configs inherited from those dependencies are consistent (see
471 "gn help allow_circular_includes_from").
472
473 If you have a standalone header file or files that need to be shared between
474 a few targets, you can consider making a source_set listing only those
475 headers as public sources. With only header files, the source set will be a
476 no-op from a build perspective, but will give a central place to refer to
477 those headers. That source set's files will still need to pass "gn check" in
478 isolation.
479
480 In rare cases it makes sense to list a header in more than one target if it
481 could be considered conceptually a member of both.
482```
483
484#### **Examples**
485
486```
487 gn check out/Debug
488 Check everything.
489
490 gn check out/Default //foo:bar
491 Check only the files in the //foo:bar target.
492
493 gn check out/Default "//foo/*
494 Check only the files in targets in the //foo directory tree.
495```
[email protected]449f3e42024-08-01 21:43:27 +0800496### <a name="cmd_clean"></a>**gn clean &lt;out_dir&gt;...**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700497
498```
499 Deletes the contents of the output directory except for args.gn and
500 creates a Ninja build environment sufficient to regenerate the build.
501```
[email protected]449f3e42024-08-01 21:43:27 +0800502### <a name="cmd_clean_stale"></a>**gn clean_stale [\--ninja-executable=...] &lt;out_dir&gt;...**&nbsp;[Back to Top](#gn-reference)
RJ Ascani4e260f12020-10-19 17:41:51 -0700503
504```
505 Removes the no longer needed output files from the build directory and prunes
506 their records from the ninja build log and dependency database. These are
507 output files that were generated from previous builds, but the current build
508 graph no longer references them.
509
510 This command requires a ninja executable of at least version 1.10.0. The
511 executable must be provided by the --ninja-executable switch.
512```
513
514#### **Options**
515
516```
517 --ninja-executable=<string>
518 Can be used to specify the ninja executable to use.
519```
[email protected]449f3e42024-08-01 21:43:27 +0800520### <a name="cmd_desc"></a>**gn desc**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700521
522```
Joe Armstrongb199e542019-03-21 09:40:08 +0800523 gn desc <out_dir> <label or pattern> [<what to show>] [--blame]
524 [--format=json]
525
Julie Hockette2a29402018-07-31 10:11:42 -0700526 Displays information about a given target or config. The build parameters
527 will be taken for the build in the given <out_dir>.
Brett Wilson796ed472018-07-16 15:11:09 -0700528
529 The <label or pattern> can be a target label, a config label, or a label
530 pattern (see "gn help label_pattern"). A label pattern will only match
531 targets.
532```
533
Nico Weber75eb3c72018-08-28 16:01:52 -0400534#### **Possibilities for &lt;what to show&gt;**
Brett Wilson796ed472018-07-16 15:11:09 -0700535
536```
537 (If unspecified an overall summary will be displayed.)
538
539 all_dependent_configs
540 allow_circular_includes_from
541 arflags [--blame]
542 args
543 cflags [--blame]
Julie Hockette2a29402018-07-31 10:11:42 -0700544 cflags_c [--blame]
Brett Wilson796ed472018-07-16 15:11:09 -0700545 cflags_cc [--blame]
Brett Wilson796ed472018-07-16 15:11:09 -0700546 check_includes
547 configs [--tree] (see below)
Nate Fischer8ed01d32019-01-08 17:32:01 -0800548 data_keys
Brett Wilson796ed472018-07-16 15:11:09 -0700549 defines [--blame]
550 depfile
551 deps [--all] [--tree] (see below)
Sylvain Defresnea09ec162020-01-16 12:36:40 +0100552 framework_dirs
553 frameworks
Brett Wilson796ed472018-07-16 15:11:09 -0700554 include_dirs [--blame]
555 inputs
556 ldflags [--blame]
557 lib_dirs
558 libs
Nate Fischer8ed01d32019-01-08 17:32:01 -0800559 metadata
560 output_conversion
Brett Wilson796ed472018-07-16 15:11:09 -0700561 outputs
562 public_configs
563 public
Nate Fischer8ed01d32019-01-08 17:32:01 -0800564 rebase
Brett Wilson796ed472018-07-16 15:11:09 -0700565 script
566 sources
567 testonly
568 visibility
Nate Fischer8ed01d32019-01-08 17:32:01 -0800569 walk_keys
Robert Sesekd0a6f072020-05-15 11:21:22 -0400570 weak_frameworks
Brett Wilson796ed472018-07-16 15:11:09 -0700571
572 runtime_deps
573 Compute all runtime deps for the given target. This is a computed list
574 and does not correspond to any GN variable, unlike most other values
575 here.
576
577 The output is a list of file names relative to the build directory. See
578 "gn help runtime_deps" for how this is computed. This also works with
579 "--blame" to see the source of the dependency.
580```
581
582#### **Shared flags**
Brett Wilson796ed472018-07-16 15:11:09 -0700583
Robert Sesekd0a6f072020-05-15 11:21:22 -0400584```
585 --default-toolchain
586 Normally wildcard targets are matched in all toolchains. This
587 switch makes wildcard labels with no explicit toolchain reference
588 only match targets in the default toolchain.
589
590 Non-wildcard inputs with no explicit toolchain specification will
591 always match only a target in the default toolchain if one exists.
Brett Wilson796ed472018-07-16 15:11:09 -0700592
593 --format=json
594 Format the output as JSON instead of text.
595```
596
597#### **Target flags**
598
599```
600 --blame
601 Used with any value specified on a config, this will name the config that
Sylvain Defresnea09ec162020-01-16 12:36:40 +0100602 causes that target to get the flag. This doesn't currently work for libs,
Robert Sesekd0a6f072020-05-15 11:21:22 -0400603 lib_dirs, frameworks, weak_frameworks and framework_dirs because those are
604 inherited and are more complicated to figure out the blame (patches
605 welcome).
Brett Wilson796ed472018-07-16 15:11:09 -0700606```
607
608#### **Configs**
609
610```
611 The "configs" section will list all configs that apply. For targets this will
612 include configs specified in the "configs" variable of the target, and also
613 configs pushed onto this target via public or "all dependent" configs.
614
615 Configs can have child configs. Specifying --tree will show the hierarchy.
616```
617
618#### **Printing outputs**
619
620```
621 The "outputs" section will list all outputs that apply, including the outputs
622 computed from the tool definition (eg for "executable", "static_library", ...
623 targets).
624```
625
626#### **Printing deps**
627
628```
629 Deps will include all public, private, and data deps (TODO this could be
630 clarified and enhanced) sorted in order applying. The following may be used:
631
632 --all
633 Collects all recursive dependencies and prints a sorted flat list. Also
634 usable with --tree (see below).
Robert Sesekd0a6f072020-05-15 11:21:22 -0400635
Brett Wilson796ed472018-07-16 15:11:09 -0700636 --as=(buildfile|label|output)
637 How to print targets.
638
639 buildfile
640 Prints the build files where the given target was declared as
641 file names.
642 label (default)
643 Prints the label of the target.
644 output
645 Prints the first output file for the target relative to the
646 root build directory.
647
648 --testonly=(true|false)
649 Restrict outputs to targets with the testonly flag set
650 accordingly. When unspecified, the target's testonly flags are
651 ignored.
652
653 --tree
654 Print a dependency tree. By default, duplicates will be elided with "..."
655 but when --all and -tree are used together, no eliding will be performed.
656
657 The "deps", "public_deps", and "data_deps" will all be included in the
658 tree.
659
660 Tree output can not be used with the filtering or output flags: --as,
661 --type, --testonly.
Robert Sesekd0a6f072020-05-15 11:21:22 -0400662
Brett Wilson796ed472018-07-16 15:11:09 -0700663 --type=(action|copy|executable|group|loadable_module|shared_library|
664 source_set|static_library)
665 Restrict outputs to targets matching the given type. If
666 unspecified, no filtering will be performed.
667```
668
669#### **Note**
670
671```
672 This command will show the full name of directories and source files, but
673 when directories and source paths are written to the build file, they will be
674 adjusted to be relative to the build directory. So the values for paths
675 displayed by this command won't match (but should mean the same thing).
676```
677
678#### **Examples**
679
680```
681 gn desc out/Debug //base:base
682 Summarizes the given target.
683
684 gn desc out/Foo :base_unittests deps --tree
685 Shows a dependency tree of the "base_unittests" project in
686 the current directory.
687
688 gn desc out/Debug //base defines --blame
689 Shows defines set for the //base:base target, annotated by where
690 each one was set from.
691```
[email protected]449f3e42024-08-01 21:43:27 +0800692### <a name="cmd_format"></a>**gn format [\--dump-tree] (\--stdin | &lt;list of build_files...&gt;)**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700693
694```
695 Formats .gn file to a standard format.
696
697 The contents of some lists ('sources', 'deps', etc.) will be sorted to a
698 canonical order. To suppress this, you can add a comment of the form "#
699 NOSORT" immediately preceding the assignment. e.g.
700
701 # NOSORT
702 sources = [
703 "z.cc",
704 "a.cc",
705 ]
706```
707
708#### **Arguments**
709
710```
711 --dry-run
Nico Weberad9eab22020-11-15 22:20:28 -0500712 Prints the list of files that would be reformatted but does not write
713 anything to disk. This is useful for presubmit/lint-type checks.
Brett Wilson796ed472018-07-16 15:11:09 -0700714 - Exit code 0: successful format, matches on disk.
715 - Exit code 1: general failure (parse error, etc.)
716 - Exit code 2: successful format, but differs from on disk.
717
Julie Hockettd69a9c32019-01-23 14:36:18 -0800718 --dump-tree[=( text | json )]
719 Dumps the parse tree to stdout and does not update the file or print
720 formatted output. If no format is specified, text format will be used.
Brett Wilson796ed472018-07-16 15:11:09 -0700721
722 --stdin
723 Read input from stdin and write to stdout rather than update a file
724 in-place.
RJ Ascani4e260f12020-10-19 17:41:51 -0700725
726 --read-tree=json
727 Reads an AST from stdin in the format output by --dump-tree=json and
728 uses that as the parse tree. (The only read-tree format currently
729 supported is json.) The given .gn file will be overwritten. This can be
730 used to programmatically transform .gn files.
Brett Wilson796ed472018-07-16 15:11:09 -0700731```
732
733#### **Examples**
734```
Julie Hockettd69a9c32019-01-23 14:36:18 -0800735 gn format //some/BUILD.gn //some/other/BUILD.gn //and/another/BUILD.gn
Brett Wilson796ed472018-07-16 15:11:09 -0700736 gn format some\\BUILD.gn
737 gn format /abspath/some/BUILD.gn
738 gn format --stdin
RJ Ascani4e260f12020-10-19 17:41:51 -0700739 gn format --read-tree=json //rewritten/BUILD.gn
Brett Wilson796ed472018-07-16 15:11:09 -0700740```
[email protected]449f3e42024-08-01 21:43:27 +0800741### <a name="cmd_gen"></a>**gn gen [\--check] [&lt;ide options&gt;] &lt;out_dir&gt;**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700742
743```
744 Generates ninja files from the current tree and puts them in the given output
745 directory.
746
747 The output directory can be a source-repo-absolute path name such as:
748 //out/foo
749 Or it can be a directory relative to the current directory such as:
750 out/foo
751
James Robinson49f59032020-01-08 14:05:51 -0800752 "gn gen --check" is the same as running "gn check". "gn gen --check=system" is
753 the same as running "gn check --check-system". See "gn help check" for
754 documentation on that mode.
Brett Wilson796ed472018-07-16 15:11:09 -0700755
756 See "gn help switches" for the common command-line switches.
757```
758
RJ Ascani6966efb2020-10-19 16:50:11 -0700759#### **General options**
760
761```
762 --ninja-executable=<string>
763 Can be used to specify the ninja executable to use. This executable will
764 be used as an IDE option to indicate which ninja to use for building. This
765 executable will also be used as part of the gen process for triggering a
RJ Ascani4e260f12020-10-19 17:41:51 -0700766 restat on generated ninja files and for use with --clean-stale.
767
768 --clean-stale
769 This option will cause no longer needed output files to be removed from
770 the build directory, and their records pruned from the ninja build log and
771 dependency database after the ninja build graph has been generated. This
772 option requires a ninja executable of at least version 1.10.0. It can be
773 provided by the --ninja-executable switch. Also see "gn help clean_stale".
RJ Ascani6966efb2020-10-19 16:50:11 -0700774```
775
Brett Wilson796ed472018-07-16 15:11:09 -0700776#### **IDE options**
777
778```
Harley Li0a9affb2020-06-03 10:38:42 -0400779 GN optionally generates files for IDE. Files won't be overwritten if their
780 contents don't change. Possibilities for <ide options>
Brett Wilson796ed472018-07-16 15:11:09 -0700781
782 --ide=<ide_name>
783 Generate files for an IDE. Currently supported values:
784 "eclipse" - Eclipse CDT settings file.
785 "vs" - Visual Studio project/solution files.
Chunbo Hua4a8016d2025-02-20 10:31:32 +0800786 (default Visual Studio version: 2022)
Brett Wilson796ed472018-07-16 15:11:09 -0700787 "vs2013" - Visual Studio 2013 project/solution files.
788 "vs2015" - Visual Studio 2015 project/solution files.
789 "vs2017" - Visual Studio 2017 project/solution files.
Sylvain Defresned46f92f2019-04-03 16:14:29 +0200790 "vs2019" - Visual Studio 2019 project/solution files.
Tyler Mandry4a648092022-02-15 19:47:09 +0000791 "vs2022" - Visual Studio 2022 project/solution files.
Brett Wilson796ed472018-07-16 15:11:09 -0700792 "xcode" - Xcode workspace/solution files.
793 "qtcreator" - QtCreator project files.
794 "json" - JSON file containing target information
795
796 --filters=<path_prefixes>
797 Semicolon-separated list of label patterns used to limit the set of
798 generated projects (see "gn help label_pattern"). Only matching targets
799 and their dependencies will be included in the solution. Only used for
800 Visual Studio, Xcode and JSON.
801```
802
803#### **Visual Studio Flags**
804
805```
806 --sln=<file_name>
807 Override default sln file name ("all"). Solution file is written to the
808 root build directory.
809
810 --no-deps
811 Don't include targets dependencies to the solution. Changes the way how
812 --filters option works. Only directly matching targets are included.
813
814 --winsdk=<sdk_version>
815 Use the specified Windows 10 SDK version to generate project files.
816 As an example, "10.0.15063.0" can be specified to use Creators Update SDK
817 instead of the default one.
818
Shezan Baigc0a2d232021-07-01 00:29:49 -0400819 --ninja-executable=<string>
820 Can be used to specify the ninja executable to use when building.
821
Brett Wilson796ed472018-07-16 15:11:09 -0700822 --ninja-extra-args=<string>
823 This string is passed without any quoting to the ninja invocation
824 command-line. Can be used to configure ninja flags, like "-j".
825```
826
827#### **Xcode Flags**
828
829```
Sylvain Defresnedb55efd2020-06-16 12:23:03 +0200830 --xcode-project=<file_name>
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +0100831 Override default Xcode project file name ("all"). The project file is
Brett Wilson796ed472018-07-16 15:11:09 -0700832 written to the root build directory.
833
Sylvain Defresne7b0690e2020-06-26 15:33:01 +0200834 --xcode-build-system=<value>
835 Configure the build system to use for the Xcode project. Supported
836 values are (default to "legacy"):
837 "legacy" - Legacy Build system
838 "new" - New Build System
839
Sylvain Defresne88830702022-06-20 17:11:49 +0200840 --xcode-configs=<config_name_list>
841 Configure the list of build configuration supported by the generated
842 project. If specified, must be a list of semicolon-separated strings.
Ricardo Ribalda85bd0a62023-11-11 16:30:19 +0000843 If omitted, a single configuration will be used in the generated
Sylvain Defresne88830702022-06-20 17:11:49 +0200844 project derived from the build directory.
845
846 --xcode-config-build-dir=<string>
847 If present, must be a path relative to the source directory. It will
Ricardo Ribalda85bd0a62023-11-11 16:30:19 +0000848 default to $root_out_dir if omitted. The path is assumed to point to
Sylvain Defresne88830702022-06-20 17:11:49 +0200849 the directory where ninja needs to be invoked. This variable can be
850 used to build for multiple configuration / platform / environment from
851 the same generated Xcode project (assuming that the user has created a
852 gn build directory with the correct args.gn for each).
853
854 One useful value is to use Xcode variables such as '${CONFIGURATION}'
855 or '${EFFECTIVE_PLATFORM}'.
856
Sylvain Defresneae474cc2022-06-21 14:44:02 +0200857 --xcode-additional-files-patterns=<pattern_list>
858 If present, must be a list of semicolon-separated file patterns. It
859 will be used to add all files matching the pattern located in the
860 source tree to the project. It can be used to add, e.g. documentation
861 files to the project to allow easily edit them.
862
863 --xcode-additional-files-roots=<path_list>
864 If present, must be a list of semicolon-separated paths. It will be used
Ricardo Ribalda85bd0a62023-11-11 16:30:19 +0000865 as roots when looking for additional files to add. If omitted, defaults
Sylvain Defresneae474cc2022-06-21 14:44:02 +0200866 to "//".
867
Sylvain Defresneaff489a2020-03-11 18:27:43 +0100868 --ninja-executable=<string>
869 Can be used to specify the ninja executable to use when building.
870
Brett Wilson796ed472018-07-16 15:11:09 -0700871 --ninja-extra-args=<string>
872 This string is passed without any quoting to the ninja invocation
873 command-line. Can be used to configure ninja flags, like "-j".
874
Sylvain Defresnee431b2f2020-11-04 10:49:47 +0100875 --ide-root-target=<target_name>
Brett Wilson796ed472018-07-16 15:11:09 -0700876 Name of the target corresponding to "All" target in Xcode. If unset,
877 "All" invokes ninja without any target and builds everything.
878```
879
880#### **QtCreator Flags**
881
882```
Sylvain Defresnee431b2f2020-11-04 10:49:47 +0100883 --ide-root-target=<target_name>
Brett Wilson796ed472018-07-16 15:11:09 -0700884 Name of the root target for which the QtCreator project will be generated
885 to contain files of it and its dependencies. If unset, the whole build
886 graph will be emitted.
887```
888
889#### **Eclipse IDE Support**
890
891```
892 GN DOES NOT generate Eclipse CDT projects. Instead, it generates a settings
893 file which can be imported into an Eclipse CDT project. The XML file contains
894 a list of include paths and defines. Because GN does not generate a full
895 .cproject definition, it is not possible to properly define includes/defines
896 for each file individually. Instead, one set of includes/defines is generated
897 for the entire project. This works fairly well but may still result in a few
898 indexer issues here and there.
899```
900
901#### **Generic JSON Output**
902
903```
904 Dumps target information to a JSON file and optionally invokes a
905 python script on the generated file. See the comments at the beginning
906 of json_project_writer.cc and desc_builder.cc for an overview of the JSON
907 file format.
908
909 --json-file-name=<json_file_name>
910 Overrides default file name (project.json) of generated JSON file.
911
912 --json-ide-script=<path_to_python_script>
Harley Li0a9affb2020-06-03 10:38:42 -0400913 Executes python script after the JSON file is generated or updated with
914 new content. Path can be project absolute (//), system absolute (/) or
915 relative, in which case the output directory will be base. Path to
916 generated JSON file will be first argument when invoking script.
Brett Wilson796ed472018-07-16 15:11:09 -0700917
918 --json-ide-script-args=<argument>
David 'Digit' Turner6253a392024-02-20 19:55:35 +0100919 Optional second argument that will be passed to executed script.
nespie1cad8f672025-04-20 17:44:49 +0300920
921 --filter-with-data
922 Additionally follows data deps when filtering. Without this flag, only
923 public and private linked deps will be followed. Only used with --filters.
David 'Digit' Turner6253a392024-02-20 19:55:35 +0100924```
925
926#### **Ninja Outputs**
927
928```
929 The --ninja-outputs-file=<FILE> option dumps a JSON file that maps GN labels
930 to their Ninja output paths. This can be later processed to build an index
931 to convert between Ninja targets and GN ones before or after the build itself.
932 It looks like:
933
934 {
935 "label1": [
936 "path1",
937 "path2"
938 ],
939 "label2": [
940 "path3"
941 ]
942 }
943
944 --ninja-outputs-script=<path_to_python_script>
945 Executes python script after the outputs file is generated or updated
946 with new content. Path can be project absolute (//), system absolute (/) or
947 relative, in which case the output directory will be base. Path to
948 generated file will be first argument when invoking script.
949
950 --ninja-outputs-script-args=<argument>
951 Optional second argument that will be passed to executed script.
Brett Wilson796ed472018-07-16 15:11:09 -0700952```
Julie Hockett11e09912018-07-31 13:15:08 -0700953
954#### **Compilation Database**
955
956```
Robert Sesekd0a6f072020-05-15 11:21:22 -0400957 --export-rust-project
958 Produces a rust-project.json file in the root of the build directory
959 This is used for various tools in the Rust ecosystem allowing for the
960 replay of individual compilations independent of the build system.
961 This is an unstable format and likely to change without warning.
962
Brett Wilson1da84bb2022-09-14 15:35:29 -0700963 --add-export-compile-commands=<label_pattern>
964 Adds an additional label pattern (see "gn help label_pattern") of a
965 target to add to the compilation database. This pattern is appended to any
966 list values specified in the export_compile_commands variable in the
967 .gn file (see "gn help dotfile"). This allows the user to add additional
968 targets to the compilation database that the project doesn't add by default.
969
970 To add more than one value, specify this switch more than once. Each
971 invocation adds an additional label pattern.
972
973 Example:
974 --add-export-compile-commands=//tools:my_tool
975 --add-export-compile-commands="//base/*"
976
Robert Sesek252674d2019-05-10 14:08:52 -0400977 --export-compile-commands[=<target_name1,target_name2...>]
Brett Wilson1da84bb2022-09-14 15:35:29 -0700978 DEPRECATED https://bugs.chromium.org/p/gn/issues/detail?id=302.
979 Please use --add-export-compile-commands for per-user configuration, and
980 the "export_compile_commands" value in the project-level .gn file (see
981 "gn help dotfile") for per-project configuration.
982
983 Overrides the value of the export_compile_commands in the .gn file (see
984 "gn help dotfile") as well as the --add-export-compile-commands switch.
985
986 Unlike the .gn setting, this switch takes a legacy format which is a list
987 of target names that are matched in any directory. For example, "foo" will
988 match:
989 - "//path/to/src:foo"
990 - "//other/path:foo"
991 - "//foo:foo"
Aaron Wood2d9fd622020-12-10 21:28:19 -0800992 and not match:
Brett Wilson1da84bb2022-09-14 15:35:29 -0700993 - "//foo:bar"
Julie Hockett11e09912018-07-31 13:15:08 -0700994```
[email protected]449f3e42024-08-01 21:43:27 +0800995### <a name="cmd_help"></a>**gn help &lt;anything&gt;**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700996
997```
998 Yo dawg, I heard you like help on your help so I put help on the help in the
999 help.
1000
1001 You can also use "all" as the parameter to get all help at once.
1002```
1003
1004#### **Switches**
1005
1006```
1007 --markdown
1008 Format output in markdown syntax.
1009```
1010
1011#### **Example**
1012
1013```
1014 gn help --markdown all
1015 Dump all help to stdout in markdown format.
1016```
[email protected]449f3e42024-08-01 21:43:27 +08001017### <a name="cmd_ls"></a>**gn ls &lt;out_dir&gt; [&lt;label_pattern&gt;] [\--default-toolchain] [\--as=...]**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001018```
1019 [--type=...] [--testonly=...]
1020
1021 Lists all targets matching the given pattern for the given build directory.
1022 By default, only targets in the default toolchain will be matched unless a
1023 toolchain is explicitly supplied.
1024
1025 If the label pattern is unspecified, list all targets. The label pattern is
1026 not a general regular expression (see "gn help label_pattern"). If you need
1027 more complex expressions, pipe the result through grep.
1028```
1029
1030#### **Options**
1031
1032```
1033 --as=(buildfile|label|output)
1034 How to print targets.
1035
1036 buildfile
1037 Prints the build files where the given target was declared as
1038 file names.
1039 label (default)
1040 Prints the label of the target.
1041 output
1042 Prints the first output file for the target relative to the
1043 root build directory.
1044
Robert Sesekd0a6f072020-05-15 11:21:22 -04001045 --default-toolchain
1046 Normally wildcard targets are matched in all toolchains. This
1047 switch makes wildcard labels with no explicit toolchain reference
1048 only match targets in the default toolchain.
Brett Wilson796ed472018-07-16 15:11:09 -07001049
Robert Sesekd0a6f072020-05-15 11:21:22 -04001050 Non-wildcard inputs with no explicit toolchain specification will
1051 always match only a target in the default toolchain if one exists.
Brett Wilson796ed472018-07-16 15:11:09 -07001052
1053 --testonly=(true|false)
1054 Restrict outputs to targets with the testonly flag set
1055 accordingly. When unspecified, the target's testonly flags are
1056 ignored.
1057
1058 --type=(action|copy|executable|group|loadable_module|shared_library|
1059 source_set|static_library)
1060 Restrict outputs to targets matching the given type. If
1061 unspecified, no filtering will be performed.
1062```
1063
1064#### **Examples**
1065
1066```
1067 gn ls out/Debug
1068 Lists all targets in the default toolchain.
1069
1070 gn ls out/Debug "//base/*"
1071 Lists all targets in the directory base and all subdirectories.
1072
1073 gn ls out/Debug "//base:*"
1074 Lists all targets defined in //base/BUILD.gn.
1075
1076 gn ls out/Debug //base --as=output
1077 Lists the build output file for //base:base
1078
1079 gn ls out/Debug --type=executable
1080 Lists all executables produced by the build.
1081
1082 gn ls out/Debug "//base/*" --as=output | xargs ninja -C out/Debug
1083 Builds all targets in //base and all subdirectories.
Brett Wilson796ed472018-07-16 15:11:09 -07001084```
[email protected]449f3e42024-08-01 21:43:27 +08001085### <a name="cmd_meta"></a>**gn meta**&nbsp;[Back to Top](#gn-reference)
Joe Armstrongb199e542019-03-21 09:40:08 +08001086
Nate Fischer8ed01d32019-01-08 17:32:01 -08001087```
Joe Armstrongb199e542019-03-21 09:40:08 +08001088 gn meta <out_dir> <target>* --data=<key>[,<key>*]* [--walk=<key>[,<key>*]*]
1089 [--rebase=<dest dir>]
Nate Fischer8ed01d32019-01-08 17:32:01 -08001090
1091 Lists collected metaresults of all given targets for the given data key(s),
1092 collecting metadata dependencies as specified by the given walk key(s).
1093
1094 See `gn help generated_file` for more information on the walk.
1095```
1096
1097#### **Arguments**
1098
1099```
1100 <target(s)>
1101 A list of target labels from which to initiate the walk.
1102
1103 --data
Tyler Mandry4a648092022-02-15 19:47:09 +00001104 A comma-separated list of keys from which to extract data. In each target
1105 walked, its metadata scope is checked for the presence of these keys. If
1106 present, the contents of those variable in the scope are appended to the
1107 results list.
Nate Fischer8ed01d32019-01-08 17:32:01 -08001108
1109 --walk (optional)
Tyler Mandry4a648092022-02-15 19:47:09 +00001110 A comma-separated list of keys from which to control the walk. In each
1111 target walked, its metadata scope is checked for the presence of any of
1112 these keys. If present, the contents of those variables is checked to ensure
1113 that it is a label of a valid dependency of the target and then added to the
1114 set of targets to walk. If the empty string ("") is present in any of these
1115 keys, all deps and data_deps are added to the walk set.
Nate Fischer8ed01d32019-01-08 17:32:01 -08001116
1117 --rebase (optional)
1118 A destination directory onto which to rebase any paths found. If set, all
1119 collected metadata will be rebased onto this path. This option will throw errors
1120 if collected metadata is not a list of strings.
1121```
1122
1123#### **Examples**
1124
1125```
1126 gn meta out/Debug "//base/foo" --data=files
1127 Lists collected metaresults for the `files` key in the //base/foo:foo
1128 target and all of its dependency tree.
1129
Tyler Mandry4a648092022-02-15 19:47:09 +00001130 gn meta out/Debug "//base/foo" --data=files,other
Nate Fischer8ed01d32019-01-08 17:32:01 -08001131 Lists collected metaresults for the `files` and `other` keys in the
1132 //base/foo:foo target and all of its dependency tree.
1133
1134 gn meta out/Debug "//base/foo" --data=files --walk=stop
1135 Lists collected metaresults for the `files` key in the //base/foo:foo
1136 target and all of the dependencies listed in the `stop` key (and so on).
1137
1138 gn meta out/Debug "//base/foo" --data=files --rebase="/"
1139 Lists collected metaresults for the `files` key in the //base/foo:foo
1140 target and all of its dependency tree, rebasing the strings in the `files`
1141 key onto the source directory of the target's declaration relative to "/".
1142```
[email protected]449f3e42024-08-01 21:43:27 +08001143### <a name="cmd_outputs"></a>**gn outputs &lt;out_dir&gt; &lt;list of target or file names...&gt;**&nbsp;[Back to Top](#gn-reference)
Brett Wilson74397092020-03-18 16:34:14 -07001144
1145```
1146 Lists the output files corresponding to the given target(s) or file name(s).
1147 There can be multiple outputs because there can be more than one output
1148 generated by a build step, and there can be more than one toolchain matched.
1149 You can also list multiple inputs which will generate a union of all the
1150 outputs from those inputs.
1151
1152 - The input target/file names are relative to the current directory.
1153
1154 - The output file names are relative to the root build directory.
1155
1156 This command is useful for finding a ninja command that will build only a
1157 portion of the build.
1158```
1159
1160#### **Target outputs**
1161
1162```
1163 If the parameter is a target name that includes a toolchain, it will match
1164 only that target in that toolchain. If no toolchain is specified, it will
1165 match all targets with that name in any toolchain.
1166
1167 The result will be the outputs specified by that target which could be a
1168 library, executable, output of an action, a stamp file, etc.
1169```
1170
1171#### **File outputs**
1172
1173```
1174 If the parameter is a file name it will compute the output for that compile
1175 step for all targets in all toolchains that contain that file as a source
1176 file.
1177
1178 If the source is not compiled (e.g. a header or text file), the command will
1179 produce no output.
1180
1181 If the source is listed as an "input" to a binary target or action will
1182 resolve to that target's outputs.
1183```
1184
1185#### **Example**
1186
1187```
1188 gn outputs out/debug some/directory:some_target
1189 Find the outputs of a given target.
1190
1191 gn outputs out/debug src/project/my_file.cc | xargs ninja -C out/debug
1192 Compiles just the given source file in all toolchains it's referenced in.
1193
1194 git diff --name-only | xargs gn outputs out/x64 | xargs ninja -C out/x64
1195 Compiles all files changed in git.
1196```
[email protected]449f3e42024-08-01 21:43:27 +08001197### <a name="cmd_path"></a>**gn path &lt;out_dir&gt; &lt;target_one&gt; &lt;target_two&gt;**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001198
1199```
1200 Finds paths of dependencies between two targets. Each unique path will be
1201 printed in one group, and groups will be separate by newlines. The two
1202 targets can appear in either order (paths will be found going in either
1203 direction).
1204
1205 By default, a single path will be printed. If there is a path with only
1206 public dependencies, the shortest public path will be printed. Otherwise, the
1207 shortest path using either public or private dependencies will be printed. If
1208 --with-data is specified, data deps will also be considered. If there are
1209 multiple shortest paths, an arbitrary one will be selected.
1210```
1211
1212#### **Interesting paths**
1213
1214```
1215 In a large project, there can be 100's of millions of unique paths between a
1216 very high level and a common low-level target. To make the output more useful
1217 (and terminate in a reasonable time), GN will not revisit sub-paths
1218 previously known to lead to the target.
1219```
1220
1221#### **Options**
1222
1223```
1224 --all
1225 Prints all "interesting" paths found rather than just the first one.
1226 Public paths will be printed first in order of increasing length, followed
1227 by non-public paths in order of increasing length.
1228
1229 --public
1230 Considers only public paths. Can't be used with --with-data.
1231
1232 --with-data
1233 Additionally follows data deps. Without this flag, only public and private
1234 linked deps will be followed. Can't be used with --public.
1235```
1236
1237#### **Example**
1238
1239```
Keir Mierle45611e32019-11-12 11:18:00 -08001240 gn path out/Default //base //gn
Brett Wilson796ed472018-07-16 15:11:09 -07001241```
[email protected]449f3e42024-08-01 21:43:27 +08001242### <a name="cmd_refs"></a>**gn refs**&nbsp;[Back to Top](#gn-reference)
Joe Armstrongb199e542019-03-21 09:40:08 +08001243
Brett Wilson796ed472018-07-16 15:11:09 -07001244```
Nico Weberad9eab22020-11-15 22:20:28 -05001245 gn refs <out_dir> (<label_pattern>|<label>|<file>|@<response_file>)* [--all]
1246 [--default-toolchain] [--as=...] [--testonly=...] [--type=...]
Brett Wilson796ed472018-07-16 15:11:09 -07001247
1248 Finds reverse dependencies (which targets reference something). The input is
1249 a list containing:
1250
1251 - Target label: The result will be which targets depend on it.
1252
1253 - Config label: The result will be which targets list the given config in
1254 its "configs" or "public_configs" list.
1255
1256 - Label pattern: The result will be which targets depend on any target
1257 matching the given pattern. Patterns will not match configs. These are not
1258 general regular expressions, see "gn help label_pattern" for details.
1259
1260 - File name: The result will be which targets list the given file in its
1261 "inputs", "sources", "public", "data", or "outputs". Any input that does
1262 not contain wildcards and does not match a target or a config will be
1263 treated as a file.
1264
1265 - Response file: If the input starts with an "@", it will be interpreted as
1266 a path to a file containing a list of labels or file names, one per line.
1267 This allows us to handle long lists of inputs without worrying about
1268 command line limits.
1269```
1270
1271#### **Options**
1272
1273```
1274 --all
1275 When used without --tree, will recurse and display all unique
1276 dependencies of the given targets. For example, if the input is a target,
1277 this will output all targets that depend directly or indirectly on the
1278 input. If the input is a file, this will output all targets that depend
1279 directly or indirectly on that file.
1280
1281 When used with --tree, turns off eliding to show a complete tree.
Brett Wilson796ed472018-07-16 15:11:09 -07001282
1283 --as=(buildfile|label|output)
1284 How to print targets.
1285
1286 buildfile
1287 Prints the build files where the given target was declared as
1288 file names.
1289 label (default)
1290 Prints the label of the target.
1291 output
1292 Prints the first output file for the target relative to the
1293 root build directory.
1294
Robert Sesekd0a6f072020-05-15 11:21:22 -04001295 --default-toolchain
1296 Normally wildcard targets are matched in all toolchains. This
1297 switch makes wildcard labels with no explicit toolchain reference
1298 only match targets in the default toolchain.
1299
1300 Non-wildcard inputs with no explicit toolchain specification will
1301 always match only a target in the default toolchain if one exists.
1302
Brett Wilson796ed472018-07-16 15:11:09 -07001303 -q
1304 Quiet. If nothing matches, don't print any output. Without this option, if
1305 there are no matches there will be an informational message printed which
1306 might interfere with scripts processing the output.
Robert Sesekd0a6f072020-05-15 11:21:22 -04001307
Brett Wilson796ed472018-07-16 15:11:09 -07001308 --testonly=(true|false)
1309 Restrict outputs to targets with the testonly flag set
1310 accordingly. When unspecified, the target's testonly flags are
1311 ignored.
1312
1313 --tree
1314 Outputs a reverse dependency tree from the given target. Duplicates will
1315 be elided. Combine with --all to see a full dependency tree.
1316
1317 Tree output can not be used with the filtering or output flags: --as,
1318 --type, --testonly.
Robert Sesekd0a6f072020-05-15 11:21:22 -04001319
Brett Wilson796ed472018-07-16 15:11:09 -07001320 --type=(action|copy|executable|group|loadable_module|shared_library|
1321 source_set|static_library)
1322 Restrict outputs to targets matching the given type. If
1323 unspecified, no filtering will be performed.
1324```
1325
1326#### **Examples (target input)**
1327
1328```
Keir Mierle45611e32019-11-12 11:18:00 -08001329 gn refs out/Debug //gn:gn
Brett Wilson796ed472018-07-16 15:11:09 -07001330 Find all targets depending on the given exact target name.
1331
Lei Zhang415b3b12024-04-02 09:29:36 -07001332 gn refs out/Debug //base:i18n --as=buildfile | xargs gvim
Brett Wilson796ed472018-07-16 15:11:09 -07001333 Edit all .gn files containing references to //base:i18n
1334
1335 gn refs out/Debug //base --all
1336 List all targets depending directly or indirectly on //base:base.
1337
1338 gn refs out/Debug "//base/*"
1339 List all targets depending directly on any target in //base or
1340 its subdirectories.
1341
1342 gn refs out/Debug "//base:*"
1343 List all targets depending directly on any target in
1344 //base/BUILD.gn.
1345
1346 gn refs out/Debug //base --tree
1347 Print a reverse dependency tree of //base:base
1348```
1349
1350#### **Examples (file input)**
1351
1352```
1353 gn refs out/Debug //base/macros.h
1354 Print target(s) listing //base/macros.h as a source.
1355
1356 gn refs out/Debug //base/macros.h --tree
1357 Display a reverse dependency tree to get to the given file. This
1358 will show how dependencies will reference that file.
1359
1360 gn refs out/Debug //base/macros.h //base/at_exit.h --all
1361 Display all unique targets with some dependency path to a target
1362 containing either of the given files as a source.
1363
1364 gn refs out/Debug //base/macros.h --testonly=true --type=executable
1365 --all --as=output
1366 Display the executable file names of all test executables
1367 potentially affected by a change to the given file.
1368```
1369## <a name="targets"></a>Target declarations
1370
[email protected]449f3e42024-08-01 21:43:27 +08001371### <a name="func_action"></a>**action**: Declare a target that runs a script a single time.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001372
1373```
1374 This target type allows you to run a script a single time to produce one or
1375 more output files. If you want to run a script once for each of a set of
1376 input files, see "gn help action_foreach".
1377```
1378
1379#### **Inputs**
1380
1381```
1382 In an action the "sources" and "inputs" are treated the same: they're both
1383 input dependencies on script execution with no special handling. If you want
1384 to pass the sources to your script, you must do so explicitly by including
1385 them in the "args". Note also that this means there is no special handling of
1386 paths since GN doesn't know which of the args are paths and not. You will
1387 want to use rebase_path() to convert paths to be relative to the
1388 root_build_dir.
1389
1390 You can dynamically write input dependencies (for incremental rebuilds if an
1391 input file changes) by writing a depfile when the script is run (see "gn help
1392 depfile"). This is more flexible than "inputs".
1393
1394 If the command line length is very long, you can use response files to pass
1395 args to your script. See "gn help response_file_contents".
1396
1397 It is recommended you put inputs to your script in the "sources" variable,
1398 and stuff like other Python files required to run your script in the "inputs"
1399 variable.
Julie Hockette2a29402018-07-31 10:11:42 -07001400
Adrian Taylorc0d4f8b2022-03-25 15:05:57 -07001401 Actions can take the configs and public_configs lists, as well as any of the
1402 configs variables (defines, include_dirs, etc.) set directly on the target.
1403 These behave exactly as they would on a binary target and can be accessed
1404 using substitution patterns in the script args (see "gn help args") to
1405 implement custom compiler-like tools.
1406
Brett Wilson796ed472018-07-16 15:11:09 -07001407 The "deps" and "public_deps" for an action will always be
1408 completed before any part of the action is run so it can depend on
1409 the output of previous steps. The "data_deps" will be built if the
1410 action is built, but may not have completed before all steps of the
1411 action are started. This can give additional parallelism in the build
1412 for runtime-only dependencies.
1413```
1414
1415#### **Outputs**
1416
1417```
1418 You should specify files created by your script by specifying them in the
1419 "outputs".
Julie Hockette2a29402018-07-31 10:11:42 -07001420
Brett Wilson796ed472018-07-16 15:11:09 -07001421 The script will be executed with the given arguments with the current
1422 directory being that of the root build directory. If you pass files
1423 to your script, see "gn help rebase_path" for how to convert
1424 file names to be relative to the build directory (file names in the
1425 sources, outputs, and inputs will be all treated as relative to the
1426 current build file and converted as needed automatically).
Brett Wilson1e1ea9d2020-02-04 15:34:05 -08001427
1428 GN sets Ninja's flag 'restat = 1` for all action commands. This means
1429 that Ninja will check the timestamp of the output after the action
1430 completes. If output timestamp is unchanged, the step will be treated
1431 as if it never needed to be rebuilt, potentially eliminating some
1432 downstream steps for incremental builds. Scripts can improve build
1433 performance by taking care not to change the timstamp of the output
1434 file(s) if the contents have not changed.
Brett Wilson796ed472018-07-16 15:11:09 -07001435```
1436
1437#### **File name handling**
Julie Hockette2a29402018-07-31 10:11:42 -07001438
Brett Wilson796ed472018-07-16 15:11:09 -07001439```
1440 All output files must be inside the output directory of the build.
1441 You would generally use |$target_out_dir| or |$target_gen_dir| to
1442 reference the output or generated intermediate file directories,
1443 respectively.
1444```
1445
1446#### **Variables**
1447
1448```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001449 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
1450 cflags_objcc, defines, include_dirs, inputs, ldflags,
1451 lib_dirs, libs, precompiled_header, precompiled_source,
1452 rustenv, rustflags, swiftflags, testonly
1453 Dependent configs: all_dependent_configs, public_configs
1454 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
1455 write_runtime_deps
1456 General: check_includes, configs, data, friend, inputs, metadata,
1457 output_extension, output_name, public, sources, testonly,
1458 visibility
1459 Action variables: args, bridge_header, configs, data, depfile,
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07001460 framework_dirs, inputs, mnemonic, module_deps,
1461 module_name, outputs*, pool, response_file_contents,
1462 script*, sources
Brett Wilson796ed472018-07-16 15:11:09 -07001463 * = required
1464```
1465
1466#### **Example**
1467
1468```
1469 action("run_this_guy_once") {
1470 script = "doprocessing.py"
1471 sources = [ "my_configuration.txt" ]
1472 outputs = [ "$target_gen_dir/insightful_output.txt" ]
1473
1474 # Our script imports this Python file so we want to rebuild if it changes.
1475 inputs = [ "helper_library.py" ]
1476
1477 # Note that we have to manually pass the sources to our script if the
1478 # script needs them as inputs.
1479 args = [ "--out", rebase_path(target_gen_dir, root_build_dir) ] +
1480 rebase_path(sources, root_build_dir)
1481 }
1482```
[email protected]449f3e42024-08-01 21:43:27 +08001483### <a name="func_action_foreach"></a>**action_foreach**: Declare a target that runs a script over a set of files.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001484
1485```
1486 This target type allows you to run a script once-per-file over a set of
1487 sources. If you want to run a script once that takes many files as input, see
1488 "gn help action".
1489```
1490
1491#### **Inputs**
1492
1493```
1494 The script will be run once per file in the "sources" variable. The "outputs"
1495 variable should specify one or more files with a source expansion pattern in
1496 it (see "gn help source_expansion"). The output file(s) for each script
1497 invocation should be unique. Normally you use "{{source_name_part}}" in each
1498 output file.
1499
1500 If your script takes additional data as input, such as a shared configuration
1501 file or a Python module it uses, those files should be listed in the "inputs"
1502 variable. These files are treated as dependencies of each script invocation.
1503
1504 If the command line length is very long, you can use response files to pass
1505 args to your script. See "gn help response_file_contents".
1506
1507 You can dynamically write input dependencies (for incremental rebuilds if an
1508 input file changes) by writing a depfile when the script is run (see "gn help
1509 depfile"). This is more flexible than "inputs".
Julie Hockette2a29402018-07-31 10:11:42 -07001510
Brett Wilson796ed472018-07-16 15:11:09 -07001511 The "deps" and "public_deps" for an action will always be
1512 completed before any part of the action is run so it can depend on
1513 the output of previous steps. The "data_deps" will be built if the
1514 action is built, but may not have completed before all steps of the
1515 action are started. This can give additional parallelism in the build
1516 for runtime-only dependencies.
1517```
1518
1519#### **Outputs**
Julie Hockette2a29402018-07-31 10:11:42 -07001520
Brett Wilson796ed472018-07-16 15:11:09 -07001521```
1522 The script will be executed with the given arguments with the current
1523 directory being that of the root build directory. If you pass files
1524 to your script, see "gn help rebase_path" for how to convert
1525 file names to be relative to the build directory (file names in the
1526 sources, outputs, and inputs will be all treated as relative to the
1527 current build file and converted as needed automatically).
Brett Wilson1e1ea9d2020-02-04 15:34:05 -08001528
1529 GN sets Ninja's flag 'restat = 1` for all action commands. This means
1530 that Ninja will check the timestamp of the output after the action
1531 completes. If output timestamp is unchanged, the step will be treated
1532 as if it never needed to be rebuilt, potentially eliminating some
1533 downstream steps for incremental builds. Scripts can improve build
1534 performance by taking care not to change the timstamp of the output
1535 file(s) if the contents have not changed.
Brett Wilson796ed472018-07-16 15:11:09 -07001536```
1537
1538#### **File name handling**
Julie Hockette2a29402018-07-31 10:11:42 -07001539
Brett Wilson796ed472018-07-16 15:11:09 -07001540```
1541 All output files must be inside the output directory of the build.
1542 You would generally use |$target_out_dir| or |$target_gen_dir| to
1543 reference the output or generated intermediate file directories,
1544 respectively.
1545```
1546
1547#### **Variables**
1548
1549```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001550 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
1551 cflags_objcc, defines, include_dirs, inputs, ldflags,
1552 lib_dirs, libs, precompiled_header, precompiled_source,
1553 rustenv, rustflags, swiftflags, testonly
1554 Dependent configs: all_dependent_configs, public_configs
1555 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
1556 write_runtime_deps
1557 General: check_includes, configs, data, friend, inputs, metadata,
1558 output_extension, output_name, public, sources, testonly,
1559 visibility
1560 Action variables: args, bridge_header, configs, data, depfile,
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07001561 framework_dirs, inputs, mnemonic, module_deps,
1562 module_name, outputs*, pool, response_file_contents,
1563 script*, sources
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001564 * = required
Brett Wilson796ed472018-07-16 15:11:09 -07001565```
1566
1567#### **Example**
1568
1569```
1570 # Runs the script over each IDL file. The IDL script will generate both a .cc
1571 # and a .h file for each input.
1572 action_foreach("my_idl") {
1573 script = "idl_processor.py"
1574 sources = [ "foo.idl", "bar.idl" ]
1575
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07001576 # Causes ninja to output "IDL <label>" rather than the default
1577 # "ACTION <label>" when building this action.
1578 mnemonic = "IDL"
1579
Joe Armstrong73e89072019-05-10 11:23:52 +08001580 # Our script reads this file each time, so we need to list it as a
Brett Wilson796ed472018-07-16 15:11:09 -07001581 # dependency so we can rebuild if it changes.
1582 inputs = [ "my_configuration.txt" ]
1583
1584 # Transformation from source file name to output file names.
1585 outputs = [ "$target_gen_dir/{{source_name_part}}.h",
1586 "$target_gen_dir/{{source_name_part}}.cc" ]
1587
1588 # Note that since "args" is opaque to GN, if you specify paths here, you
1589 # will need to convert it to be relative to the build directory using
1590 # rebase_path().
1591 args = [
1592 "{{source}}",
1593 "-o",
Hector Dearman0d67e272020-12-22 01:37:16 +00001594 rebase_path(target_gen_dir, root_build_dir) +
Brett Wilson796ed472018-07-16 15:11:09 -07001595 "/{{source_name_part}}.h" ]
1596 }
1597```
[email protected]449f3e42024-08-01 21:43:27 +08001598### <a name="func_bundle_data"></a>**bundle_data**: [iOS/macOS] Declare a target without output.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001599
1600```
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01001601 This target type allows one to declare data that is required at runtime. It is
Brett Wilson796ed472018-07-16 15:11:09 -07001602 used to inform "create_bundle" targets of the files to copy into generated
1603 bundle, see "gn help create_bundle" for help.
1604
1605 The target must define a list of files as "sources" and a single "outputs".
1606 If there are multiple files, source expansions must be used to express the
1607 output. The output must reference a file inside of {{bundle_root_dir}}.
1608
1609 This target can be used on all platforms though it is designed only to
1610 generate iOS/macOS bundle. In cross-platform projects, it is advised to put it
1611 behind iOS/macOS conditionals.
1612
Sylvain Defresne06cdcc82024-03-21 13:48:59 +01001613 If any source files in a bundle_data target match `*/*.xcassets/*` then they
1614 will be considered part of an assets catalog, and instead of being copied to
1615 the final bundle the assets catalog itself will be added to the inputs of the
1616 assets catalog compilation step. See "compile_xcassets" tool.
1617
Brett Wilson796ed472018-07-16 15:11:09 -07001618 See "gn help create_bundle" for more information.
1619```
1620
1621#### **Variables**
1622
1623```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001624 Dependent configs: all_dependent_configs, public_configs
1625 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
1626 write_runtime_deps
1627 General: check_includes, configs, data, friend, inputs, metadata,
1628 output_extension, output_name, public, sources, testonly,
1629 visibility
1630 Bundle-specific: sources*, outputs*
Brett Wilson796ed472018-07-16 15:11:09 -07001631 * = required
1632```
1633
1634#### **Examples**
1635
1636```
1637 bundle_data("icudata") {
1638 sources = [ "sources/data/in/icudtl.dat" ]
1639 outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ]
1640 }
1641
1642 bundle_data("base_unittests_bundle_data]") {
1643 sources = [ "test/data" ]
1644 outputs = [
1645 "{{bundle_resources_dir}}/{{source_root_relative_dir}}/" +
1646 "{{source_file_part}}"
1647 ]
1648 }
1649
1650 bundle_data("material_typography_bundle_data") {
1651 sources = [
1652 "src/MaterialTypography.bundle/Roboto-Bold.ttf",
1653 "src/MaterialTypography.bundle/Roboto-Italic.ttf",
1654 "src/MaterialTypography.bundle/Roboto-Regular.ttf",
1655 "src/MaterialTypography.bundle/Roboto-Thin.ttf",
1656 ]
1657 outputs = [
1658 "{{bundle_resources_dir}}/MaterialTypography.bundle/"
1659 "{{source_file_part}}"
1660 ]
1661 }
1662```
[email protected]449f3e42024-08-01 21:43:27 +08001663### <a name="func_copy"></a>**copy**: Declare a target that copies files.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001664
1665#### **File name handling**
1666
1667```
1668 All output files must be inside the output directory of the build. You would
1669 generally use |$target_out_dir| or |$target_gen_dir| to reference the output
1670 or generated intermediate file directories, respectively.
1671
1672 Both "sources" and "outputs" must be specified. Sources can include as many
1673 files as you want, but there can only be one item in the outputs list (plural
1674 is used for the name for consistency with other target types).
1675
1676 If there is more than one source file, your output name should specify a
1677 mapping from each source file to an output file name using source expansion
1678 (see "gn help source_expansion"). The placeholders will look like
1679 "{{source_name_part}}", for example.
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001680
1681 If you want to copy the output of a previous build step, the target that
1682 generates the file to copy must be reachable from the deps or public_deps of
1683 the copy target.
1684```
1685
1686#### **Variables**
1687
1688```
1689 Dependent configs: all_dependent_configs, public_configs
1690 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
1691 write_runtime_deps
1692 General: check_includes, configs, data, friend, inputs, metadata,
1693 output_extension, output_name, public, sources, testonly,
1694 visibility
1695 Copy variables: sources*, outputs*
1696 * = required
Brett Wilson796ed472018-07-16 15:11:09 -07001697```
1698
1699#### **Examples**
1700
1701```
1702 # Write a rule that copies a checked-in DLL to the output directory.
1703 copy("mydll") {
1704 sources = [ "mydll.dll" ]
1705 outputs = [ "$target_out_dir/mydll.dll" ]
1706 }
1707
1708 # Write a rule to copy several files to the target generated files directory.
1709 copy("myfiles") {
1710 sources = [ "data1.dat", "data2.dat", "data3.dat" ]
1711
1712 # Use source expansion to generate output files with the corresponding file
1713 # names in the gen dir. This will just copy each file.
1714 outputs = [ "$target_gen_dir/{{source_file_part}}" ]
1715 }
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001716
1717 # Copy the output of a generated executable.
1718 copy("package_melon") {
1719 # This example uses get_label_info() to compute the output directory of the
1720 # dependency. This allows the copy rule to work regardless of the toolchain.
1721 #
1722 # In some cases (particularly actions defined previously in the same file)
1723 # you can use get_target_outputs() to get the input file which can eliminate
1724 # the assumptions about the output file name of the dependency.
1725
1726 input_dir = get_label_info("//src/tools/melon", "root_out_dir");
1727 sources = [ "$input_dir/melon" ]
1728
1729 outputs = [ "$target_gen_dir/{{source_file_part}}" ]
1730
1731 # Depend on the target to build the file before copying.
1732 deps = [ "//src/tools/melon" ]
1733 }
Brett Wilson796ed472018-07-16 15:11:09 -07001734```
[email protected]449f3e42024-08-01 21:43:27 +08001735### <a name="func_create_bundle"></a>**create_bundle**: [ios/macOS] Build an iOS or macOS bundle.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001736
1737```
1738 This target generates an iOS or macOS bundle (which is a directory with a
1739 well-know structure). This target does not define any sources, instead they
1740 are computed from all "bundle_data" target this one depends on transitively
1741 (the recursion stops at "create_bundle" targets).
1742
Sylvain Defresned46f92f2019-04-03 16:14:29 +02001743 The "bundle_*_dir" are be used for the expansion of {{bundle_*_dir}} rules in
1744 "bundle_data" outputs. The properties are optional but must be defined if any
1745 of the "bundle_data" target use them.
Brett Wilson796ed472018-07-16 15:11:09 -07001746
1747 This target can be used on all platforms though it is designed only to
1748 generate iOS or macOS bundle. In cross-platform projects, it is advised to put
1749 it behind iOS/macOS conditionals.
1750
1751 If a create_bundle is specified as a data_deps for another target, the bundle
1752 is considered a leaf, and its public and private dependencies will not
1753 contribute to any data or data_deps. Required runtime dependencies should be
1754 placed in the bundle. A create_bundle can declare its own explicit data and
1755 data_deps, however.
1756```
1757
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001758#### **Post-processing**
Brett Wilson796ed472018-07-16 15:11:09 -07001759
1760```
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001761 Some bundle needs to be post-processed as part of the build (e.g. on iOS all
1762 application needs to be code signed to run on a device). The post processing
1763 step can be configured via the post_processing_script variable.
Brett Wilson796ed472018-07-16 15:11:09 -07001764
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001765 If set, `post_processing_script` is the path of a script that invoked after
1766 all files have been moved into the bundle. The script must not change any file
1767 in the bundle, but may add new files.
Brett Wilson796ed472018-07-16 15:11:09 -07001768
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001769 If `post_processing_script` is defined, then `post_processing_outputs` must
1770 be defined and non-empty to inform when the script needs to be re-run. The
1771 `post_processing_args` will be passed as is to the script (so path have to be
1772 rebased) and additional inputs may be listed via `post_processing_sources`.
Sylvain Defresne19281422025-08-01 10:40:16 +02001773
1774 If `post_processing_manifest` is defined, then gn will write a file listing
1775 the expected content of the generated bundle (one file per line). The file
1776 can then be passed as a parameter to `post_processing_script` via the
1777 `post_processing_args` array. This can only be set if `post_processing_script`
1778 is set.
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001779```
1780
Brett Wilson796ed472018-07-16 15:11:09 -07001781#### **Variables**
1782
1783```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001784 Dependent configs: all_dependent_configs, public_configs
1785 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
1786 write_runtime_deps
1787 General: check_includes, configs, data, friend, inputs, metadata,
1788 output_extension, output_name, public, sources, testonly,
1789 visibility
1790 Bundle vars: bundle_root_dir, bundle_contents_dir, bundle_resources_dir,
1791 bundle_executable_dir, bundle_deps_filter, product_type,
Sylvain Defresne19281422025-08-01 10:40:16 +02001792 post_processing_args, post_processing_manifest,
1793 post_processing_script, post_processing_sources,
1794 post_processing_outputs, xcode_extra_attributes,
1795 xcode_test_application_name, partial_info_plist
Brett Wilson796ed472018-07-16 15:11:09 -07001796```
1797
1798#### **Example**
1799
1800```
1801 # Defines a template to create an application. On most platform, this is just
1802 # an alias for an "executable" target, but on iOS/macOS, it builds an
1803 # application bundle.
1804 template("app") {
1805 if (!is_ios && !is_mac) {
1806 executable(target_name) {
1807 forward_variables_from(invoker, "*")
1808 }
1809 } else {
1810 app_name = target_name
1811 gen_path = target_gen_dir
1812
1813 action("${app_name}_generate_info_plist") {
1814 script = [ "//build/ios/ios_gen_plist.py" ]
1815 sources = [ "templates/Info.plist" ]
1816 outputs = [ "$gen_path/Info.plist" ]
1817 args = rebase_path(sources, root_build_dir) +
1818 rebase_path(outputs, root_build_dir)
1819 }
1820
1821 bundle_data("${app_name}_bundle_info_plist") {
Sylvain Defresnedcab2f92019-04-03 16:34:05 +02001822 public_deps = [ ":${app_name}_generate_info_plist" ]
Brett Wilson796ed472018-07-16 15:11:09 -07001823 sources = [ "$gen_path/Info.plist" ]
1824 outputs = [ "{{bundle_contents_dir}}/Info.plist" ]
1825 }
1826
1827 executable("${app_name}_generate_executable") {
1828 forward_variables_from(invoker, "*", [
1829 "output_name",
1830 "visibility",
1831 ])
1832 output_name =
1833 rebase_path("$gen_path/$app_name", root_build_dir)
1834 }
1835
1836 code_signing =
1837 defined(invoker.code_signing) && invoker.code_signing
1838
Sylvain Defresnedcab2f92019-04-03 16:34:05 +02001839 if (!is_ios || !code_signing) {
Brett Wilson796ed472018-07-16 15:11:09 -07001840 bundle_data("${app_name}_bundle_executable") {
Sylvain Defresnedcab2f92019-04-03 16:34:05 +02001841 public_deps = [ ":${app_name}_generate_executable" ]
Brett Wilson796ed472018-07-16 15:11:09 -07001842 sources = [ "$gen_path/$app_name" ]
1843 outputs = [ "{{bundle_executable_dir}}/$app_name" ]
1844 }
1845 }
1846
Sylvain Defresnedcab2f92019-04-03 16:34:05 +02001847 create_bundle("$app_name.app") {
Brett Wilson796ed472018-07-16 15:11:09 -07001848 product_type = "com.apple.product-type.application"
1849
1850 if (is_ios) {
Sylvain Defresnedcab2f92019-04-03 16:34:05 +02001851 bundle_root_dir = "$root_build_dir/$target_name"
Brett Wilson796ed472018-07-16 15:11:09 -07001852 bundle_contents_dir = bundle_root_dir
1853 bundle_resources_dir = bundle_contents_dir
1854 bundle_executable_dir = bundle_contents_dir
Brett Wilson796ed472018-07-16 15:11:09 -07001855
Sylvain Defresne7b0690e2020-06-26 15:33:01 +02001856 xcode_extra_attributes = {
Brett Wilson796ed472018-07-16 15:11:09 -07001857 ONLY_ACTIVE_ARCH = "YES"
1858 DEBUG_INFORMATION_FORMAT = "dwarf"
1859 }
1860 } else {
Sylvain Defresnedcab2f92019-04-03 16:34:05 +02001861 bundle_root_dir = "$root_build_dir/$target_name"
1862 bundle_contents_dir = "$bundle_root_dir/Contents"
1863 bundle_resources_dir = "$bundle_contents_dir/Resources"
1864 bundle_executable_dir = "$bundle_contents_dir/MacOS"
Brett Wilson796ed472018-07-16 15:11:09 -07001865 }
1866 deps = [ ":${app_name}_bundle_info_plist" ]
1867 if (is_ios && code_signing) {
1868 deps += [ ":${app_name}_generate_executable" ]
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001869 post_processing_script = "//build/config/ios/codesign.py"
Sylvain Defresne19281422025-08-01 10:40:16 +02001870 post_processing_manifest = "$target_out_dir/$target_name.manifest"
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001871 post_processing_sources = [
Brett Wilson796ed472018-07-16 15:11:09 -07001872 invoker.entitlements_path,
1873 "$target_gen_dir/$app_name",
1874 ]
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001875 post_processing_outputs = [
Brett Wilson796ed472018-07-16 15:11:09 -07001876 "$bundle_root_dir/$app_name",
1877 "$bundle_root_dir/_CodeSignature/CodeResources",
1878 "$bundle_root_dir/embedded.mobileprovision",
1879 "$target_gen_dir/$app_name.xcent",
1880 ]
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001881 post_processing_args = [
1882 "-i=" + ios_post_processing_identity,
Brett Wilson796ed472018-07-16 15:11:09 -07001883 "-b=" + rebase_path(
1884 "$target_gen_dir/$app_name", root_build_dir),
1885 "-e=" + rebase_path(
1886 invoker.entitlements_path, root_build_dir),
1887 "-e=" + rebase_path(
1888 "$target_gen_dir/$app_name.xcent", root_build_dir),
Sylvain Defresne19281422025-08-01 10:40:16 +02001889 "-m=" + rebase_path(post_processing_manifest, root_build_dir),
Brett Wilson796ed472018-07-16 15:11:09 -07001890 rebase_path(bundle_root_dir, root_build_dir),
1891 ]
1892 } else {
1893 deps += [ ":${app_name}_bundle_executable" ]
1894 }
1895 }
1896 }
1897 }
1898```
[email protected]449f3e42024-08-01 21:43:27 +08001899### <a name="func_executable"></a>**executable**: Declare an executable target.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001900
Julie Hockettce1fa072019-05-07 17:44:37 -07001901#### **Language and compilation**
1902
1903```
1904 The tools and commands used to create this target type will be
1905 determined by the source files in its sources. Targets containing
1906 multiple compiler-incompatible languages are not allowed (e.g. a
1907 target containing both C and C++ sources is acceptable, but a
1908 target containing C and Rust sources is not).
1909```
1910
Brett Wilson796ed472018-07-16 15:11:09 -07001911#### **Variables**
1912
1913```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001914 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
1915 cflags_objcc, defines, include_dirs, inputs, ldflags,
1916 lib_dirs, libs, precompiled_header, precompiled_source,
1917 rustenv, rustflags, swiftflags, testonly
1918 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
1919 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07001920 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08001921 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001922 output_extension, output_name, public, sources, testonly,
Nate Fischer8ed01d32019-01-08 17:32:01 -08001923 visibility
Petr Hosekadd1bb12019-09-11 14:39:38 -07001924 Rust variables: aliased_deps, crate_root, crate_name
Nate Fischer8ed01d32019-01-08 17:32:01 -08001925```
[email protected]449f3e42024-08-01 21:43:27 +08001926### <a name="func_generated_file"></a>**generated_file**: Declare a generated_file target.&nbsp;[Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08001927
1928```
1929 Writes data value(s) to disk on resolution. This target type mirrors some
1930 functionality of the write_file() function, but also provides the ability to
1931 collect metadata from its dependencies on resolution rather than writing out
Keir Mierle45611e32019-11-12 11:18:00 -08001932 at parse time.
Nate Fischer8ed01d32019-01-08 17:32:01 -08001933
1934 The `outputs` variable is required to be a list with a single element,
1935 specifying the intended location of the output file.
1936
1937 The `output_conversion` variable specified the format to write the
Sylvain Defresne72d5a6e2021-06-15 17:01:32 +02001938 value. See `gn help io_conversion`.
Nate Fischer8ed01d32019-01-08 17:32:01 -08001939
Tomasz Śniatowski46b572c2021-09-03 21:47:17 +02001940 One of `contents` or `data_keys` must be specified; use of `contents` will
1941 write the contents of that value to file, while use of `data_keys` will
1942 trigger a metadata collection walk based on the dependencies of the target and
1943 the optional values of the `rebase` and `walk_keys` variables. See
Nate Fischer8ed01d32019-01-08 17:32:01 -08001944 `gn help metadata`.
1945
1946 Collected metadata, if specified, will be returned in postorder of
1947 dependencies. See the example for details.
1948```
1949
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001950#### **Variables**
1951
1952```
1953 Dependent configs: all_dependent_configs, public_configs
1954 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
1955 write_runtime_deps
1956 General: check_includes, configs, data, friend, inputs, metadata,
1957 output_extension, output_name, public, sources, testonly,
1958 visibility
Brett Wilson225e90c2024-08-09 10:17:48 -07001959 Generated file: contents, data_keys, rebase, walk_keys, output_conversion,
1960 outputs
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001961```
1962
Nate Fischer8ed01d32019-01-08 17:32:01 -08001963#### **Example (metadata collection)**
1964
1965```
1966 Given the following targets defined in //base/BUILD.gn, where A depends on B
1967 and B depends on C and D:
1968
1969 group("a") {
1970 metadata = {
1971 doom_melon = [ "enable" ]
1972 my_files = [ "foo.cpp" ]
1973
Keir Mierle45611e32019-11-12 11:18:00 -08001974 # Note: this is functionally equivalent to not defining `my_barrier`
1975 # at all in this target's metadata.
Nate Fischer8ed01d32019-01-08 17:32:01 -08001976 my_barrier = [ "" ]
1977 }
1978
1979 deps = [ ":b" ]
1980 }
1981
Julie Hockettd69a9c32019-01-23 14:36:18 -08001982 group("b") {
Nate Fischer8ed01d32019-01-08 17:32:01 -08001983 metadata = {
1984 my_files = [ "bar.cpp" ]
1985 my_barrier = [ ":c" ]
1986 }
1987
1988 deps = [ ":c", ":d" ]
1989 }
1990
1991 group("c") {
1992 metadata = {
1993 doom_melon = [ "disable" ]
1994 my_files = [ "baz.cpp" ]
1995 }
1996 }
1997
1998 group("d") {
1999 metadata = {
2000 my_files = [ "missing.cpp" ]
2001 }
2002 }
2003
2004 If the following generated_file target is defined:
2005
2006 generated_file("my_files_metadata") {
2007 outputs = [ "$root_build_dir/my_files.json" ]
2008 data_keys = [ "my_files" ]
2009
2010 deps = [ "//base:a" ]
2011 }
2012
2013 The following will be written to "$root_build_dir/my_files.json" (less the
2014 comments):
2015 [
2016 "baz.cpp", // from //base:c via //base:b
2017 "missing.cpp" // from //base:d via //base:b
2018 "bar.cpp", // from //base:b via //base:a
2019 "foo.cpp", // from //base:a
2020 ]
2021
2022 Alternatively, as an example of using walk_keys, if the following
2023 generated_file target is defined:
2024
2025 generated_file("my_files_metadata") {
2026 outputs = [ "$root_build_dir/my_files.json" ]
2027 data_keys = [ "my_files" ]
2028 walk_keys = [ "my_barrier" ]
2029
2030 deps = [ "//base:a" ]
2031 }
2032
2033 The following will be written to "$root_build_dir/my_files.json" (again less
2034 the comments):
2035 [
2036 "baz.cpp", // from //base:c via //base:b
2037 "bar.cpp", // from //base:b via //base:a
2038 "foo.cpp", // from //base:a
2039 ]
2040
2041 If `rebase` is used in the following generated_file target:
2042
2043 generated_file("my_files_metadata") {
2044 outputs = [ "$root_build_dir/my_files.json" ]
2045 data_keys = [ "my_files" ]
2046 walk_keys = [ "my_barrier" ]
2047 rebase = root_build_dir
2048
2049 deps = [ "//base:a" ]
2050 }
2051
2052 The following will be written to "$root_build_dir/my_files.json" (again less
2053 the comments) (assuming root_build_dir = "//out"):
2054 [
2055 "../base/baz.cpp", // from //base:c via //base:b
2056 "../base/bar.cpp", // from //base:b via //base:a
2057 "../base/foo.cpp", // from //base:a
2058 ]
2059```
[email protected]449f3e42024-08-01 21:43:27 +08002060### <a name="func_group"></a>**group**: Declare a named group of targets.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002061
2062```
2063 This target type allows you to create meta-targets that just collect a set of
2064 dependencies into one named target. Groups can additionally specify configs
2065 that apply to their dependents.
2066```
2067
2068#### **Variables**
2069
2070```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002071 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2072 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002073 Dependent configs: all_dependent_configs, public_configs
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002074 General: check_includes, configs, data, friend, inputs, metadata,
2075 output_extension, output_name, public, sources, testonly,
2076 visibility
Brett Wilson796ed472018-07-16 15:11:09 -07002077```
2078
2079#### **Example**
2080
2081```
2082 group("all") {
2083 deps = [
2084 "//project:runner",
2085 "//project:unit_tests",
2086 ]
2087 }
2088```
[email protected]449f3e42024-08-01 21:43:27 +08002089### <a name="func_loadable_module"></a>**loadable_module**: Declare a loadable module target.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002090
2091```
2092 This target type allows you to create an object file that is (and can only
2093 be) loaded and unloaded at runtime.
2094
2095 A loadable module will be specified on the linker line for targets listing
2096 the loadable module in its "deps". If you don't want this (if you don't need
2097 to dynamically load the library at runtime), then you should use a
2098 "shared_library" target type instead.
2099```
2100
Julie Hockettce1fa072019-05-07 17:44:37 -07002101#### **Language and compilation**
2102
2103```
2104 The tools and commands used to create this target type will be
2105 determined by the source files in its sources. Targets containing
2106 multiple compiler-incompatible languages are not allowed (e.g. a
2107 target containing both C and C++ sources is acceptable, but a
2108 target containing C and Rust sources is not).
2109```
2110
Brett Wilson796ed472018-07-16 15:11:09 -07002111#### **Variables**
2112
2113```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002114 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2115 cflags_objcc, defines, include_dirs, inputs, ldflags,
2116 lib_dirs, libs, precompiled_header, precompiled_source,
2117 rustenv, rustflags, swiftflags, testonly
2118 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2119 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002120 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08002121 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002122 output_extension, output_name, public, sources, testonly,
Nate Fischer8ed01d32019-01-08 17:32:01 -08002123 visibility
Petr Hosekadd1bb12019-09-11 14:39:38 -07002124 Rust variables: aliased_deps, crate_root, crate_name, crate_type
Julie Hockettce1fa072019-05-07 17:44:37 -07002125```
[email protected]449f3e42024-08-01 21:43:27 +08002126### <a name="func_rust_library"></a>**rust_library**: Declare a Rust library target.&nbsp;[Back to Top](#gn-reference)
Julie Hockettce1fa072019-05-07 17:44:37 -07002127
2128```
2129 A Rust library is an archive containing additional rust-c provided metadata.
2130 These are the files produced by the rustc compiler with the `.rlib`
2131 extension, and are the intermediate step for most Rust-based binaries.
2132```
2133
2134#### **Language and compilation**
2135
2136```
2137 The tools and commands used to create this target type will be
2138 determined by the source files in its sources. Targets containing
2139 multiple compiler-incompatible languages are not allowed (e.g. a
2140 target containing both C and C++ sources is acceptable, but a
2141 target containing C and Rust sources is not).
2142```
2143
2144#### **Variables**
2145
2146```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002147 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2148 cflags_objcc, defines, include_dirs, inputs, ldflags,
2149 lib_dirs, libs, precompiled_header, precompiled_source,
2150 rustenv, rustflags, swiftflags, testonly
2151 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2152 write_runtime_deps
Julie Hockettce1fa072019-05-07 17:44:37 -07002153 Dependent configs: all_dependent_configs, public_configs
2154 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002155 output_extension, output_name, public, sources, testonly,
Julie Hockettce1fa072019-05-07 17:44:37 -07002156 visibility
Petr Hosekadd1bb12019-09-11 14:39:38 -07002157 Rust variables: aliased_deps, crate_root, crate_name
Brett Wilson796ed472018-07-16 15:11:09 -07002158```
[email protected]449f3e42024-08-01 21:43:27 +08002159### <a name="func_rust_proc_macro"></a>**rust_proc_macro**: Declare a Rust procedural macro target.&nbsp;[Back to Top](#gn-reference)
Petr Hosekfe36c7c2019-11-26 14:38:08 -08002160
2161```
2162 A Rust procedural macro allows creating syntax extensions as execution of a
2163 function. They are compiled as dynamic libraries and used by the compiler at
2164 runtime.
2165
2166 Their use is the same as of other Rust libraries, but their build has some
2167 additional restrictions in terms of supported flags.
2168```
2169
2170#### **Language and compilation**
2171
2172```
2173 The tools and commands used to create this target type will be
2174 determined by the source files in its sources. Targets containing
2175 multiple compiler-incompatible languages are not allowed (e.g. a
2176 target containing both C and C++ sources is acceptable, but a
2177 target containing C and Rust sources is not).
2178```
2179
2180#### **Variables**
2181
2182```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002183 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2184 cflags_objcc, defines, include_dirs, inputs, ldflags,
2185 lib_dirs, libs, precompiled_header, precompiled_source,
2186 rustenv, rustflags, swiftflags, testonly
2187 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2188 write_runtime_deps
Petr Hosekfe36c7c2019-11-26 14:38:08 -08002189 Dependent configs: all_dependent_configs, public_configs
2190 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002191 output_extension, output_name, public, sources, testonly,
Petr Hosekfe36c7c2019-11-26 14:38:08 -08002192 visibility
2193 Rust variables: aliased_deps, crate_root, crate_name
2194```
[email protected]449f3e42024-08-01 21:43:27 +08002195### <a name="func_shared_library"></a>**shared_library**: Declare a shared library target.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002196
2197```
2198 A shared library will be specified on the linker line for targets listing the
2199 shared library in its "deps". If you don't want this (say you dynamically
2200 load the library at runtime), then you should depend on the shared library
2201 via "data_deps" or, on Darwin platforms, use a "loadable_module" target type
2202 instead.
2203```
2204
Julie Hockettce1fa072019-05-07 17:44:37 -07002205#### **Language and compilation**
2206
2207```
2208 The tools and commands used to create this target type will be
2209 determined by the source files in its sources. Targets containing
2210 multiple compiler-incompatible languages are not allowed (e.g. a
2211 target containing both C and C++ sources is acceptable, but a
2212 target containing C and Rust sources is not).
2213```
2214
Brett Wilson796ed472018-07-16 15:11:09 -07002215#### **Variables**
2216
2217```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002218 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2219 cflags_objcc, defines, include_dirs, inputs, ldflags,
2220 lib_dirs, libs, precompiled_header, precompiled_source,
2221 rustenv, rustflags, swiftflags, testonly
2222 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2223 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002224 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08002225 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002226 output_extension, output_name, public, sources, testonly,
Nate Fischer8ed01d32019-01-08 17:32:01 -08002227 visibility
Petr Hosekadd1bb12019-09-11 14:39:38 -07002228 Rust variables: aliased_deps, crate_root, crate_name, crate_type
Brett Wilson796ed472018-07-16 15:11:09 -07002229```
[email protected]449f3e42024-08-01 21:43:27 +08002230### <a name="func_source_set"></a>**source_set**: Declare a source set target.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002231
2232```
Robert Sesekd0a6f072020-05-15 11:21:22 -04002233 Only C-language source sets are supported at the moment.
Julie Hockettce1fa072019-05-07 17:44:37 -07002234```
2235
2236#### **C-language source_sets**
2237
2238```
Brett Wilson796ed472018-07-16 15:11:09 -07002239 A source set is a collection of sources that get compiled, but are not linked
2240 to produce any kind of library. Instead, the resulting object files are
2241 implicitly added to the linker line of all targets that depend on the source
2242 set.
2243
2244 In most cases, a source set will behave like a static library, except no
2245 actual library file will be produced. This will make the build go a little
2246 faster by skipping creation of a large static library, while maintaining the
2247 organizational benefits of focused build targets.
2248
2249 The main difference between a source set and a static library is around
2250 handling of exported symbols. Most linkers assume declaring a function
2251 exported means exported from the static library. The linker can then do dead
2252 code elimination to delete code not reachable from exported functions.
2253
2254 A source set will not do this code elimination since there is no link step.
Julie Hockette2a29402018-07-31 10:11:42 -07002255 This allows you to link many source sets into a shared library and have the
Brett Wilson796ed472018-07-16 15:11:09 -07002256 "exported symbol" notation indicate "export from the final shared library and
2257 not from the intermediate targets." There is no way to express this concept
2258 when linking multiple static libraries into a shared library.
2259```
2260
2261#### **Variables**
2262
2263```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002264 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2265 cflags_objcc, defines, include_dirs, inputs, ldflags,
2266 lib_dirs, libs, precompiled_header, precompiled_source,
2267 rustenv, rustflags, swiftflags, testonly
2268 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2269 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002270 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08002271 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002272 output_extension, output_name, public, sources, testonly,
Nate Fischer8ed01d32019-01-08 17:32:01 -08002273 visibility
Brett Wilson796ed472018-07-16 15:11:09 -07002274```
[email protected]449f3e42024-08-01 21:43:27 +08002275### <a name="func_static_library"></a>**static_library**: Declare a static library target.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002276
2277```
2278 Make a ".a" / ".lib" file.
2279
2280 If you only need the static library for intermediate results in the build,
2281 you should consider a source_set instead since it will skip the (potentially
2282 slow) step of creating the intermediate library file.
2283```
2284
2285#### **Variables**
2286
2287```
2288 complete_static_lib
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002289 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2290 cflags_objcc, defines, include_dirs, inputs, ldflags,
2291 lib_dirs, libs, precompiled_header, precompiled_source,
2292 rustenv, rustflags, swiftflags, testonly
2293 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2294 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002295 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08002296 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002297 output_extension, output_name, public, sources, testonly,
Nate Fischer8ed01d32019-01-08 17:32:01 -08002298 visibility
Petr Hosekadd1bb12019-09-11 14:39:38 -07002299 Rust variables: aliased_deps, crate_root, crate_name
Julie Hockettce1fa072019-05-07 17:44:37 -07002300
2301 The tools and commands used to create this target type will be
2302 determined by the source files in its sources. Targets containing
2303 multiple compiler-incompatible languages are not allowed (e.g. a
2304 target containing both C and C++ sources is acceptable, but a
2305 target containing C and Rust sources is not).
Brett Wilson796ed472018-07-16 15:11:09 -07002306```
[email protected]449f3e42024-08-01 21:43:27 +08002307### <a name="func_target"></a>**target**: Declare a target with the given programmatic type.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002308
2309```
2310 target(target_type_string, target_name_string) { ... }
2311
2312 The target() function is a way to invoke a built-in target or template with a
2313 type determined at runtime. This is useful for cases where the type of a
2314 target might not be known statically.
2315
2316 Only templates and built-in target functions are supported for the
2317 target_type_string parameter. Arbitrary functions, configs, and toolchains
2318 are not supported.
2319
2320 The call:
2321 target("source_set", "doom_melon") {
2322 Is equivalent to:
2323 source_set("doom_melon") {
2324```
2325
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002326#### **Common target variables**
2327
2328```
2329 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2330 write_runtime_deps
2331 Dependent configs: all_dependent_configs, public_configs
2332 General: check_includes, configs, data, friend, inputs, metadata,
2333 output_extension, output_name, public, sources, testonly,
2334 visibility
2335
2336 Targets will also have variables specific to that type, see "gn help <type>"
2337 for more.
2338```
2339
Brett Wilson796ed472018-07-16 15:11:09 -07002340#### **Example**
2341
2342```
2343 if (foo_build_as_shared) {
2344 my_type = "shared_library"
2345 } else {
2346 my_type = "source_set"
2347 }
2348
2349 target(my_type, "foo") {
2350 ...
2351 }
2352```
2353## <a name="functions"></a>Buildfile functions
2354
[email protected]449f3e42024-08-01 21:43:27 +08002355### <a name="func_assert"></a>**assert**: Assert an expression is true at generation time.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002356
2357```
2358 assert(<condition> [, <error string>])
2359
2360 If the condition is false, the build will fail with an error. If the
2361 optional second argument is provided, that string will be printed
2362 with the error message.
2363```
2364
2365#### **Examples**
2366
2367```
2368 assert(is_win)
2369 assert(defined(sources), "Sources must be defined");
2370```
[email protected]449f3e42024-08-01 21:43:27 +08002371### <a name="func_config"></a>**config**: Defines a configuration object.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002372
2373```
2374 Configuration objects can be applied to targets and specify sets of compiler
2375 flags, includes, defines, etc. They provide a way to conveniently group sets
2376 of this configuration information.
2377
2378 A config is referenced by its label just like a target.
2379
2380 The values in a config are additive only. If you want to remove a flag you
2381 need to remove the corresponding config that sets it. The final set of flags,
2382 defines, etc. for a target is generated in this order:
2383
Nico Weber693f9fb2021-10-08 15:33:57 -04002384 1. The values specified directly on the target (rather than using a config).
Brett Wilson796ed472018-07-16 15:11:09 -07002385 2. The configs specified in the target's "configs" list, in order.
2386 3. Public_configs from a breadth-first traversal of the dependency tree in
2387 the order that the targets appear in "deps".
2388 4. All dependent configs from a breadth-first traversal of the dependency
2389 tree in the order that the targets appear in "deps".
2390```
2391
Joe Armstrong39413942019-03-15 10:34:03 +08002392#### **More background**
2393
2394```
2395 Configs solve a problem where the build system needs to have a higher-level
2396 understanding of various compiler settings. For example, some compiler flags
2397 have to appear in a certain order relative to each other, some settings like
2398 defines and flags logically go together, and the build system needs to
2399 de-duplicate flags even though raw command-line parameters can't always be
2400 operated on in that way.
2401
2402 The config gives a name to a group of settings that can then be reasoned
2403 about by GN. GN can know that configs with the same label are the same thing
2404 so can be de-duplicated. It allows related settings to be grouped so they
2405 are added or removed as a unit. And it allows targets to refer to settings
2406 with conceptual names ("no_rtti", "enable_exceptions", etc.) rather than
2407 having to hard-coding every compiler's flags each time they are referred to.
2408```
2409
Brett Wilson796ed472018-07-16 15:11:09 -07002410#### **Variables valid in a config definition**
Joe Armstrong39413942019-03-15 10:34:03 +08002411
Brett Wilson796ed472018-07-16 15:11:09 -07002412```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002413 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2414 cflags_objcc, defines, include_dirs, inputs, ldflags,
2415 lib_dirs, libs, precompiled_header, precompiled_source,
2416 rustenv, rustflags, swiftflags, testonly
Brett Wilson796ed472018-07-16 15:11:09 -07002417 Nested configs: configs
Tomasz Śniatowski46b572c2021-09-03 21:47:17 +02002418 General: visibility
Brett Wilson796ed472018-07-16 15:11:09 -07002419```
2420
2421#### **Variables on a target used to apply configs**
2422
2423```
2424 all_dependent_configs, configs, public_configs
2425```
2426
2427#### **Example**
2428
2429```
2430 config("myconfig") {
Joe Armstrongf5ad8072019-05-08 08:42:56 +08002431 include_dirs = [ "include/common" ]
Brett Wilson796ed472018-07-16 15:11:09 -07002432 defines = [ "ENABLE_DOOM_MELON" ]
2433 }
2434
2435 executable("mything") {
2436 configs = [ ":myconfig" ]
2437 }
2438```
[email protected]449f3e42024-08-01 21:43:27 +08002439### <a name="func_declare_args"></a>**declare_args**: Declare build arguments.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002440
2441```
2442 Introduces the given arguments into the current scope. If they are not
2443 specified on the command line or in a toolchain's arguments, the default
2444 values given in the declare_args block will be used. However, these defaults
2445 will not override command-line values.
2446
2447 See also "gn help buildargs" for an overview.
2448
2449 The precise behavior of declare args is:
2450
2451 1. The declare_args() block executes. Any variable defined in the enclosing
2452 scope is available for reading, but any variable defined earlier in
2453 the current scope is not (since the overrides haven't been applied yet).
2454
2455 2. At the end of executing the block, any variables set within that scope
Petr Hosek7617b592019-10-02 09:52:21 -07002456 are saved, with the values specified in the block used as the "default value"
2457 for that argument. Once saved, these variables are available for override
2458 via args.gn.
Brett Wilson796ed472018-07-16 15:11:09 -07002459
2460 3. User-defined overrides are applied. Anything set in "gn args" now
2461 overrides any default values. The resulting set of variables is promoted
2462 to be readable from the following code in the file.
2463
2464 This has some ramifications that may not be obvious:
2465
2466 - You should not perform difficult work inside a declare_args block since
2467 this only sets a default value that may be discarded. In particular,
2468 don't use the result of exec_script() to set the default value. If you
2469 want to have a script-defined default, set some default "undefined" value
2470 like [], "", or -1, and after the declare_args block, call exec_script if
2471 the value is unset by the user.
2472
2473 - Because you cannot read the value of a variable defined in the same
2474 block, if you need to make the default value of one arg depend
2475 on the possibly-overridden value of another, write two separate
2476 declare_args() blocks:
2477
2478 declare_args() {
2479 enable_foo = true
2480 }
2481 declare_args() {
2482 # Bar defaults to same user-overridden state as foo.
2483 enable_bar = enable_foo
2484 }
2485```
2486
2487#### **Example**
2488
2489```
2490 declare_args() {
2491 enable_teleporter = true
2492 enable_doom_melon = false
2493 }
2494
2495 If you want to override the (default disabled) Doom Melon:
2496 gn --args="enable_doom_melon=true enable_teleporter=true"
2497 This also sets the teleporter, but it's already defaulted to on so it will
2498 have no effect.
2499```
[email protected]449f3e42024-08-01 21:43:27 +08002500### <a name="func_defined"></a>**defined**: Returns whether an identifier is defined.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002501
2502```
2503 Returns true if the given argument is defined. This is most useful in
2504 templates to assert that the caller set things up properly.
2505
2506 You can pass an identifier:
2507 defined(foo)
2508 which will return true or false depending on whether foo is defined in the
2509 current scope.
2510
2511 You can also check a named scope:
2512 defined(foo.bar)
2513 which will return true or false depending on whether bar is defined in the
2514 named scope foo. It will throw an error if foo is not defined or is not a
2515 scope.
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07002516
2517 You can also check a named scope using a subscript string expression:
2518 defined(foo[bar + "_name"])
Takuto Ikuta26aa46c2023-05-09 16:28:45 +09002519 which will return true or false depending on whether the subscript
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07002520 expression expands to the name of a member of the scope foo. It will
2521 throw an error if foo is not defined or is not a scope, or if the
2522 expression does not expand to a string, or if it is an empty string.
Brett Wilson796ed472018-07-16 15:11:09 -07002523```
2524
2525#### **Example**
2526
2527```
2528 template("mytemplate") {
2529 # To help users call this template properly...
2530 assert(defined(invoker.sources), "Sources must be defined")
2531
2532 # If we want to accept an optional "values" argument, we don't
2533 # want to dereference something that may not be defined.
2534 if (defined(invoker.values)) {
2535 values = invoker.values
2536 } else {
2537 values = "some default value"
2538 }
2539 }
2540```
[email protected]449f3e42024-08-01 21:43:27 +08002541### <a name="func_exec_script"></a>**exec_script**: Synchronously run a script and return the output.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002542
2543```
2544 exec_script(filename,
2545 arguments = [],
2546 input_conversion = "",
2547 file_dependencies = [])
2548
2549 Runs the given script, returning the stdout of the script. The build
2550 generation will fail if the script does not exist or returns a nonzero exit
2551 code.
2552
2553 The current directory when executing the script will be the root build
2554 directory. If you are passing file names, you will want to use the
2555 rebase_path() function to make file names relative to this path (see "gn help
2556 rebase_path").
Gary Miguelce7fa362018-09-17 12:48:17 -07002557
2558 The default script interpreter is Python ("python" on POSIX, "python.exe" or
2559 "python.bat" on Windows). This can be configured by the script_executable
2560 variable, see "gn help dotfile".
Brett Wilson796ed472018-07-16 15:11:09 -07002561```
2562
2563#### **Arguments**:
2564
2565```
2566 filename:
Gary Miguelce7fa362018-09-17 12:48:17 -07002567 File name of script to execute. Non-absolute names will be treated as
2568 relative to the current build file.
Brett Wilson796ed472018-07-16 15:11:09 -07002569
2570 arguments:
2571 A list of strings to be passed to the script as arguments. May be
2572 unspecified or the empty list which means no arguments.
2573
2574 input_conversion:
Sylvain Defresne72d5a6e2021-06-15 17:01:32 +02002575 Controls how the file is read and parsed. See `gn help io_conversion`.
Brett Wilson796ed472018-07-16 15:11:09 -07002576
2577 If unspecified, defaults to the empty string which causes the script
2578 result to be discarded. exec script will return None.
2579
2580 dependencies:
2581 (Optional) A list of files that this script reads or otherwise depends
2582 on. These dependencies will be added to the build result such that if any
2583 of them change, the build will be regenerated and the script will be
2584 re-run.
2585
2586 The script itself will be an implicit dependency so you do not need to
2587 list it.
2588```
2589
2590#### **Example**
2591
2592```
2593 all_lines = exec_script(
2594 "myscript.py", [some_input], "list lines",
2595 [ rebase_path("data_file.txt", root_build_dir) ])
2596
2597 # This example just calls the script with no arguments and discards the
2598 # result.
2599 exec_script("//foo/bar/myscript.py")
2600```
[email protected]449f3e42024-08-01 21:43:27 +08002601### <a name="func_filter_exclude"></a>**filter_exclude**: Remove values that match a set of patterns.&nbsp;[Back to Top](#gn-reference)
Sylvain Defresneaff489a2020-03-11 18:27:43 +01002602
2603```
2604 filter_exclude(values, exclude_patterns)
2605
2606 The argument values must be a list of strings.
2607
2608 The argument exclude_patterns must be a list of file patterns (see
2609 "gn help file_pattern"). Any elements in values matching at least one
2610 of those patterns will be excluded.
2611```
2612
2613#### **Examples**
2614```
2615 values = [ "foo.cc", "foo.h", "foo.proto" ]
2616 result = filter_exclude(values, [ "*.proto" ])
2617 # result will be [ "foo.cc", "foo.h" ]
2618```
[email protected]449f3e42024-08-01 21:43:27 +08002619### <a name="func_filter_include"></a>**filter_include**: Remove values that do not match a set of patterns.&nbsp;[Back to Top](#gn-reference)
Sylvain Defresneaff489a2020-03-11 18:27:43 +01002620
2621```
2622 filter_include(values, include_patterns)
2623
2624 The argument values must be a list of strings.
2625
2626 The argument include_patterns must be a list of file patterns (see
2627 "gn help file_pattern"). Only elements from values matching at least
2628 one of the pattern will be included.
2629```
2630
2631#### **Examples**
2632```
2633 values = [ "foo.cc", "foo.h", "foo.proto" ]
2634 result = filter_include(values, [ "*.proto" ])
2635 # result will be [ "foo.proto" ]
2636```
[email protected]449f3e42024-08-01 21:43:27 +08002637### <a name="func_filter_labels_exclude"></a>**filter_labels_exclude**: Remove labels that match a set of patterns.&nbsp;[Back to Top](#gn-reference)
Aaron Woode05c0aa2024-02-14 13:40:53 -08002638
2639```
2640 filter_labels_exclude(labels, exclude_patterns)
2641
2642 The argument labels must be a list of strings.
2643
2644 The argument exclude_patterns must be a list of label patterns (see
2645 "gn help label_pattern"). Only elements from labels matching at least
2646 one of the patterns will be excluded.
2647```
2648
2649#### **Examples**
2650```
2651 labels = [ "//foo:baz", "//foo/bar:baz", "//bar:baz" ]
2652 result = filter_labels_exclude(labels, [ "//foo:*" ])
2653 # result will be [ "//foo/bar:baz", "//bar:baz" ]
2654```
[email protected]449f3e42024-08-01 21:43:27 +08002655### <a name="func_filter_labels_include"></a>**filter_labels_include**: Remove labels that do not match a set of patterns.&nbsp;[Back to Top](#gn-reference)
Aaron Woode05c0aa2024-02-14 13:40:53 -08002656
2657```
2658 filter_labels_include(labels, include_patterns)
2659
2660 The argument labels must be a list of strings.
2661
2662 The argument include_patterns must be a list of label patterns (see
2663 "gn help label_pattern"). Only elements from labels matching at least
2664 one of the patterns will be included.
2665```
2666
2667#### **Examples**
2668```
2669 labels = [ "//foo:baz", "//foo/bar:baz", "//bar:baz" ]
2670 result = filter_labels_include(labels, [ "//foo:*" ])
2671 # result will be [ "//foo:baz" ]
2672```
[email protected]449f3e42024-08-01 21:43:27 +08002673### <a name="func_foreach"></a>**foreach**: Iterate over a list.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002674
2675```
2676 foreach(<loop_var>, <list>) {
2677 <loop contents>
2678 }
2679
2680 Executes the loop contents block over each item in the list, assigning the
2681 loop_var to each item in sequence. The <loop_var> will be a copy so assigning
2682 to it will not mutate the list. The loop will iterate over a copy of <list>
2683 so mutating it inside the loop will not affect iteration.
2684
2685 The block does not introduce a new scope, so that variable assignments inside
2686 the loop will be visible once the loop terminates.
2687
2688 The loop variable will temporarily shadow any existing variables with the
2689 same name for the duration of the loop. After the loop terminates the loop
2690 variable will no longer be in scope, and the previous value (if any) will be
2691 restored.
2692```
2693
2694#### **Example**
2695
2696```
2697 mylist = [ "a", "b", "c" ]
2698 foreach(i, mylist) {
2699 print(i)
2700 }
2701
2702 Prints:
2703 a
2704 b
2705 c
2706```
[email protected]449f3e42024-08-01 21:43:27 +08002707### <a name="func_forward_variables_from"></a>**forward_variables_from**: Copies variables from a different scope.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002708
2709```
2710 forward_variables_from(from_scope, variable_list_or_star,
2711 variable_to_not_forward_list = [])
2712
2713 Copies the given variables from the given scope to the local scope if they
2714 exist. This is normally used in the context of templates to use the values of
2715 variables defined in the template invocation to a template-defined target.
2716
2717 The variables in the given variable_list will be copied if they exist in the
2718 given scope or any enclosing scope. If they do not exist, nothing will happen
2719 and they be left undefined in the current scope.
2720
2721 As a special case, if the variable_list is a string with the value of "*",
2722 all variables from the given scope will be copied. "*" only copies variables
2723 set directly on the from_scope, not enclosing ones. Otherwise it would
2724 duplicate all global variables.
2725
2726 When an explicit list of variables is supplied, if the variable exists in the
2727 current (destination) scope already, an error will be thrown. If "*" is
2728 specified, variables in the current scope will be clobbered (the latter is
2729 important because most targets have an implicit configs list, which means it
2730 wouldn't work at all if it didn't clobber).
2731
Brett Wilson796ed472018-07-16 15:11:09 -07002732 If variables_to_not_forward_list is non-empty, then it must contains a list
2733 of variable names that will not be forwarded. This is mostly useful when
2734 variable_list_or_star has a value of "*".
2735```
2736
2737#### **Examples**
2738
2739```
Andrew Grieve57a964c2018-09-14 10:50:56 -04002740 # forward_variables_from(invoker, ["foo"])
2741 # is equivalent to:
2742 assert(!defined(foo))
2743 if (defined(invoker.foo)) {
2744 foo = invoker.foo
2745 }
2746
Brett Wilson796ed472018-07-16 15:11:09 -07002747 # This is a common action template. It would invoke a script with some given
2748 # parameters, and wants to use the various types of deps and the visibility
2749 # from the invoker if it's defined. It also injects an additional dependency
2750 # to all targets.
2751 template("my_test") {
2752 action(target_name) {
2753 forward_variables_from(invoker, [ "data_deps", "deps",
Julie Hockette2a29402018-07-31 10:11:42 -07002754 "public_deps", "visibility"])
Brett Wilson796ed472018-07-16 15:11:09 -07002755 # Add our test code to the dependencies.
2756 # "deps" may or may not be defined at this point.
2757 if (defined(deps)) {
2758 deps += [ "//tools/doom_melon" ]
2759 } else {
2760 deps = [ "//tools/doom_melon" ]
2761 }
2762 }
2763 }
2764
Julie Hockette2a29402018-07-31 10:11:42 -07002765 # This is a template around a target whose type depends on a global variable.
2766 # It forwards all values from the invoker.
Brett Wilson796ed472018-07-16 15:11:09 -07002767 template("my_wrapper") {
2768 target(my_wrapper_target_type, target_name) {
2769 forward_variables_from(invoker, "*")
2770 }
2771 }
2772
2773 # A template that wraps another. It adds behavior based on one
2774 # variable, and forwards all others to the nested target.
2775 template("my_ios_test_app") {
2776 ios_test_app(target_name) {
2777 forward_variables_from(invoker, "*", ["test_bundle_name"])
2778 if (!defined(extra_substitutions)) {
2779 extra_substitutions = []
2780 }
2781 extra_substitutions += [ "BUNDLE_ID_TEST_NAME=$test_bundle_name" ]
2782 }
2783 }
2784```
[email protected]449f3e42024-08-01 21:43:27 +08002785### <a name="func_get_label_info"></a>**get_label_info**: Get an attribute from a target's label.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002786
2787```
2788 get_label_info(target_label, what)
2789
2790 Given the label of a target, returns some attribute of that target. The
2791 target need not have been previously defined in the same file, since none of
2792 the attributes depend on the actual target definition, only the label itself.
2793
2794 See also "gn help get_target_outputs".
2795```
2796
2797#### **Possible values for the "what" parameter**
2798
2799```
2800 "name"
2801 The short name of the target. This will match the value of the
2802 "target_name" variable inside that target's declaration. For the label
2803 "//foo/bar:baz" this will return "baz".
2804
2805 "dir"
2806 The directory containing the target's definition, with no slash at the
2807 end. For the label "//foo/bar:baz" this will return "//foo/bar".
2808
2809 "target_gen_dir"
2810 The generated file directory for the target. This will match the value of
2811 the "target_gen_dir" variable when inside that target's declaration.
2812
2813 "root_gen_dir"
2814 The root of the generated file tree for the target. This will match the
2815 value of the "root_gen_dir" variable when inside that target's
2816 declaration.
2817
2818 "target_out_dir
2819 The output directory for the target. This will match the value of the
2820 "target_out_dir" variable when inside that target's declaration.
2821
2822 "root_out_dir"
2823 The root of the output file tree for the target. This will match the
2824 value of the "root_out_dir" variable when inside that target's
2825 declaration.
2826
2827 "label_no_toolchain"
2828 The fully qualified version of this label, not including the toolchain.
2829 For the input ":bar" it might return "//foo:bar".
2830
2831 "label_with_toolchain"
2832 The fully qualified version of this label, including the toolchain. For
2833 the input ":bar" it might return "//foo:bar(//toolchain:x64)".
2834
2835 "toolchain"
2836 The label of the toolchain. This will match the value of the
2837 "current_toolchain" variable when inside that target's declaration.
2838```
2839
2840#### **Examples**
2841
2842```
2843 get_label_info(":foo", "name")
2844 # Returns string "foo".
2845
2846 get_label_info("//foo/bar:baz", "target_gen_dir")
2847 # Returns string "//out/Debug/gen/foo/bar".
2848```
[email protected]449f3e42024-08-01 21:43:27 +08002849### <a name="func_get_path_info"></a>**get_path_info**: Extract parts of a file or directory name.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002850
2851```
2852 get_path_info(input, what)
2853
2854 The first argument is either a string representing a file or directory name,
2855 or a list of such strings. If the input is a list the return value will be a
2856 list containing the result of applying the rule to each item in the input.
2857```
2858
2859#### **Possible values for the "what" parameter**
2860
2861```
2862 "file"
2863 The substring after the last slash in the path, including the name and
2864 extension. If the input ends in a slash, the empty string will be
2865 returned.
2866 "foo/bar.txt" => "bar.txt"
2867 "bar.txt" => "bar.txt"
2868 "foo/" => ""
2869 "" => ""
2870
2871 "name"
2872 The substring of the file name not including the extension.
2873 "foo/bar.txt" => "bar"
2874 "foo/bar" => "bar"
2875 "foo/" => ""
2876
2877 "extension"
2878 The substring following the last period following the last slash, or the
2879 empty string if not found. The period is not included.
2880 "foo/bar.txt" => "txt"
2881 "foo/bar" => ""
2882
2883 "dir"
2884 The directory portion of the name, not including the slash.
2885 "foo/bar.txt" => "foo"
2886 "//foo/bar" => "//foo"
2887 "foo" => "."
2888
2889 The result will never end in a slash, so if the resulting is empty, the
2890 system ("/") or source ("//") roots, a "." will be appended such that it
2891 is always legal to append a slash and a filename and get a valid path.
2892
2893 "out_dir"
2894 The output file directory corresponding to the path of the given file,
2895 not including a trailing slash.
2896 "//foo/bar/baz.txt" => "//out/Default/obj/foo/bar"
2897
2898 "gen_dir"
2899 The generated file directory corresponding to the path of the given file,
2900 not including a trailing slash.
2901 "//foo/bar/baz.txt" => "//out/Default/gen/foo/bar"
2902
2903 "abspath"
2904 The full absolute path name to the file or directory. It will be resolved
2905 relative to the current directory, and then the source- absolute version
2906 will be returned. If the input is system- absolute, the same input will
2907 be returned.
2908 "foo/bar.txt" => "//mydir/foo/bar.txt"
2909 "foo/" => "//mydir/foo/"
2910 "//foo/bar" => "//foo/bar" (already absolute)
2911 "/usr/include" => "/usr/include" (already absolute)
2912
2913 If you want to make the path relative to another directory, or to be
2914 system-absolute, see rebase_path().
2915```
2916
2917#### **Examples**
2918```
2919 sources = [ "foo.cc", "foo.h" ]
2920 result = get_path_info(source, "abspath")
2921 # result will be [ "//mydir/foo.cc", "//mydir/foo.h" ]
2922
2923 result = get_path_info("//foo/bar/baz.cc", "dir")
2924 # result will be "//foo/bar"
2925
2926 # Extract the source-absolute directory name,
Joe Armstrong39413942019-03-15 10:34:03 +08002927 result = get_path_info(get_path_info(path, "dir"), "abspath")
Brett Wilson796ed472018-07-16 15:11:09 -07002928```
[email protected]449f3e42024-08-01 21:43:27 +08002929### <a name="func_get_target_outputs"></a>**get_target_outputs**: [file list] Get the list of outputs from a target.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002930
2931```
2932 get_target_outputs(target_label)
2933
2934 Returns a list of output files for the named target. The named target must
2935 have been previously defined in the current file before this function is
2936 called (it can't reference targets in other files because there isn't a
2937 defined execution order, and it obviously can't reference targets that are
2938 defined after the function call).
2939
Julie Hockettce1fa072019-05-07 17:44:37 -07002940 Only copy, generated_file, and action targets are supported. The outputs from
2941 binary targets will depend on the toolchain definition which won't
2942 necessarily have been loaded by the time a given line of code has run, and
2943 source sets and groups have no useful output file.
Brett Wilson796ed472018-07-16 15:11:09 -07002944```
2945
2946#### **Return value**
2947
2948```
2949 The names in the resulting list will be absolute file paths (normally like
2950 "//out/Debug/bar.exe", depending on the build directory).
2951
Julie Hockettce1fa072019-05-07 17:44:37 -07002952 action, copy, and generated_file targets: this will just return the files
2953 specified in the "outputs" variable of the target.
Brett Wilson796ed472018-07-16 15:11:09 -07002954
2955 action_foreach targets: this will return the result of applying the output
2956 template to the sources (see "gn help source_expansion"). This will be the
2957 same result (though with guaranteed absolute file paths), as
2958 process_file_template will return for those inputs (see "gn help
2959 process_file_template").
2960
Brett Wilson796ed472018-07-16 15:11:09 -07002961 source sets and groups: this will return a list containing the path of the
Takuto Ikuta50ecf4c2024-08-19 18:43:24 +09002962 phony target that Ninja completes once all outputs are generated. This
Brett Wilson796ed472018-07-16 15:11:09 -07002963 probably isn't very useful.
2964```
2965
2966#### **Example**
2967
2968```
2969 # Say this action generates a bunch of C source files.
2970 action_foreach("my_action") {
2971 sources = [ ... ]
2972 outputs = [ ... ]
2973 }
2974
2975 # Compile the resulting source files into a source set.
2976 source_set("my_lib") {
2977 sources = get_target_outputs(":my_action")
2978 }
2979```
[email protected]449f3e42024-08-01 21:43:27 +08002980### <a name="func_getenv"></a>**getenv**: Get an environment variable.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002981
2982```
2983 value = getenv(env_var_name)
2984
2985 Returns the value of the given environment variable. If the value is not
2986 found, it will try to look up the variable with the "opposite" case (based on
2987 the case of the first letter of the variable), but is otherwise
2988 case-sensitive.
2989
2990 If the environment variable is not found, the empty string will be returned.
2991 Note: it might be nice to extend this if we had the concept of "none" in the
2992 language to indicate lookup failure.
2993```
2994
2995#### **Example**
2996
2997```
2998 home_dir = getenv("HOME")
2999```
[email protected]449f3e42024-08-01 21:43:27 +08003000### <a name="func_import"></a>**import**: Import a file into the current scope.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003001
3002```
3003 The import command loads the rules and variables resulting from executing the
3004 given file into the current scope.
3005
3006 By convention, imported files are named with a .gni extension.
3007
3008 An import is different than a C++ "include". The imported file is executed in
3009 a standalone environment from the caller of the import command. The results
3010 of this execution are cached for other files that import the same .gni file.
3011
3012 Note that you can not import a BUILD.gn file that's otherwise used in the
3013 build. Files must either be imported or implicitly loaded as a result of deps
3014 rules, but not both.
3015
3016 The imported file's scope will be merged with the scope at the point import
3017 was called. If there is a conflict (both the current scope and the imported
3018 file define some variable or rule with the same name but different value), a
3019 runtime error will be thrown. Therefore, it's good practice to minimize the
3020 stuff that an imported file defines.
3021
3022 Variables and templates beginning with an underscore '_' are considered
3023 private and will not be imported. Imported files can use such variables for
3024 internal computation without affecting other files.
3025```
3026
3027#### **Examples**
3028
3029```
3030 import("//build/rules/idl_compilation_rule.gni")
3031
3032 # Looks in the current directory.
3033 import("my_vars.gni")
3034```
[email protected]449f3e42024-08-01 21:43:27 +08003035### <a name="func_label_matches"></a>**label_matches**: Returns true if the label matches any of a set of patterns.&nbsp;[Back to Top](#gn-reference)
Aaron Woode05c0aa2024-02-14 13:40:53 -08003036
3037```
3038 label_matches(target_label, patterns)
3039
3040 The argument patterns must be a list of label patterns (see
3041 "gn help label_pattern"). If the target_label matches any of the patterns,
3042 the function returns the value true.
3043```
3044
3045#### **Examples**
3046```
3047 result = label_matches("//baz:bar", [ "//foo/bar/*", "//baz:*" ])
3048 # result will be true
3049```
[email protected]449f3e42024-08-01 21:43:27 +08003050### <a name="func_not_needed"></a>**not_needed**: Mark variables from scope as not needed.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003051
3052```
3053 not_needed(variable_list_or_star, variable_to_ignore_list = [])
3054 not_needed(from_scope, variable_list_or_star,
3055 variable_to_ignore_list = [])
3056
3057 Mark the variables in the current or given scope as not needed, which means
3058 you will not get an error about unused variables for these. The
3059 variable_to_ignore_list allows excluding variables from "all matches" if
3060 variable_list_or_star is "*".
3061```
3062
3063#### **Example**
3064
3065```
3066 not_needed("*", [ "config" ])
3067 not_needed([ "data_deps", "deps" ])
3068 not_needed(invoker, "*", [ "config" ])
3069 not_needed(invoker, [ "data_deps", "deps" ])
3070```
Takuto Ikutadae6a442025-03-05 17:31:58 +09003071### <a name="func_path_exists"></a>**path_exists**: Returns whether the given path exists.&nbsp;[Back to Top](#gn-reference)
Andrew Grievef98b6d72025-02-25 08:54:51 -08003072
3073```
3074 path_exists(path)
Andrew Grievef98b6d72025-02-25 08:54:51 -08003075```
3076
Takuto Ikutadae6a442025-03-05 17:31:58 +09003077#### **Examples**:
Andrew Grievef98b6d72025-02-25 08:54:51 -08003078```
3079 path_exists("//") # true
3080 path_exists("BUILD.gn") # true
3081 path_exists("/abs-non-existent") # false
3082```
[email protected]449f3e42024-08-01 21:43:27 +08003083### <a name="func_pool"></a>**pool**: Defines a pool object.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003084
3085```
3086 Pool objects can be applied to a tool to limit the parallelism of the
3087 build. This object has a single property "depth" corresponding to
3088 the number of tasks that may run simultaneously.
3089
3090 As the file containing the pool definition may be executed in the
3091 context of more than one toolchain it is recommended to specify an
3092 explicit toolchain when defining and referencing a pool.
3093
Julie Hockette2a29402018-07-31 10:11:42 -07003094 A pool named "console" defined in the root build file represents Ninja's
3095 console pool. Targets using this pool will have access to the console's
3096 stdin and stdout, and output will not be buffered. This special pool must
3097 have a depth of 1. Pools not defined in the root must not be named "console".
3098 The console pool can only be defined for the default toolchain.
3099 Refer to the Ninja documentation on the console pool for more info.
3100
Brett Wilson796ed472018-07-16 15:11:09 -07003101 A pool is referenced by its label just like a target.
3102```
3103
3104#### **Variables**
3105
3106```
3107 depth*
3108 * = required
3109```
3110
3111#### **Example**
3112
3113```
3114 if (current_toolchain == default_toolchain) {
3115 pool("link_pool") {
3116 depth = 1
3117 }
3118 }
3119
3120 toolchain("toolchain") {
3121 tool("link") {
3122 command = "..."
Petr Hosekadd1bb12019-09-11 14:39:38 -07003123 pool = ":link_pool($default_toolchain)"
Brett Wilson796ed472018-07-16 15:11:09 -07003124 }
3125 }
3126```
[email protected]449f3e42024-08-01 21:43:27 +08003127### <a name="func_print"></a>**print**: Prints to the console.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003128
3129```
3130 Prints all arguments to the console separated by spaces. A newline is
3131 automatically appended to the end.
3132
3133 This function is intended for debugging. Note that build files are run in
3134 parallel so you may get interleaved prints. A buildfile may also be executed
3135 more than once in parallel in the context of different toolchains so the
3136 prints from one file may be duplicated or
3137 interleaved with itself.
3138```
3139
3140#### **Examples**
3141
3142```
3143 print("Hello world")
3144
3145 print(sources, deps)
3146```
[email protected]449f3e42024-08-01 21:43:27 +08003147### <a name="func_print_stack_trace"></a>**print_stack_trace**: Prints a stack trace.&nbsp;[Back to Top](#gn-reference)
Aaron Wood24062bb2022-04-25 20:37:48 -07003148
3149```
3150 Prints the current file location, and all template invocations that led up to
3151 this location, to the console.
3152```
3153
3154#### **Examples**
3155
3156```
3157 template("foo"){
3158 print_stack_trace()
3159 }
3160 template("bar"){
3161 foo(target_name + ".foo") {
3162 baz = invoker.baz
3163 }
3164 }
3165 bar("lala") {
3166 baz = 42
3167 }
3168
3169 will print out the following:
3170
3171 print_stack_trace() initiated at //build.gn:2
3172 bar("lala") //BUILD.gn:9
3173 foo("lala.foo") //BUILD.gn:5
3174 print_stack_trace() //BUILD.gn:2
3175```
[email protected]449f3e42024-08-01 21:43:27 +08003176### <a name="func_process_file_template"></a>**process_file_template**: Do template expansion over a list of files.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003177
3178```
3179 process_file_template(source_list, template)
3180
3181 process_file_template applies a template list to a source file list,
3182 returning the result of applying each template to each source. This is
3183 typically used for computing output file names from input files.
3184
3185 In most cases, get_target_outputs() will give the same result with shorter,
3186 more maintainable code. This function should only be used when that function
3187 can't be used (like there's no target or the target is defined in another
3188 build file).
3189```
3190
3191#### **Arguments**
3192
3193```
3194 The source_list is a list of file names.
3195
3196 The template can be a string or a list. If it is a list, multiple output
3197 strings are generated for each input.
3198
3199 The template should contain source expansions to which each name in the
3200 source list is applied. See "gn help source_expansion".
3201```
3202
3203#### **Example**
3204
3205```
3206 sources = [
3207 "foo.idl",
3208 "bar.idl",
3209 ]
3210 myoutputs = process_file_template(
3211 sources,
3212 [ "$target_gen_dir/{{source_name_part}}.cc",
3213 "$target_gen_dir/{{source_name_part}}.h" ])
3214
3215 The result in this case will be:
3216 [ "//out/Debug/foo.cc"
3217 "//out/Debug/foo.h"
3218 "//out/Debug/bar.cc"
3219 "//out/Debug/bar.h" ]
3220```
[email protected]449f3e42024-08-01 21:43:27 +08003221### <a name="func_read_file"></a>**read_file**: Read a file into a variable.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003222
3223```
3224 read_file(filename, input_conversion)
3225
3226 Whitespace will be trimmed from the end of the file. Throws an error if the
3227 file can not be opened.
3228```
3229
3230#### **Arguments**
3231
3232```
3233 filename
3234 Filename to read, relative to the build file.
3235
3236 input_conversion
Sylvain Defresne72d5a6e2021-06-15 17:01:32 +02003237 Controls how the file is read and parsed. See `gn help io_conversion`.
Brett Wilson796ed472018-07-16 15:11:09 -07003238```
3239
3240#### **Example**
3241
3242```
3243 lines = read_file("foo.txt", "list lines")
3244```
[email protected]449f3e42024-08-01 21:43:27 +08003245### <a name="func_rebase_path"></a>**rebase_path**: Rebase a file or directory to another location.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003246
3247```
3248 converted = rebase_path(input,
3249 new_base = "",
3250 current_base = ".")
3251
3252 Takes a string argument representing a file name, or a list of such strings
3253 and converts it/them to be relative to a different base directory.
3254
3255 When invoking the compiler or scripts, GN will automatically convert sources
3256 and include directories to be relative to the build directory. However, if
3257 you're passing files directly in the "args" array or doing other manual
3258 manipulations where GN doesn't know something is a file name, you will need
3259 to convert paths to be relative to what your tool is expecting.
3260
3261 The common case is to use this to convert paths relative to the current
3262 directory to be relative to the build directory (which will be the current
3263 directory when executing scripts).
3264
3265 If you want to convert a file path to be source-absolute (that is, beginning
3266 with a double slash like "//foo/bar"), you should use the get_path_info()
3267 function. This function won't work because it will always make relative
3268 paths, and it needs to support making paths relative to the source root, so
Robert Sesekd0a6f072020-05-15 11:21:22 -04003269 it can't also generate source-absolute paths without more special-cases.
Brett Wilson796ed472018-07-16 15:11:09 -07003270```
3271
3272#### **Arguments**
3273
3274```
3275 input
Robert Sesekd0a6f072020-05-15 11:21:22 -04003276 A string or list of strings representing file or directory names. These
Brett Wilson796ed472018-07-16 15:11:09 -07003277 can be relative paths ("foo/bar.txt"), system absolute paths
3278 ("/foo/bar.txt"), or source absolute paths ("//foo/bar.txt").
3279
3280 new_base
3281 The directory to convert the paths to be relative to. This can be an
3282 absolute path or a relative path (which will be treated as being relative
3283 to the current BUILD-file's directory).
3284
3285 As a special case, if new_base is the empty string (the default), all
3286 paths will be converted to system-absolute native style paths with system
3287 path separators. This is useful for invoking external programs.
3288
3289 current_base
3290 Directory representing the base for relative paths in the input. If this
3291 is not an absolute path, it will be treated as being relative to the
3292 current build file. Use "." (the default) to convert paths from the
3293 current BUILD-file's directory.
3294```
3295
3296#### **Return value**
3297
3298```
3299 The return value will be the same type as the input value (either a string or
3300 a list of strings). All relative and source-absolute file names will be
3301 converted to be relative to the requested output System-absolute paths will
3302 be unchanged.
3303
3304 Whether an output path will end in a slash will match whether the
3305 corresponding input path ends in a slash. It will return "." or "./"
3306 (depending on whether the input ends in a slash) to avoid returning empty
3307 strings. This means if you want a root path ("//" or "/") not ending in a
3308 slash, you can add a dot ("//.").
3309```
3310
3311#### **Example**
3312
3313```
3314 # Convert a file in the current directory to be relative to the build
3315 # directory (the current dir when executing compilers and scripts).
3316 foo = rebase_path("myfile.txt", root_build_dir)
3317 # might produce "../../project/myfile.txt".
3318
3319 # Convert a file to be system absolute:
3320 foo = rebase_path("myfile.txt")
3321 # Might produce "D:\\source\\project\\myfile.txt" on Windows or
3322 # "/home/you/source/project/myfile.txt" on Linux.
3323
3324 # Typical usage for converting to the build directory for a script.
3325 action("myscript") {
3326 # Don't convert sources, GN will automatically convert these to be relative
3327 # to the build directory when it constructs the command line for your
3328 # script.
3329 sources = [ "foo.txt", "bar.txt" ]
3330
3331 # Extra file args passed manually need to be explicitly converted
3332 # to be relative to the build directory:
3333 args = [
3334 "--data",
3335 rebase_path("//mything/data/input.dat", root_build_dir),
3336 "--rel",
3337 rebase_path("relative_path.txt", root_build_dir)
3338 ] + rebase_path(sources, root_build_dir)
3339 }
3340```
[email protected]449f3e42024-08-01 21:43:27 +08003341### <a name="func_set_default_toolchain"></a>**set_default_toolchain**: Sets the default toolchain name.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003342
3343```
3344 set_default_toolchain(toolchain_label)
3345
3346 The given label should identify a toolchain definition (see "gn help
3347 toolchain"). This toolchain will be used for all targets unless otherwise
3348 specified.
3349
3350 This function is only valid to call during the processing of the build
3351 configuration file. Since the build configuration file is processed
3352 separately for each toolchain, this function will be a no-op when called
3353 under any non-default toolchains.
3354
3355 For example, the default toolchain should be appropriate for the current
3356 environment. If the current environment is 32-bit and somebody references a
3357 target with a 64-bit toolchain, we wouldn't want processing of the build
3358 config file for the 64-bit toolchain to reset the default toolchain to
3359 64-bit, we want to keep it 32-bits.
3360```
3361
3362#### **Argument**
3363
3364```
3365 toolchain_label
3366 Toolchain name.
3367```
3368
3369#### **Example**
3370
3371```
3372 # Set default toolchain only has an effect when run in the context of the
3373 # default toolchain. Pick the right one according to the current CPU
3374 # architecture.
3375 if (target_cpu == "x64") {
3376 set_default_toolchain("//toolchains:64")
3377 } else if (target_cpu == "x86") {
3378 set_default_toolchain("//toolchains:32")
3379 }
3380```
[email protected]449f3e42024-08-01 21:43:27 +08003381### <a name="func_set_defaults"></a>**set_defaults**: Set default values for a target type.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003382
3383```
3384 set_defaults(<target_type_name>) { <values...> }
3385
3386 Sets the default values for a given target type. Whenever target_type_name is
3387 seen in the future, the values specified in set_default's block will be
3388 copied into the current scope.
3389
3390 When the target type is used, the variable copying is very strict. If a
3391 variable with that name is already in scope, the build will fail with an
3392 error.
3393
3394 set_defaults can be used for built-in target types ("executable",
3395 "shared_library", etc.) and custom ones defined via the "template" command.
3396 It can be called more than once and the most recent call in any scope will
3397 apply, but there is no way to refer to the previous defaults and modify them
3398 (each call to set_defaults must supply a complete list of all defaults it
3399 wants). If you want to share defaults, store them in a separate variable.
3400```
3401
3402#### **Example**
3403
3404```
3405 set_defaults("static_library") {
3406 configs = [ "//tools/mything:settings" ]
3407 }
3408
Nico Webere49cb722018-08-28 13:10:29 -04003409 static_library("mylib") {
Brett Wilson796ed472018-07-16 15:11:09 -07003410 # The configs will be auto-populated as above. You can remove it if
3411 # you don't want the default for a particular default:
3412 configs -= [ "//tools/mything:settings" ]
3413 }
3414```
[email protected]449f3e42024-08-01 21:43:27 +08003415### <a name="func_split_list"></a>**split_list**: Splits a list into N different sub-lists.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003416
3417```
3418 result = split_list(input, n)
3419
3420 Given a list and a number N, splits the list into N sub-lists of
3421 approximately equal size. The return value is a list of the sub-lists. The
3422 result will always be a list of size N. If N is greater than the number of
3423 elements in the input, it will be padded with empty lists.
3424
3425 The expected use is to divide source files into smaller uniform chunks.
3426```
3427
3428#### **Example**
3429
3430```
3431 The code:
3432 mylist = [1, 2, 3, 4, 5, 6]
3433 print(split_list(mylist, 3))
3434
3435 Will print:
3436 [[1, 2], [3, 4], [5, 6]
3437```
[email protected]449f3e42024-08-01 21:43:27 +08003438### <a name="func_string_join"></a>**string_join**: Concatenates a list of strings with a separator.&nbsp;[Back to Top](#gn-reference)
Keir Mierle6ae63302019-11-08 23:02:18 -08003439
3440```
3441 result = string_join(separator, strings)
3442
3443 Concatenate a list of strings with intervening occurrences of separator.
3444```
3445
3446#### **Examples**
3447
3448```
3449 string_join("", ["a", "b", "c"]) --> "abc"
3450 string_join("|", ["a", "b", "c"]) --> "a|b|c"
3451 string_join(", ", ["a", "b", "c"]) --> "a, b, c"
3452 string_join("s", ["", ""]) --> "s"
3453```
[email protected]449f3e42024-08-01 21:43:27 +08003454### <a name="func_string_replace"></a>**string_replace**: Replaces substring in the given string.&nbsp;[Back to Top](#gn-reference)
Petr Hosekc0744ed2018-08-04 16:13:59 -07003455
3456```
3457 result = string_replace(str, old, new[, max])
3458
3459 Returns a copy of the string str in which the occurrences of old have been
3460 replaced with new, optionally restricting the number of replacements. The
3461 replacement is performed sequentially, so if new contains old, it won't be
3462 replaced.
3463```
3464
3465#### **Example**
3466
3467```
3468 The code:
3469 mystr = "Hello, world!"
3470 print(string_replace(mystr, "world", "GN"))
3471
3472 Will print:
3473 Hello, GN!
3474```
[email protected]449f3e42024-08-01 21:43:27 +08003475### <a name="func_string_split"></a>**string_split**: Split string into a list of strings.&nbsp;[Back to Top](#gn-reference)
Keir Mierle6ae63302019-11-08 23:02:18 -08003476
3477```
3478 result = string_split(str[, sep])
3479
3480 Split string into all substrings separated by separator and returns a list
3481 of the substrings between those separators.
3482
3483 If the separator argument is omitted, the split is by any whitespace, and
3484 any leading/trailing whitespace is ignored; similar to Python's str.split().
3485```
3486
3487#### **Examples without a separator (split on whitespace)**:
3488
3489```
3490 string_split("") --> []
3491 string_split("a") --> ["a"]
3492 string_split(" aa bb") --> ["aa", "bb"]
3493```
3494
3495#### **Examples with a separator (split on separators)**:
3496
3497```
3498 string_split("", "|") --> [""]
3499 string_split(" a b ", " ") --> ["", "", "a", "b", "", ""]
3500 string_split("aa+-bb+-c", "+-") --> ["aa", "bb", "c"]
3501```
[email protected]449f3e42024-08-01 21:43:27 +08003502### <a name="func_template"></a>**template**: Define a template rule.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003503
3504```
3505 A template defines a custom name that acts like a function. It provides a way
3506 to add to the built-in target types.
3507
3508 The template() function is used to declare a template. To invoke the
3509 template, just use the name of the template like any other target type.
3510
3511 Often you will want to declare your template in a special file that other
3512 files will import (see "gn help import") so your template rule can be shared
3513 across build files.
3514```
3515
3516#### **Variables and templates**:
3517
3518```
3519 When you call template() it creates a closure around all variables currently
3520 in scope with the code in the template block. When the template is invoked,
3521 the closure will be executed.
3522
3523 When the template is invoked, the code in the caller is executed and passed
3524 to the template code as an implicit "invoker" variable. The template uses
3525 this to read state out of the invoking code.
3526
3527 One thing explicitly excluded from the closure is the "current directory"
3528 against which relative file names are resolved. The current directory will be
3529 that of the invoking code, since typically that code specifies the file
3530 names. This means all files internal to the template should use absolute
3531 names.
3532
3533 A template will typically forward some or all variables from the invoking
3534 scope to a target that it defines. Often, such variables might be optional.
3535 Use the pattern:
3536
3537 if (defined(invoker.deps)) {
3538 deps = invoker.deps
3539 }
3540
3541 The function forward_variables_from() provides a shortcut to forward one or
3542 more or possibly all variables in this manner:
3543
3544 forward_variables_from(invoker, ["deps", "public_deps"])
3545```
3546
3547#### **Target naming**
3548
3549```
3550 Your template should almost always define a built-in target with the name the
3551 template invoker specified. For example, if you have an IDL template and
3552 somebody does:
3553 idl("foo") {...
3554 you will normally want this to expand to something defining a source_set or
3555 static_library named "foo" (among other things you may need). This way, when
3556 another target specifies a dependency on "foo", the static_library or
3557 source_set will be linked.
3558
3559 It is also important that any other targets your template expands to have
3560 unique names, or you will get collisions.
3561
3562 Access the invoking name in your template via the implicit "target_name"
3563 variable. This should also be the basis for how other targets that a template
3564 expands to ensure uniqueness.
3565
3566 A typical example would be a template that defines an action to generate some
3567 source files, and a source_set to compile that source. Your template would
3568 name the source_set "target_name" because that's what you want external
3569 targets to depend on to link your code. And you would name the action
3570 something like "${target_name}_action" to make it unique. The source set
3571 would have a dependency on the action to make it run.
3572```
3573
3574#### **Overriding builtin targets**
3575
3576```
3577 You can use template to redefine a built-in target in which case your template
3578 takes a precedence over the built-in one. All uses of the target from within
3579 the template definition will refer to the built-in target which makes it
3580 possible to extend the behavior of the built-in target:
3581
3582 template("shared_library") {
3583 shared_library(shlib) {
Julie Hockette2a29402018-07-31 10:11:42 -07003584 forward_variables_from(invoker, "*")
Brett Wilson796ed472018-07-16 15:11:09 -07003585 ...
3586 }
3587 }
3588```
3589
3590#### **Example of defining a template**
3591
3592```
3593 template("my_idl") {
3594 # Be nice and help callers debug problems by checking that the variables
3595 # the template requires are defined. This gives a nice message rather than
3596 # giving the user an error about an undefined variable in the file defining
3597 # the template
3598 #
3599 # You can also use defined() to give default values to variables
3600 # unspecified by the invoker.
3601 assert(defined(invoker.sources),
3602 "Need sources in $target_name listing the idl files.")
3603
3604 # Name of the intermediate target that does the code gen. This must
3605 # incorporate the target name so it's unique across template
3606 # instantiations.
3607 code_gen_target_name = target_name + "_code_gen"
3608
3609 # Intermediate target to convert IDL to C source. Note that the name is
3610 # based on the name the invoker of the template specified. This way, each
3611 # time the template is invoked we get a unique intermediate action name
3612 # (since all target names are in the global scope).
3613 action_foreach(code_gen_target_name) {
3614 # Access the scope defined by the invoker via the implicit "invoker"
3615 # variable.
3616 sources = invoker.sources
3617
3618 # Note that we need an absolute path for our script file name. The
3619 # current directory when executing this code will be that of the invoker
3620 # (this is why we can use the "sources" directly above without having to
3621 # rebase all of the paths). But if we need to reference a script relative
3622 # to the template file, we'll need to use an absolute path instead.
3623 script = "//tools/idl/idl_code_generator.py"
3624
3625 # Tell GN how to expand output names given the sources.
3626 # See "gn help source_expansion" for more.
3627 outputs = [ "$target_gen_dir/{{source_name_part}}.cc",
3628 "$target_gen_dir/{{source_name_part}}.h" ]
3629 }
3630
3631 # Name the source set the same as the template invocation so instancing
3632 # this template produces something that other targets can link to in their
3633 # deps.
3634 source_set(target_name) {
3635 # Generates the list of sources, we get these from the action_foreach
3636 # above.
3637 sources = get_target_outputs(":$code_gen_target_name")
3638
3639 # This target depends on the files produced by the above code gen target.
3640 deps = [ ":$code_gen_target_name" ]
3641 }
3642 }
3643```
3644
3645#### **Example of invoking the resulting template**
3646
3647```
3648 # This calls the template code above, defining target_name to be
3649 # "foo_idl_files" and "invoker" to be the set of stuff defined in the curly
3650 # brackets.
3651 my_idl("foo_idl_files") {
3652 # Goes into the template as "invoker.sources".
3653 sources = [ "foo.idl", "bar.idl" ]
3654 }
3655
3656 # Here is a target that depends on our template.
3657 executable("my_exe") {
3658 # Depend on the name we gave the template call above. Internally, this will
3659 # produce a dependency from executable to the source_set inside the
3660 # template (since it has this name), which will in turn depend on the code
3661 # gen action.
3662 deps = [ ":foo_idl_files" ]
3663 }
3664```
[email protected]449f3e42024-08-01 21:43:27 +08003665### <a name="func_tool"></a>**tool**: Specify arguments to a toolchain tool.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003666
3667#### **Usage**
3668
3669```
3670 tool(<tool type>) {
3671 <tool variables...>
3672 }
3673```
3674
3675#### **Tool types**
3676
3677```
3678 Compiler tools:
3679 "cc": C compiler
3680 "cxx": C++ compiler
Sylvain Defresne89e64252020-08-07 13:01:06 +02003681 "cxx_module": C++ compiler used for Clang .modulemap files
Brett Wilson796ed472018-07-16 15:11:09 -07003682 "objc": Objective C compiler
3683 "objcxx": Objective C++ compiler
3684 "rc": Resource compiler (Windows .rc files)
3685 "asm": Assembler
Sylvain Defresne89e64252020-08-07 13:01:06 +02003686 "swift": Swift compiler driver
Brett Wilson796ed472018-07-16 15:11:09 -07003687
3688 Linker tools:
3689 "alink": Linker for static libraries (archives)
3690 "solink": Linker for shared libraries
3691 "link": Linker for executables
3692
3693 Other tools:
3694 "stamp": Tool for creating stamp files
3695 "copy": Tool to copy files.
3696 "action": Defaults for actions
3697
3698 Platform specific tools:
3699 "copy_bundle_data": [iOS, macOS] Tool to copy files in a bundle.
3700 "compile_xcassets": [iOS, macOS] Tool to compile asset catalogs.
Julie Hockettce1fa072019-05-07 17:44:37 -07003701
3702 Rust tools:
Petr Hosek7617b592019-10-02 09:52:21 -07003703 "rust_bin": Tool for compiling Rust binaries
3704 "rust_cdylib": Tool for compiling C-compatible dynamic libraries.
3705 "rust_dylib": Tool for compiling Rust dynamic libraries.
3706 "rust_macro": Tool for compiling Rust procedural macros.
3707 "rust_rlib": Tool for compiling Rust libraries.
3708 "rust_staticlib": Tool for compiling Rust static libraries.
Brett Wilson796ed472018-07-16 15:11:09 -07003709```
3710
3711#### **Tool variables**
3712
3713```
3714 command [string with substitutions]
3715 Valid for: all tools except "action" (required)
3716
3717 The command to run.
3718
Joe Armstrong23d22bc2019-06-28 15:31:03 +08003719 command_launcher [string]
3720 Valid for: all tools except "action" (optional)
3721
3722 The prefix with which to launch the command (e.g. the path to a Goma or
3723 CCache compiler launcher).
3724
3725 Note that this prefix will not be included in the compilation database or
3726 IDE files generated from the build.
3727
Brett Wilson796ed472018-07-16 15:11:09 -07003728 default_output_dir [string with substitutions]
3729 Valid for: linker tools
3730
3731 Default directory name for the output file relative to the
3732 root_build_dir. It can contain other substitution patterns. This will
3733 be the default value for the {{output_dir}} expansion (discussed below)
3734 but will be overridden by the "output_dir" variable in a target, if one
3735 is specified.
3736
3737 GN doesn't do anything with this string other than pass it along,
3738 potentially with target-specific overrides. It is the tool's job to use
3739 the expansion so that the files will be in the right place.
3740
3741 default_output_extension [string]
3742 Valid for: linker tools
3743
3744 Extension for the main output of a linkable tool. It includes the
3745 leading dot. This will be the default value for the
3746 {{output_extension}} expansion (discussed below) but will be overridden
3747 by by the "output extension" variable in a target, if one is specified.
3748 Empty string means no extension.
3749
3750 GN doesn't actually do anything with this extension other than pass it
3751 along, potentially with target-specific overrides. One would typically
3752 use the {{output_extension}} value in the "outputs" to read this value.
3753
3754 Example: default_output_extension = ".exe"
3755
3756 depfile [string with substitutions]
3757 Valid for: compiler tools (optional)
3758
3759 If the tool can write ".d" files, this specifies the name of the
3760 resulting file. These files are used to list header file dependencies
3761 (or other implicit input dependencies) that are discovered at build
3762 time. See also "depsformat".
3763
3764 Example: depfile = "{{output}}.d"
3765
3766 depsformat [string]
3767 Valid for: compiler tools (when depfile is specified)
3768
3769 Format for the deps outputs. This is either "gcc" or "msvc". See the
3770 ninja documentation for "deps" for more information.
3771
3772 Example: depsformat = "gcc"
3773
3774 description [string with substitutions, optional]
3775 Valid for: all tools
3776
3777 What to print when the command is run.
3778
3779 Example: description = "Compiling {{source}}"
3780
Julie Hockettce1fa072019-05-07 17:44:37 -07003781 exe_output_extension [string, optional, rust tools only]
3782 rlib_output_extension [string, optional, rust tools only]
3783 dylib_output_extension [string, optional, rust tools only]
3784 cdylib_output_extension [string, optional, rust tools only]
Petr Hosekfe36c7c2019-11-26 14:38:08 -08003785 rust_proc_macro_output_extension [string, optional, rust tools only]
Julie Hockettce1fa072019-05-07 17:44:37 -07003786 Valid for: Rust tools
3787
3788 These specify the default tool output for each of the crate types.
3789 The default is empty for executables, shared, and static libraries and
3790 ".rlib" for rlibs. Note that the Rust compiler complains with an error
3791 if external crates do not take the form `lib<name>.rlib` or
3792 `lib<name>.<shared_extension>`, where `<shared_extension>` is `.so`,
3793 `.dylib`, or `.dll` as appropriate for the platform.
3794
Brett Wilson796ed472018-07-16 15:11:09 -07003795 lib_switch [string, optional, link tools only]
3796 lib_dir_switch [string, optional, link tools only]
3797 Valid for: Linker tools except "alink"
3798
3799 These strings will be prepended to the libraries and library search
Sylvain Defresnea09ec162020-01-16 12:36:40 +01003800 directories, respectively, because linkers differ on how to specify
3801 them.
3802
Brett Wilson796ed472018-07-16 15:11:09 -07003803 If you specified:
3804 lib_switch = "-l"
3805 lib_dir_switch = "-L"
Sylvain Defresnea09ec162020-01-16 12:36:40 +01003806 then the "{{libs}}" expansion for
3807 [ "freetype", "expat" ]
3808 would be
3809 "-lfreetype -lexpat".
3810
3811 framework_switch [string, optional, link tools only]
Robert Sesekd0a6f072020-05-15 11:21:22 -04003812 weak_framework_switch [string, optional, link tools only]
Sylvain Defresnea09ec162020-01-16 12:36:40 +01003813 framework_dir_switch [string, optional, link tools only]
3814 Valid for: Linker tools
3815
3816 These strings will be prepended to the frameworks and framework search
3817 path directories, respectively, because linkers differ on how to specify
3818 them.
3819
3820 If you specified:
3821 framework_switch = "-framework "
Robert Sesekd0a6f072020-05-15 11:21:22 -04003822 weak_framework_switch = "-weak_framework "
Sylvain Defresnea09ec162020-01-16 12:36:40 +01003823 framework_dir_switch = "-F"
Robert Sesekd0a6f072020-05-15 11:21:22 -04003824 and:
3825 framework_dirs = [ "$root_out_dir" ]
3826 frameworks = [ "UIKit.framework", "Foo.framework" ]
3827 weak_frameworks = [ "MediaPlayer.framework" ]
3828 would be:
3829 "-F. -framework UIKit -framework Foo -weak_framework MediaPlayer"
Brett Wilson796ed472018-07-16 15:11:09 -07003830
Sylvain Defresne89e64252020-08-07 13:01:06 +02003831 swiftmodule_switch [string, optional, link tools only]
3832 Valid for: Linker tools except "alink"
3833
3834 The string will be prependend to the path to the .swiftmodule files
3835 that are embedded in the linker output.
3836
3837 If you specified:
3838 swiftmodule_swift = "-Wl,-add_ast_path,"
3839 then the "{{swiftmodules}}" expansion for
3840 [ "obj/foo/Foo.swiftmodule" ]
3841 would be
3842 "-Wl,-add_ast_path,obj/foo/Foo.swiftmodule"
3843
danakj4fb095d2024-05-30 11:40:51 -04003844 rust_swiftmodule_switch [string, optional, link tools only]
3845 Valid for: Linker tools except "alink"
3846
3847 Like swiftmodule_switch, but for targets built/linked with the Rust
3848 compiler. The string will be prependend to the path to the
3849 .swiftmodule files that are embedded in the linker output.
3850
3851 If you specified:
3852 rust_swiftmodule_swift = "-Clink-arg=-Wl,-add_ast_path,"
3853 then the "{{swiftmodules}}" expansion for
3854 [ "obj/foo/Foo.swiftmodule" ]
3855 would be
3856 "-Clink-arg=-Wl,-add_ast_path,obj/foo/Foo.swiftmodule"
3857
Brett Wilson796ed472018-07-16 15:11:09 -07003858 outputs [list of strings with substitutions]
3859 Valid for: Linker and compiler tools (required)
3860
3861 An array of names for the output files the tool produces. These are
3862 relative to the build output directory. There must always be at least
3863 one output file. There can be more than one output (a linker might
3864 produce a library and an import library, for example).
3865
3866 This array just declares to GN what files the tool will produce. It is
3867 your responsibility to specify the tool command that actually produces
3868 these files.
3869
3870 If you specify more than one output for shared library links, you
3871 should consider setting link_output, depend_output, and
3872 runtime_outputs.
3873
3874 Example for a compiler tool that produces .obj files:
3875 outputs = [
3876 "{{source_out_dir}}/{{source_name_part}}.obj"
3877 ]
3878
3879 Example for a linker tool that produces a .dll and a .lib. The use of
3880 {{target_output_name}}, {{output_extension}} and {{output_dir}} allows
3881 the target to override these values.
3882 outputs = [
Nico Weberad9eab22020-11-15 22:20:28 -05003883 "{{output_dir}}/{{target_output_name}}{{output_extension}}",
Brett Wilson796ed472018-07-16 15:11:09 -07003884 "{{output_dir}}/{{target_output_name}}.lib",
3885 ]
3886
Sylvain Defresne89e64252020-08-07 13:01:06 +02003887 partial_outputs [list of strings with substitutions]
3888 Valid for: "swift" only
3889
3890 An array of names for the partial outputs the tool produces. These
3891 are relative to the build output directory. The expansion will be
3892 evaluated for each file listed in the "sources" of the target.
3893
3894 This is used to deal with whole module optimization, allowing to
3895 list one object file per source file when whole module optimization
3896 is disabled.
3897
Brett Wilson796ed472018-07-16 15:11:09 -07003898 pool [label, optional]
3899 Valid for: all tools (optional)
3900
3901 Label of the pool to use for the tool. Pools are used to limit the
3902 number of tasks that can execute concurrently during the build.
3903
3904 See also "gn help pool".
3905
3906 link_output [string with substitutions]
3907 depend_output [string with substitutions]
David 'Digit' Turnere3d088c2024-08-12 16:36:30 +02003908 Valid for: "solink", "rust_dylib" or "rust_cdylib" only (optional)
Brett Wilson796ed472018-07-16 15:11:09 -07003909
David 'Digit' Turnere3d088c2024-08-12 16:36:30 +02003910 These two files specify which of the outputs from the tool should
3911 be used for linking and dependency tracking. These should match entries
3912 in the "outputs". If unspecified, the first item in the "outputs" array
3913 will be used for all. See "Separate linking and dependencies for shared
3914 libraries" below for more.
Brett Wilson796ed472018-07-16 15:11:09 -07003915
3916 On Windows, where the tools produce a .dll shared library and a .lib
3917 import library, you will want the first two to be the import library
3918 and the third one to be the .dll file. On Linux, if you're not doing
3919 the separate linking/dependency optimization, all of these should be
3920 the .so output.
3921
3922 output_prefix [string]
3923 Valid for: Linker tools (optional)
3924
3925 Prefix to use for the output name. Defaults to empty. This prefix will
3926 be prepended to the name of the target (or the output_name if one is
3927 manually specified for it) if the prefix is not already there. The
3928 result will show up in the {{output_name}} substitution pattern.
3929
3930 Individual targets can opt-out of the output prefix by setting:
3931 output_prefix_override = true
3932 (see "gn help output_prefix_override").
3933
3934 This is typically used to prepend "lib" to libraries on
3935 Posix systems:
3936 output_prefix = "lib"
3937
3938 precompiled_header_type [string]
3939 Valid for: "cc", "cxx", "objc", "objcxx"
3940
3941 Type of precompiled headers. If undefined or the empty string,
3942 precompiled headers will not be used for this tool. Otherwise use "gcc"
3943 or "msvc".
3944
3945 For precompiled headers to be used for a given target, the target (or a
3946 config applied to it) must also specify a "precompiled_header" and, for
3947 "msvc"-style headers, a "precompiled_source" value. If the type is
3948 "gcc", then both "precompiled_header" and "precompiled_source" must
3949 resolve to the same file, despite the different formats required for
3950 each."
3951
3952 See "gn help precompiled_header" for more.
3953
3954 restat [boolean]
3955 Valid for: all tools (optional, defaults to false)
3956
3957 Requests that Ninja check the file timestamp after this tool has run to
3958 determine if anything changed. Set this if your tool has the ability to
3959 skip writing output if the output file has not changed.
3960
3961 Normally, Ninja will assume that when a tool runs the output be new and
Takuto Ikuta60a28b62024-09-05 17:45:42 +09003962 downstream dependents must be rebuild. When this is set to true, Ninja
Brett Wilson796ed472018-07-16 15:11:09 -07003963 can skip rebuilding downstream dependents for input changes that don't
3964 actually affect the output.
3965
3966 Example:
3967 restat = true
3968
3969 rspfile [string with substitutions]
3970 Valid for: all tools except "action" (optional)
3971
3972 Name of the response file. If empty, no response file will be
3973 used. See "rspfile_content".
3974
3975 rspfile_content [string with substitutions]
3976 Valid for: all tools except "action" (required when "rspfile" is used)
3977
3978 The contents to be written to the response file. This may include all
3979 or part of the command to send to the tool which allows you to get
3980 around OS command-line length limits.
3981
3982 This example adds the inputs and libraries to a response file, but
3983 passes the linker flags directly on the command line:
3984 tool("link") {
3985 command = "link -o {{output}} {{ldflags}} @{{output}}.rsp"
3986 rspfile = "{{output}}.rsp"
Adrian Taylorac6cc952020-04-26 20:49:18 -07003987 rspfile_content = "{{inputs}} {{solibs}} {{libs}} {{rlibs}}"
Brett Wilson796ed472018-07-16 15:11:09 -07003988 }
3989
3990 runtime_outputs [string list with substitutions]
3991 Valid for: linker tools
3992
3993 If specified, this list is the subset of the outputs that should be
3994 added to runtime deps (see "gn help runtime_deps"). By default (if
3995 runtime_outputs is empty or unspecified), it will be the link_output.
Adrian Taylor4aa9bdf2021-11-15 19:00:06 -08003996
3997 rust_sysroot
3998 Valid for: Rust tools
3999
4000 A path relative to root_out_dir. This is not used in the build
4001 process, but may be used when generating metadata for rust-analyzer.
4002 (See --export-rust-project). It enables such metadata to include
4003 information about the Rust standard library.
Adrian Taylore3978de2023-05-26 12:07:53 +01004004
4005 dynamic_link_switch
4006 Valid for: Rust tools which link
4007
4008 A switch to be optionally inserted into linker command lines
4009 to indicate that subsequent items may be dynamically linked.
4010 For ld-like linkers, -Clink-arg=-Bdynamic may be a good choice.
4011 This switch is inserted by gn into rustc command lines before
4012 listing any non-Rust dependencies. This may be necessary because
4013 sometimes rustc puts the linker into a mode where it would otherwise
4014 link against static libraries by default. This flag will be
4015 inserted into the {{rustdeps}} variable at the appropriate place;
4016 {{ldflags}} can't be used for the same purpose because the flags
4017 may not be inserted at the desired place in the command line.
Brett Wilson796ed472018-07-16 15:11:09 -07004018```
4019
4020#### **Expansions for tool variables**
4021
4022```
4023 All paths are relative to the root build directory, which is the current
4024 directory for running all tools. These expansions are available to all tools:
4025
4026 {{label}}
4027 The label of the current target. This is typically used in the
4028 "description" field for link tools. The toolchain will be omitted from
4029 the label for targets in the default toolchain, and will be included
4030 for targets in other toolchains.
4031
4032 {{label_name}}
4033 The short name of the label of the target. This is the part after the
4034 colon. For "//foo/bar:baz" this will be "baz". Unlike
4035 {{target_output_name}}, this is not affected by the "output_prefix" in
4036 the tool or the "output_name" set on the target.
4037
Scott Graham501b49a2020-08-05 13:03:37 -07004038 {{label_no_toolchain}}
4039 The label of the current target, never including the toolchain
4040 (otherwise, this is identical to {{label}}). This is used as the module
4041 name when using .modulemap files.
4042
Brett Wilson796ed472018-07-16 15:11:09 -07004043 {{output}}
4044 The relative path and name of the output(s) of the current build step.
4045 If there is more than one output, this will expand to a list of all of
4046 them. Example: "out/base/my_file.o"
4047
4048 {{target_gen_dir}}
4049 {{target_out_dir}}
4050 The directory of the generated file and output directories,
4051 respectively, for the current target. There is no trailing slash. See
4052 also {{output_dir}} for linker tools. Example: "out/base/test"
4053
4054 {{target_output_name}}
4055 The short name of the current target with no path information, or the
4056 value of the "output_name" variable if one is specified in the target.
4057 This will include the "output_prefix" if any. See also {{label_name}}.
4058
4059 Example: "libfoo" for the target named "foo" and an output prefix for
4060 the linker tool of "lib".
4061
4062 Compiler tools have the notion of a single input and a single output, along
4063 with a set of compiler-specific flags. The following expansions are
4064 available:
4065
4066 {{asmflags}}
4067 {{cflags}}
4068 {{cflags_c}}
4069 {{cflags_cc}}
4070 {{cflags_objc}}
4071 {{cflags_objcc}}
4072 {{defines}}
4073 {{include_dirs}}
4074 Strings correspond that to the processed flags/defines/include
4075 directories specified for the target.
4076 Example: "--enable-foo --enable-bar"
4077
4078 Defines will be prefixed by "-D" and include directories will be
4079 prefixed by "-I" (these work with Posix tools as well as Microsoft
4080 ones).
4081
Scott Graham484245b2020-08-11 10:58:50 -07004082 {{module_deps}}
4083 {{module_deps_no_self}}
4084 Strings that correspond to the flags necessary to depend upon the Clang
4085 modules referenced by the current target. The "_no_self" version doesn't
4086 include the module for the current target, and can be used to compile
4087 the pcm itself.
4088
Brett Wilson796ed472018-07-16 15:11:09 -07004089 {{source}}
4090 The relative path and name of the current input file.
4091 Example: "../../base/my_file.cc"
4092
4093 {{source_file_part}}
4094 The file part of the source including the extension (with no directory
4095 information).
4096 Example: "foo.cc"
4097
4098 {{source_name_part}}
4099 The filename part of the source file with no directory or extension.
4100 Example: "foo"
4101
4102 {{source_gen_dir}}
4103 {{source_out_dir}}
4104 The directory in the generated file and output directories,
4105 respectively, for the current input file. If the source file is in the
4106 same directory as the target is declared in, they will will be the same
4107 as the "target" versions above. Example: "gen/base/test"
4108
Julie Hockette2a29402018-07-31 10:11:42 -07004109 Linker tools have multiple inputs and (potentially) multiple outputs. The
Brett Wilson796ed472018-07-16 15:11:09 -07004110 static library tool ("alink") is not considered a linker tool. The following
4111 expansions are available:
4112
4113 {{inputs}}
4114 {{inputs_newline}}
4115 Expands to the inputs to the link step. This will be a list of object
4116 files and static libraries.
4117 Example: "obj/foo.o obj/bar.o obj/somelibrary.a"
4118
4119 The "_newline" version will separate the input files with newlines
4120 instead of spaces. This is useful in response files: some linkers can
4121 take a "-filelist" flag which expects newline separated files, and some
4122 Microsoft tools have a fixed-sized buffer for parsing each line of a
4123 response file.
4124
4125 {{ldflags}}
4126 Expands to the processed set of ldflags and library search paths
4127 specified for the target.
4128 Example: "-m64 -fPIC -pthread -L/usr/local/mylib"
4129
4130 {{libs}}
4131 Expands to the list of system libraries to link to. Each will be
4132 prefixed by the "lib_switch".
4133
Brett Wilson796ed472018-07-16 15:11:09 -07004134 Example: "-lfoo -lbar"
4135
4136 {{output_dir}}
4137 The value of the "output_dir" variable in the target, or the the value
4138 of the "default_output_dir" value in the tool if the target does not
4139 override the output directory. This will be relative to the
4140 root_build_dir and will not end in a slash. Will be "." for output to
4141 the root_build_dir.
4142
4143 This is subtly different than {{target_out_dir}} which is defined by GN
4144 based on the target's path and not overridable. {{output_dir}} is for
4145 the final output, {{target_out_dir}} is generally for object files and
4146 other outputs.
4147
4148 Usually {{output_dir}} would be defined in terms of either
4149 {{target_out_dir}} or {{root_out_dir}}
4150
4151 {{output_extension}}
4152 The value of the "output_extension" variable in the target, or the
4153 value of the "default_output_extension" value in the tool if the target
4154 does not specify an output extension.
4155 Example: ".so"
4156
4157 {{solibs}}
4158 Extra libraries from shared library dependencies not specified in the
4159 {{inputs}}. This is the list of link_output files from shared libraries
David 'Digit' Turnere3d088c2024-08-12 16:36:30 +02004160 (if the solink, rust_dylib and rust_cdylib tools specify a "link_output"
4161 variable separate from the "depend_output").
Brett Wilson796ed472018-07-16 15:11:09 -07004162
4163 These should generally be treated the same as libs by your tool.
4164
4165 Example: "libfoo.so libbar.so"
4166
Adrian Taylorac6cc952020-04-26 20:49:18 -07004167 {{rlibs}}
4168 Any Rust .rlibs which need to be linked into a final C++ target.
4169 These should be treated as {{inputs}} except that sometimes
4170 they might have different linker directives applied.
4171
4172 Example: "obj/foo/libfoo.rlib"
4173
Sylvain Defresnea09ec162020-01-16 12:36:40 +01004174 {{frameworks}}
4175 Shared libraries packaged as framework bundle. This is principally
4176 used on Apple's platforms (macOS and iOS). All name must be ending
4177 with ".framework" suffix; the suffix will be stripped when expanding
Robert Sesekd0a6f072020-05-15 11:21:22 -04004178 {{frameworks}} and each item will be preceded by "-framework" or
4179 "-weak_framework".
Sylvain Defresnea09ec162020-01-16 12:36:40 +01004180
Sylvain Defresne89e64252020-08-07 13:01:06 +02004181 {{swiftmodules}}
4182 Swift .swiftmodule files that needs to be embedded into the binary.
4183 This is necessary to correctly link with object generated by the
4184 Swift compiler (the .swiftmodule file cannot be embedded in object
4185 files directly). Those will be prefixed with "swiftmodule_switch"
4186 value.
4187
Brett Wilson796ed472018-07-16 15:11:09 -07004188 The static library ("alink") tool allows {{arflags}} plus the common tool
4189 substitutions.
4190
4191 The copy tool allows the common compiler/linker substitutions, plus
4192 {{source}} which is the source of the copy. The stamp tool allows only the
4193 common tool substitutions.
4194
4195 The copy_bundle_data and compile_xcassets tools only allows the common tool
4196 substitutions. Both tools are required to create iOS/macOS bundles and need
4197 only be defined on those platforms.
4198
4199 The copy_bundle_data tool will be called with one source and needs to copy
4200 (optionally optimizing the data representation) to its output. It may be
4201 called with a directory as input and it needs to be recursively copied.
4202
4203 The compile_xcassets tool will be called with one or more source (each an
4204 asset catalog) that needs to be compiled to a single output. The following
4205 substitutions are available:
4206
4207 {{inputs}}
4208 Expands to the list of .xcassets to use as input to compile the asset
4209 catalog.
4210
4211 {{bundle_product_type}}
4212 Expands to the product_type of the bundle that will contain the
4213 compiled asset catalog. Usually corresponds to the product_type
4214 property of the corresponding create_bundle target.
4215
4216 {{bundle_partial_info_plist}}
4217 Expands to the path to the partial Info.plist generated by the
4218 assets catalog compiler. Usually based on the target_name of
4219 the create_bundle target.
Julie Hockettce1fa072019-05-07 17:44:37 -07004220
Harley Li0a9affb2020-06-03 10:38:42 -04004221 {{xcasset_compiler_flags}}
4222 Expands to the list of flags specified in corresponding
4223 create_bundle target.
4224
Sylvain Defresne06cdcc82024-03-21 13:48:59 +01004225 The inputs for compile_xcassets tool will be found from the bundle_data
4226 dependencies by looking for any file matching "*/*.xcassets/*" pattern.
4227 The "$assets.xcassets" directory will be added as input to the tool.
4228
Sylvain Defresne89e64252020-08-07 13:01:06 +02004229 The Swift tool has multiple input and outputs. It must have exactly one
4230 output of .swiftmodule type, but can have one or more object file outputs,
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01004231 in addition to other type of outputs. The following expansions are available:
Sylvain Defresne89e64252020-08-07 13:01:06 +02004232
4233 {{module_name}}
4234 Expands to the string representing the module name of target under
4235 compilation (see "module_name" variable).
4236
4237 {{module_dirs}}
4238 Expands to the list of -I<path> for the target Swift module search
4239 path computed from target dependencies.
4240
4241 {{swiftflags}}
4242 Expands to the list of strings representing Swift compiler flags.
4243
Julie Hockettce1fa072019-05-07 17:44:37 -07004244 Rust tools have the notion of a single input and a single output, along
4245 with a set of compiler-specific flags. The following expansions are
4246 available:
4247
4248 {{crate_name}}
4249 Expands to the string representing the crate name of target under
4250 compilation.
4251
4252 {{crate_type}}
4253 Expands to the string representing the type of crate for the target
4254 under compilation.
4255
4256 {{externs}}
4257 Expands to the list of --extern flags needed to include addition Rust
4258 libraries in this target. Includes any specified renamed dependencies.
4259
Julie Hockettce1fa072019-05-07 17:44:37 -07004260 {{rustdeps}}
Takuto Ikutadae6a442025-03-05 17:31:58 +09004261 Expands to the list of -Ldependency=<path> and -Clink-arg=<path> strings
4262 needed to compile this target.
Julie Hockettce1fa072019-05-07 17:44:37 -07004263
4264 {{rustenv}}
4265 Expands to the list of environment variables.
4266
4267 {{rustflags}}
4268 Expands to the list of strings representing Rust compiler flags.
Brett Wilson796ed472018-07-16 15:11:09 -07004269```
4270
4271#### **Separate linking and dependencies for shared libraries**
4272
4273```
4274 Shared libraries are special in that not all changes to them require that
4275 dependent targets be re-linked. If the shared library is changed but no
4276 imports or exports are different, dependent code needn't be relinked, which
4277 can speed up the build.
4278
4279 If your link step can output a list of exports from a shared library and
4280 writes the file only if the new one is different, the timestamp of this file
4281 can be used for triggering re-links, while the actual shared library would be
4282 used for linking.
4283
4284 You will need to specify
4285 restat = true
4286 in the linker tool to make this work, so Ninja will detect if the timestamp
4287 of the dependency file has changed after linking (otherwise it will always
4288 assume that running a command updates the output):
4289
4290 tool("solink") {
4291 command = "..."
4292 outputs = [
4293 "{{output_dir}}/{{target_output_name}}{{output_extension}}",
Nico Weberad9eab22020-11-15 22:20:28 -05004294 "{{output_dir}}/{{target_output_name}}{{output_extension}}.TOC",
Brett Wilson796ed472018-07-16 15:11:09 -07004295 ]
4296 link_output =
4297 "{{output_dir}}/{{target_output_name}}{{output_extension}}"
4298 depend_output =
Nico Weberad9eab22020-11-15 22:20:28 -05004299 "{{output_dir}}/{{target_output_name}}{{output_extension}}.TOC"
Brett Wilson796ed472018-07-16 15:11:09 -07004300 restat = true
4301 }
4302```
4303
4304#### **Example**
4305
4306```
4307 toolchain("my_toolchain") {
4308 # Put these at the top to apply to all tools below.
4309 lib_switch = "-l"
4310 lib_dir_switch = "-L"
4311
4312 tool("cc") {
4313 command = "gcc {{source}} -o {{output}}"
4314 outputs = [ "{{source_out_dir}}/{{source_name_part}}.o" ]
4315 description = "GCC {{source}}"
4316 }
4317 tool("cxx") {
4318 command = "g++ {{source}} -o {{output}}"
4319 outputs = [ "{{source_out_dir}}/{{source_name_part}}.o" ]
4320 description = "G++ {{source}}"
4321 }
4322 };
4323```
[email protected]449f3e42024-08-01 21:43:27 +08004324### <a name="func_toolchain"></a>**toolchain**: Defines a toolchain.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004325
4326```
4327 A toolchain is a set of commands and build flags used to compile the source
4328 code. The toolchain() function defines these commands.
4329```
4330
4331#### **Toolchain overview**
4332
4333```
4334 You can have more than one toolchain in use at once in a build and a target
4335 can exist simultaneously in multiple toolchains. A build file is executed
4336 once for each toolchain it is referenced in so the GN code can vary all
4337 parameters of each target (or which targets exist) on a per-toolchain basis.
4338
4339 When you have a simple build with only one toolchain, the build config file
4340 is loaded only once at the beginning of the build. It must call
4341 set_default_toolchain() (see "gn help set_default_toolchain") to tell GN the
4342 label of the toolchain definition to use. The "toolchain_args" section of the
4343 toolchain definition is ignored.
4344
4345 When a target has a dependency on a target using different toolchain (see "gn
4346 help labels" for how to specify this), GN will start a build using that
4347 secondary toolchain to resolve the target. GN will load the build config file
4348 with the build arguments overridden as specified in the toolchain_args.
4349 Because the default toolchain is already known, calls to
4350 set_default_toolchain() are ignored.
4351
4352 To load a file in an alternate toolchain, GN does the following:
4353
4354 1. Loads the file with the toolchain definition in it (as determined by the
4355 toolchain label).
4356 2. Re-runs the master build configuration file, applying the arguments
4357 specified by the toolchain_args section of the toolchain definition.
4358 3. Loads the destination build file in the context of the configuration file
4359 in the previous step.
4360
4361 The toolchain configuration is two-way. In the default toolchain (i.e. the
4362 main build target) the configuration flows from the build config file to the
4363 toolchain. The build config file looks at the state of the build (OS type,
4364 CPU architecture, etc.) and decides which toolchain to use (via
4365 set_default_toolchain()). In secondary toolchains, the configuration flows
4366 from the toolchain to the build config file: the "toolchain_args" in the
4367 toolchain definition specifies the arguments to re-invoke the build.
4368```
4369
4370#### **Functions and variables**
4371
4372```
4373 tool()
Julie Hockette2a29402018-07-31 10:11:42 -07004374 The tool() function call specifies the commands to run for a given step. See
4375 "gn help tool".
Brett Wilson796ed472018-07-16 15:11:09 -07004376
Julie Hockette2a29402018-07-31 10:11:42 -07004377 toolchain_args [scope]
Brett Wilson796ed472018-07-16 15:11:09 -07004378 Overrides for build arguments to pass to the toolchain when invoking it.
4379 This is a variable of type "scope" where the variable names correspond to
4380 variables in declare_args() blocks.
4381
4382 When you specify a target using an alternate toolchain, the master build
4383 configuration file is re-interpreted in the context of that toolchain.
4384 toolchain_args allows you to control the arguments passed into this
4385 alternate invocation of the build.
4386
4387 Any default system arguments or arguments passed in via "gn args" will also
4388 be passed to the alternate invocation unless explicitly overridden by
4389 toolchain_args.
4390
4391 The toolchain_args will be ignored when the toolchain being defined is the
4392 default. In this case, it's expected you want the default argument values.
4393
4394 See also "gn help buildargs" for an overview of these arguments.
4395
Julie Hockette2a29402018-07-31 10:11:42 -07004396 propagates_configs [boolean, default=false]
4397 Determines whether public_configs and all_dependent_configs in this
4398 toolchain propagate to targets in other toolchains.
4399
4400 When false (the default), this toolchain will not propagate any configs to
4401 targets in other toolchains that depend on it targets inside this
4402 toolchain. This matches the most common usage of toolchains where they
4403 represent different architectures or compilers and the settings that apply
4404 to one won't necessarily apply to others.
4405
4406 When true, configs (public and all-dependent) will cross the boundary out
4407 of this toolchain as if the toolchain boundary wasn't there. This only
4408 affects one direction of dependencies: a toolchain can't control whether
4409 it accepts such configs, only whether it pushes them. The build is
4410 responsible for ensuring that any external targets depending on targets in
4411 this toolchain are compatible with the compiler flags, etc. that may be
4412 propagated.
4413
4414 deps [string list]
Brett Wilson796ed472018-07-16 15:11:09 -07004415 Dependencies of this toolchain. These dependencies will be resolved before
4416 any target in the toolchain is compiled. To avoid circular dependencies
4417 these must be targets defined in another toolchain.
4418
4419 This is expressed as a list of targets, and generally these targets will
4420 always specify a toolchain:
4421 deps = [ "//foo/bar:baz(//build/toolchain:bootstrap)" ]
4422
4423 This concept is somewhat inefficient to express in Ninja (it requires a lot
4424 of duplicate of rules) so should only be used when absolutely necessary.
4425```
4426
4427#### **Example of defining a toolchain**
4428
4429```
4430 toolchain("32") {
4431 tool("cc") {
4432 command = "gcc {{source}}"
4433 ...
4434 }
4435
4436 toolchain_args = {
4437 use_doom_melon = true # Doom melon always required for 32-bit builds.
4438 current_cpu = "x86"
4439 }
4440 }
4441
4442 toolchain("64") {
4443 tool("cc") {
4444 command = "gcc {{source}}"
4445 ...
4446 }
4447
4448 toolchain_args = {
4449 # use_doom_melon is not overridden here, it will take the default.
4450 current_cpu = "x64"
4451 }
4452 }
4453```
4454
4455#### **Example of cross-toolchain dependencies**
4456
4457```
4458 If a 64-bit target wants to depend on a 32-bit binary, it would specify a
4459 dependency using data_deps (data deps are like deps that are only needed at
4460 runtime and aren't linked, since you can't link a 32-bit and a 64-bit
4461 library).
4462
4463 executable("my_program") {
4464 ...
4465 if (target_cpu == "x64") {
4466 # The 64-bit build needs this 32-bit helper.
4467 data_deps = [ ":helper(//toolchains:32)" ]
4468 }
4469 }
4470
4471 if (target_cpu == "x86") {
4472 # Our helper library is only compiled in 32-bits.
4473 shared_library("helper") {
4474 ...
4475 }
4476 }
4477```
[email protected]449f3e42024-08-01 21:43:27 +08004478### <a name="func_write_file"></a>**write_file**: Write a file to disk.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004479
4480```
Julie Hockett09171292018-07-31 14:35:10 -07004481 write_file(filename, data, output_conversion = "")
Brett Wilson796ed472018-07-16 15:11:09 -07004482
4483 If data is a list, the list will be written one-item-per-line with no quoting
4484 or brackets.
4485
4486 If the file exists and the contents are identical to that being written, the
4487 file will not be updated. This will prevent unnecessary rebuilds of targets
4488 that depend on this file.
4489
4490 One use for write_file is to write a list of inputs to an script that might
4491 be too long for the command line. However, it is preferable to use response
4492 files for this purpose. See "gn help response_file_contents".
Brett Wilson796ed472018-07-16 15:11:09 -07004493```
4494
4495#### **Arguments**
4496
4497```
4498 filename
4499 Filename to write. This must be within the output directory.
4500
4501 data
4502 The list or string to write.
Julie Hockett09171292018-07-31 14:35:10 -07004503
4504 output_conversion
Sylvain Defresne72d5a6e2021-06-15 17:01:32 +02004505 Controls how the output is written. See `gn help io_conversion`.
Brett Wilson796ed472018-07-16 15:11:09 -07004506```
4507## <a name="predefined_variables"></a>Built-in predefined variables
4508
[email protected]449f3e42024-08-01 21:43:27 +08004509### <a name="var_current_cpu"></a>**current_cpu**: The processor architecture of the current toolchain.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004510
4511```
4512 The build configuration usually sets this value based on the value of
4513 "host_cpu" (see "gn help host_cpu") and then threads this through the
4514 toolchain definitions to ensure that it always reflects the appropriate
4515 value.
4516
Julie Hockette2a29402018-07-31 10:11:42 -07004517 This value is not used internally by GN for any purpose. It is set to the
Brett Wilson796ed472018-07-16 15:11:09 -07004518 empty string ("") by default but is declared so that it can be overridden on
4519 the command line if so desired.
4520
4521 See "gn help target_cpu" for a list of common values returned.
4522```
[email protected]449f3e42024-08-01 21:43:27 +08004523### <a name="var_current_os"></a>**current_os**: The operating system of the current toolchain.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004524
4525```
4526 The build configuration usually sets this value based on the value of
4527 "target_os" (see "gn help target_os"), and then threads this through the
4528 toolchain definitions to ensure that it always reflects the appropriate
4529 value.
4530
Julie Hockette2a29402018-07-31 10:11:42 -07004531 This value is not used internally by GN for any purpose. It is set to the
Brett Wilson796ed472018-07-16 15:11:09 -07004532 empty string ("") by default but is declared so that it can be overridden on
4533 the command line if so desired.
4534
4535 See "gn help target_os" for a list of common values returned.
4536```
[email protected]449f3e42024-08-01 21:43:27 +08004537### <a name="var_current_toolchain"></a>**current_toolchain**: Label of the current toolchain.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004538
4539```
4540 A fully-qualified label representing the current toolchain. You can use this
4541 to make toolchain-related decisions in the build. See also
4542 "default_toolchain".
4543```
4544
4545#### **Example**
4546
4547```
4548 if (current_toolchain == "//build:64_bit_toolchain") {
4549 executable("output_thats_64_bit_only") {
4550 ...
4551```
[email protected]449f3e42024-08-01 21:43:27 +08004552### <a name="var_default_toolchain"></a>**default_toolchain**: [string] Label of the default toolchain.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004553
4554```
4555 A fully-qualified label representing the default toolchain, which may not
4556 necessarily be the current one (see "current_toolchain").
4557```
[email protected]449f3e42024-08-01 21:43:27 +08004558### <a name="var_gn_version"></a>**gn_version**: [number] The version of gn.&nbsp;[Back to Top](#gn-reference)
James Robinson61377e32020-02-13 15:20:07 -08004559
4560```
Dirk Pranke7f109842025-04-09 16:48:38 -07004561 Corresponds to the number printed by `gn --version`. This variable is
4562 only variable available in the dotfile (all the rest are missing
4563 because the dotfile has to be parsed before args.gn or anything else
4564 is processed).
James Robinson61377e32020-02-13 15:20:07 -08004565```
4566
4567#### **Example**
4568
4569```
4570 assert(gn_version >= 1700, "need GN version 1700 for the frobulate feature")
4571```
[email protected]449f3e42024-08-01 21:43:27 +08004572### <a name="var_host_cpu"></a>**host_cpu**: The processor architecture that GN is running on.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004573
4574```
4575 This is value is exposed so that cross-compile toolchains can access the host
4576 architecture when needed.
4577
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01004578 The value should generally be considered read-only, but it can be overridden
Brett Wilson796ed472018-07-16 15:11:09 -07004579 in order to handle unusual cases where there might be multiple plausible
4580 values for the host architecture (e.g., if you can do either 32-bit or 64-bit
4581 builds). The value is not used internally by GN for any purpose.
4582```
4583
4584#### **Some possible values**
4585
4586```
4587 - "x64"
4588 - "x86"
4589```
[email protected]449f3e42024-08-01 21:43:27 +08004590### <a name="var_host_os"></a>**host_os**: [string] The operating system that GN is running on.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004591
4592```
4593 This value is exposed so that cross-compiles can access the host build
4594 system's settings.
4595
4596 This value should generally be treated as read-only. It, however, is not used
4597 internally by GN for any purpose.
4598```
4599
4600#### **Some possible values**
4601
4602```
4603 - "linux"
4604 - "mac"
4605 - "win"
4606```
[email protected]449f3e42024-08-01 21:43:27 +08004607### <a name="var_invoker"></a>**invoker**: [string] The invoking scope inside a template.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004608
4609```
4610 Inside a template invocation, this variable refers to the scope of the
4611 invoker of the template. Outside of template invocations, this variable is
4612 undefined.
4613
4614 All of the variables defined inside the template invocation are accessible as
4615 members of the "invoker" scope. This is the way that templates read values
4616 set by the callers.
4617
4618 This is often used with "defined" to see if a value is set on the invoking
4619 scope.
4620
4621 See "gn help template" for more examples.
4622```
4623
4624#### **Example**
4625
4626```
4627 template("my_template") {
4628 print(invoker.sources) # Prints [ "a.cc", "b.cc" ]
4629 print(defined(invoker.foo)) # Prints false.
4630 print(defined(invoker.bar)) # Prints true.
4631 }
4632
4633 my_template("doom_melon") {
4634 sources = [ "a.cc", "b.cc" ]
4635 bar = 123
4636 }
4637```
[email protected]449f3e42024-08-01 21:43:27 +08004638### <a name="var_python_path"></a>**python_path**: Absolute path of Python.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004639
4640```
4641 Normally used in toolchain definitions if running some command requires
4642 Python. You will normally not need this when invoking scripts since GN
4643 automatically finds it for you.
4644```
[email protected]449f3e42024-08-01 21:43:27 +08004645### <a name="var_root_build_dir"></a>**root_build_dir**: [string] Directory where build commands are run.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004646
4647```
4648 This is the root build output directory which will be the current directory
4649 when executing all compilers and scripts.
4650
4651 Most often this is used with rebase_path (see "gn help rebase_path") to
4652 convert arguments to be relative to a script's current directory.
4653```
[email protected]449f3e42024-08-01 21:43:27 +08004654### <a name="var_root_gen_dir"></a>**root_gen_dir**: Directory for the toolchain's generated files.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004655
4656```
4657 Absolute path to the root of the generated output directory tree for the
4658 current toolchain. An example would be "//out/Debug/gen" for the default
4659 toolchain, or "//out/Debug/arm/gen" for the "arm" toolchain.
4660
4661 This is primarily useful for setting up include paths for generated files. If
4662 you are passing this to a script, you will want to pass it through
4663 rebase_path() (see "gn help rebase_path") to convert it to be relative to the
4664 build directory.
4665
4666 See also "target_gen_dir" which is usually a better location for generated
4667 files. It will be inside the root generated dir.
4668```
[email protected]449f3e42024-08-01 21:43:27 +08004669### <a name="var_root_out_dir"></a>**root_out_dir**: [string] Root directory for toolchain output files.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004670
4671```
4672 Absolute path to the root of the output directory tree for the current
4673 toolchain. It will not have a trailing slash.
4674
4675 For the default toolchain this will be the same as the root_build_dir. An
4676 example would be "//out/Debug" for the default toolchain, or
4677 "//out/Debug/arm" for the "arm" toolchain.
4678
4679 This is primarily useful for setting up script calls. If you are passing this
4680 to a script, you will want to pass it through rebase_path() (see "gn help
4681 rebase_path") to convert it to be relative to the build directory.
4682
4683 See also "target_out_dir" which is usually a better location for output
4684 files. It will be inside the root output dir.
4685```
4686
4687#### **Example**
4688
4689```
4690 action("myscript") {
4691 # Pass the output dir to the script.
4692 args = [ "-o", rebase_path(root_out_dir, root_build_dir) ]
4693 }
4694```
[email protected]449f3e42024-08-01 21:43:27 +08004695### <a name="var_target_cpu"></a>**target_cpu**: The desired cpu architecture for the build.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004696
4697```
4698 This value should be used to indicate the desired architecture for the
4699 primary objects of the build. It will match the cpu architecture of the
4700 default toolchain, but not necessarily the current toolchain.
4701
4702 In many cases, this is the same as "host_cpu", but in the case of
4703 cross-compiles, this can be set to something different. This value is
4704 different from "current_cpu" in that it does not change based on the current
4705 toolchain. When writing rules, "current_cpu" should be used rather than
4706 "target_cpu" most of the time.
4707
4708 This value is not used internally by GN for any purpose, so it may be set to
4709 whatever value is needed for the build. GN defaults this value to the empty
4710 string ("") and the configuration files should set it to an appropriate value
4711 (e.g., setting it to the value of "host_cpu") if it is not overridden on the
4712 command line or in the args.gn file.
4713```
4714
4715#### **Possible values**
4716
4717```
4718 - "x86"
4719 - "x64"
4720 - "arm"
4721 - "arm64"
4722 - "mipsel"
Tyler Mandry4a648092022-02-15 19:47:09 +00004723 - "mips64el"
4724 - "s390x"
4725 - "ppc64"
4726 - "riscv32"
4727 - "riscv64"
4728 - "e2k"
4729 - "loong64"
Brett Wilson796ed472018-07-16 15:11:09 -07004730```
[email protected]449f3e42024-08-01 21:43:27 +08004731### <a name="var_target_gen_dir"></a>**target_gen_dir**: Directory for a target's generated files.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004732
4733```
4734 Absolute path to the target's generated file directory. This will be the
4735 "root_gen_dir" followed by the relative path to the current build file. If
4736 your file is in "//tools/doom_melon" then target_gen_dir would be
4737 "//out/Debug/gen/tools/doom_melon". It will not have a trailing slash.
4738
4739 This is primarily useful for setting up include paths for generated files. If
4740 you are passing this to a script, you will want to pass it through
4741 rebase_path() (see "gn help rebase_path") to convert it to be relative to the
4742 build directory.
4743
4744 See also "gn help root_gen_dir".
4745```
4746
4747#### **Example**
4748
4749```
4750 action("myscript") {
4751 # Pass the generated output dir to the script.
Nico Weberad9eab22020-11-15 22:20:28 -05004752 args = [ "-o", rebase_path(target_gen_dir, root_build_dir) ]
Brett Wilson796ed472018-07-16 15:11:09 -07004753 }
4754```
[email protected]449f3e42024-08-01 21:43:27 +08004755### <a name="var_target_name"></a>**target_name**: [string] The name of the current target.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004756
4757```
4758 Inside a target or template invocation, this variable refers to the name
4759 given to the target or template invocation. Outside of these, this variable
4760 is undefined.
4761
4762 This is most often used in template definitions to name targets defined in
4763 the template based on the name of the invocation. This is necessary both to
4764 ensure generated targets have unique names and to generate a target with the
4765 exact name of the invocation that other targets can depend on.
4766
4767 Be aware that this value will always reflect the innermost scope. So when
4768 defining a target inside a template, target_name will refer to the target
4769 rather than the template invocation. To get the name of the template
4770 invocation in this case, you should save target_name to a temporary variable
4771 outside of any target definitions.
4772
4773 See "gn help template" for more examples.
4774```
4775
4776#### **Example**
4777
4778```
4779 executable("doom_melon") {
4780 print(target_name) # Prints "doom_melon".
4781 }
4782
4783 template("my_template") {
4784 print(target_name) # Prints "space_ray" when invoked below.
4785
4786 executable(target_name + "_impl") {
4787 print(target_name) # Prints "space_ray_impl".
4788 }
4789 }
4790
4791 my_template("space_ray") {
4792 }
4793```
[email protected]449f3e42024-08-01 21:43:27 +08004794### <a name="var_target_os"></a>**target_os**: The desired operating system for the build.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004795
4796```
4797 This value should be used to indicate the desired operating system for the
4798 primary object(s) of the build. It will match the OS of the default
4799 toolchain.
4800
4801 In many cases, this is the same as "host_os", but in the case of
4802 cross-compiles, it may be different. This variable differs from "current_os"
4803 in that it can be referenced from inside any toolchain and will always return
4804 the initial value.
4805
4806 This should be set to the most specific value possible. So, "android" or
4807 "chromeos" should be used instead of "linux" where applicable, even though
4808 Android and ChromeOS are both Linux variants. This can mean that one needs to
4809 write
4810
4811 if (target_os == "android" || target_os == "linux") {
4812 # ...
4813 }
4814
4815 and so forth.
4816
4817 This value is not used internally by GN for any purpose, so it may be set to
4818 whatever value is needed for the build. GN defaults this value to the empty
4819 string ("") and the configuration files should set it to an appropriate value
4820 (e.g., setting it to the value of "host_os") if it is not set via the command
4821 line or in the args.gn file.
4822```
4823
4824#### **Possible values**
4825
4826```
4827 - "android"
4828 - "chromeos"
4829 - "ios"
4830 - "linux"
4831 - "nacl"
4832 - "mac"
4833 - "win"
4834```
[email protected]449f3e42024-08-01 21:43:27 +08004835### <a name="var_target_out_dir"></a>**target_out_dir**: [string] Directory for target output files.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004836
4837```
4838 Absolute path to the target's generated file directory. If your current
4839 target is in "//tools/doom_melon" then this value might be
4840 "//out/Debug/obj/tools/doom_melon". It will not have a trailing slash.
4841
4842 This is primarily useful for setting up arguments for calling scripts. If you
4843 are passing this to a script, you will want to pass it through rebase_path()
4844 (see "gn help rebase_path") to convert it to be relative to the build
4845 directory.
4846
4847 See also "gn help root_out_dir".
4848```
4849
4850#### **Example**
4851
4852```
4853 action("myscript") {
4854 # Pass the output dir to the script.
Nico Weberad9eab22020-11-15 22:20:28 -05004855 args = [ "-o", rebase_path(target_out_dir, root_build_dir) ]
Brett Wilson796ed472018-07-16 15:11:09 -07004856 }
4857```
4858## <a name="target_variables"></a>Variables you set in targets
4859
[email protected]449f3e42024-08-01 21:43:27 +08004860### <a name="var_aliased_deps"></a>**aliased_deps**: [scope] Set of crate-dependency pairs.&nbsp;[Back to Top](#gn-reference)
Julie Hockettce1fa072019-05-07 17:44:37 -07004861
4862```
4863 Valid for `rust_library` targets and `executable`, `static_library`, and
4864 `shared_library` targets that contain Rust sources.
4865
4866 A scope, each key indicating the renamed crate and the corresponding value
4867 specifying the label of the dependency producing the relevant binary.
4868
4869 All dependencies listed in this field *must* be listed as deps of the target.
4870
4871 executable("foo") {
4872 sources = [ "main.rs" ]
4873 deps = [ "//bar" ]
4874 }
4875
4876 This target would compile the `foo` crate with the following `extern` flag:
4877 `rustc ...command... --extern bar=<build_out_dir>/obj/bar`
4878
4879 executable("foo") {
4880 sources = [ "main.rs" ]
4881 deps = [ ":bar" ]
4882 aliased_deps = {
4883 bar_renamed = ":bar"
4884 }
4885 }
4886
4887 With the addition of `aliased_deps`, above target would instead compile with:
4888 `rustc ...command... --extern bar_renamed=<build_out_dir>/obj/bar`
4889```
[email protected]449f3e42024-08-01 21:43:27 +08004890### <a name="var_all_dependent_configs"></a>**all_dependent_configs**: Configs to be forced on dependents.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004891
4892```
4893 A list of config labels.
4894
4895 All targets depending on this one, and recursively, all targets depending on
4896 those, will have the configs listed in this variable added to them. These
4897 configs will also apply to the current target.
4898
4899 This addition happens in a second phase once a target and all of its
4900 dependencies have been resolved. Therefore, a target will not see these
4901 force-added configs in their "configs" variable while the script is running,
Brett Wilson20806f72024-09-09 10:04:39 -07004902 and they can not be removed.
4903
4904 Use of all_dependent_configs should be avoided when possible.
4905
4906 If your target has include_dirs and defines needed by targets that depend on
4907 it, the correct solution is to add those settings to public_configs and those
4908 targets choose whether to forward them up the dependency tree by whether they
4909 depend on your target via public_deps or not.
4910
4911 There are two recommended uses of this feature:
4912
4913 1. Legacy cases that can't easily be updated to use the proper public deps
4914 and configs.
4915 2. Additional linker flag that need to be set on the final linked target
4916 regardless of whether the dependency path is public or private.
Brett Wilson796ed472018-07-16 15:11:09 -07004917
4918 See also "public_configs".
4919```
4920
4921#### **Ordering of flags and values**
4922
4923```
4924 1. Those set on the current target (not in a config).
4925 2. Those set on the "configs" on the target in order that the
4926 configs appear in the list.
4927 3. Those set on the "all_dependent_configs" on the target in order
4928 that the configs appear in the list.
4929 4. Those set on the "public_configs" on the target in order that
4930 those configs appear in the list.
4931 5. all_dependent_configs pulled from dependencies, in the order of
4932 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01004933 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07004934 6. public_configs pulled from dependencies, in the order of the
4935 "deps" list. If a dependency is public, they will be applied
4936 recursively.
4937```
[email protected]449f3e42024-08-01 21:43:27 +08004938### <a name="var_allow_circular_includes_from"></a>**allow_circular_includes_from**: Permit includes from deps.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004939
4940```
4941 A list of target labels. Must be a subset of the target's "deps". These
4942 targets will be permitted to include headers from the current target despite
4943 the dependency going in the opposite direction.
4944
4945 When you use this, both targets must be included in a final binary for it to
4946 link. To keep linker errors from happening, it is good practice to have all
4947 external dependencies depend only on one of the two targets, and to set the
4948 visibility on the other to enforce this. Thus the targets will always be
4949 linked together in any output.
4950```
4951
4952#### **Details**
4953
4954```
4955 Normally, for a file in target A to include a file from target B, A must list
4956 B as a dependency. This invariant is enforced by the "gn check" command (and
4957 the --check flag to "gn gen" -- see "gn help check").
4958
4959 Sometimes, two targets might be the same unit for linking purposes (two
4960 source sets or static libraries that would always be linked together in a
4961 final executable or shared library) and they each include headers from the
4962 other: you want A to be able to include B's headers, and B to include A's
4963 headers. This is not an ideal situation but is sometimes unavoidable.
4964
4965 This list, if specified, lists which of the dependencies of the current
4966 target can include header files from the current target. That is, if A
4967 depends on B, B can only include headers from A if it is in A's
4968 allow_circular_includes_from list. Normally includes must follow the
4969 direction of dependencies, this flag allows them to go in the opposite
4970 direction.
4971```
4972
4973#### **Danger**
4974
4975```
4976 In the above example, A's headers are likely to include headers from A's
4977 dependencies. Those dependencies may have public_configs that apply flags,
4978 defines, and include paths that make those headers work properly.
4979
4980 With allow_circular_includes_from, B can include A's headers, and
4981 transitively from A's dependencies, without having the dependencies that
4982 would bring in the public_configs those headers need. The result may be
4983 errors or inconsistent builds.
4984
4985 So when you use allow_circular_includes_from, make sure that any compiler
4986 settings, flags, and include directories are the same between both targets
4987 (consider putting such things in a shared config they can both reference).
4988 Make sure the dependencies are also the same (you might consider a group to
4989 collect such dependencies they both depend on).
4990```
4991
4992#### **Example**
4993
4994```
4995 source_set("a") {
4996 deps = [ ":b", ":a_b_shared_deps" ]
4997 allow_circular_includes_from = [ ":b" ]
4998 ...
4999 }
5000
5001 source_set("b") {
5002 deps = [ ":a_b_shared_deps" ]
5003 # Sources here can include headers from a despite lack of deps.
5004 ...
5005 }
5006
5007 group("a_b_shared_deps") {
5008 public_deps = [ ":c" ]
5009 }
5010```
[email protected]449f3e42024-08-01 21:43:27 +08005011### <a name="var_arflags"></a>**arflags**: Arguments passed to static_library archiver.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005012
5013```
5014 A list of flags passed to the archive/lib command that creates static
5015 libraries.
5016
5017 arflags are NOT pushed to dependents, so applying arflags to source sets or
5018 any other target type will be a no-op. As with ldflags, you could put the
5019 arflags in a config and set that as a public or "all dependent" config, but
5020 that will likely not be what you want. If you have a chain of static
5021 libraries dependent on each other, this can cause the flags to propagate up
5022 to other static libraries. Due to the nature of how arflags are typically
5023 used, you will normally want to apply them directly on static_library targets
5024 themselves.
5025```
5026
5027#### **Ordering of flags and values**
5028
5029```
5030 1. Those set on the current target (not in a config).
5031 2. Those set on the "configs" on the target in order that the
5032 configs appear in the list.
5033 3. Those set on the "all_dependent_configs" on the target in order
5034 that the configs appear in the list.
5035 4. Those set on the "public_configs" on the target in order that
5036 those configs appear in the list.
5037 5. all_dependent_configs pulled from dependencies, in the order of
5038 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005039 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005040 6. public_configs pulled from dependencies, in the order of the
5041 "deps" list. If a dependency is public, they will be applied
5042 recursively.
5043```
[email protected]449f3e42024-08-01 21:43:27 +08005044### <a name="var_args"></a>**args**: (target variable) Arguments passed to an action.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005045
5046```
5047 For action and action_foreach targets, args is the list of arguments to pass
5048 to the script. Typically you would use source expansion (see "gn help
5049 source_expansion") to insert the source file names.
5050
Adrian Taylorc0d4f8b2022-03-25 15:05:57 -07005051 Args can also expand the substitution patterns corresponding to config
5052 variables in the same way that compiler tools (see "gn help tool") do. These
5053 allow actions that run compiler or compiler-like tools to access the results
5054 of propagating configs through the build graph. For example:
5055
5056 args = [ "{{defines}}", "{{include_dirs}}", "{{rustenv}}", "--input-file",
5057 "{{source}}" ]
5058
Brett Wilson796ed472018-07-16 15:11:09 -07005059 See also "gn help action" and "gn help action_foreach".
5060```
[email protected]449f3e42024-08-01 21:43:27 +08005061### <a name="var_asmflags"></a>**asmflags**: Flags passed to the assembler.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005062
5063```
5064 A list of strings.
5065
5066 "asmflags" are passed to any invocation of a tool that takes an .asm or .S
5067 file as input.
5068```
5069
5070#### **Ordering of flags and values**
5071
5072```
5073 1. Those set on the current target (not in a config).
5074 2. Those set on the "configs" on the target in order that the
5075 configs appear in the list.
5076 3. Those set on the "all_dependent_configs" on the target in order
5077 that the configs appear in the list.
5078 4. Those set on the "public_configs" on the target in order that
5079 those configs appear in the list.
5080 5. all_dependent_configs pulled from dependencies, in the order of
5081 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005082 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005083 6. public_configs pulled from dependencies, in the order of the
5084 "deps" list. If a dependency is public, they will be applied
5085 recursively.
5086```
[email protected]449f3e42024-08-01 21:43:27 +08005087### <a name="var_assert_no_deps"></a>**assert_no_deps**: Ensure no deps on these targets.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005088
5089```
5090 A list of label patterns.
5091
5092 This list is a list of patterns that must not match any of the transitive
5093 dependencies of the target. These include all public, private, and data
5094 dependencies, and cross shared library boundaries. This allows you to express
5095 that undesirable code isn't accidentally added to downstream dependencies in
5096 a way that might otherwise be difficult to notice.
5097
5098 Checking does not cross executable boundaries. If a target depends on an
5099 executable, it's assumed that the executable is a tool that is producing part
5100 of the build rather than something that is linked and distributed. This
5101 allows assert_no_deps to express what is distributed in the final target
5102 rather than depend on the internal build steps (which may include
5103 non-distributable code).
5104
5105 See "gn help label_pattern" for the format of the entries in the list. These
5106 patterns allow blacklisting individual targets or whole directory
5107 hierarchies.
5108
5109 Sometimes it is desirable to enforce that many targets have no dependencies
5110 on a target or set of targets. One efficient way to express this is to create
5111 a group with the assert_no_deps rule on it, and make that group depend on all
5112 targets you want to apply that assertion to.
5113```
5114
5115#### **Example**
5116
5117```
5118 executable("doom_melon") {
5119 deps = [ "//foo:bar" ]
5120 ...
5121 assert_no_deps = [
5122 "//evil/*", # Don't link any code from the evil directory.
5123 "//foo:test_support", # This target is also disallowed.
5124 ]
5125 }
5126```
[email protected]449f3e42024-08-01 21:43:27 +08005127### <a name="var_bridge_header"></a>**bridge_header**: [string] Path to C/Objective-C compatibility header.&nbsp;[Back to Top](#gn-reference)
Sylvain Defresne89e64252020-08-07 13:01:06 +02005128
5129```
5130 Valid for binary targets that contain Swift sources.
5131
5132 Path to an header that includes C/Objective-C functions and types that
5133 needs to be made available to the Swift module.
5134```
[email protected]449f3e42024-08-01 21:43:27 +08005135### <a name="var_bundle_contents_dir"></a>**bundle_contents_dir**: Expansion of {{bundle_contents_dir}} in&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005136```
5137 create_bundle.
5138
5139 A string corresponding to a path in $root_build_dir.
5140
5141 This string is used by the "create_bundle" target to expand the
5142 {{bundle_contents_dir}} of the "bundle_data" target it depends on. This must
5143 correspond to a path under "bundle_root_dir".
5144
5145 See "gn help bundle_root_dir" for examples.
5146```
[email protected]449f3e42024-08-01 21:43:27 +08005147### <a name="var_bundle_deps_filter"></a>**bundle_deps_filter**: [label list] A list of labels that are filtered out.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005148
5149```
5150 A list of target labels.
5151
5152 This list contains target label patterns that should be filtered out when
5153 creating the bundle. Any target matching one of those label will be removed
5154 from the dependencies of the create_bundle target.
5155
5156 This is mostly useful when creating application extension bundle as the
5157 application extension has access to runtime resources from the application
5158 bundle and thus do not require a second copy.
5159
5160 See "gn help create_bundle" for more information.
5161```
5162
5163#### **Example**
5164
5165```
5166 create_bundle("today_extension") {
5167 deps = [
5168 "//base"
5169 ]
5170 bundle_root_dir = "$root_out_dir/today_extension.appex"
5171 bundle_deps_filter = [
5172 # The extension uses //base but does not use any function calling into
5173 # third_party/icu and thus does not need the icudtl.dat file.
5174 "//third_party/icu:icudata",
5175 ]
5176 }
5177```
[email protected]449f3e42024-08-01 21:43:27 +08005178### <a name="var_bundle_executable_dir"></a>**bundle_executable_dir**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005179
Joe Armstrongb199e542019-03-21 09:40:08 +08005180```
Sylvain Defresned46f92f2019-04-03 16:14:29 +02005181 bundle_executable_dir: Expansion of {{bundle_executable_dir}} in
5182 create_bundle.
5183
Brett Wilson796ed472018-07-16 15:11:09 -07005184 A string corresponding to a path in $root_build_dir.
5185
5186 This string is used by the "create_bundle" target to expand the
5187 {{bundle_executable_dir}} of the "bundle_data" target it depends on. This
5188 must correspond to a path under "bundle_root_dir".
5189
5190 See "gn help bundle_root_dir" for examples.
5191```
[email protected]449f3e42024-08-01 21:43:27 +08005192### <a name="var_bundle_resources_dir"></a>**bundle_resources_dir**&nbsp;[Back to Top](#gn-reference)
Joe Armstrongb199e542019-03-21 09:40:08 +08005193
Brett Wilson796ed472018-07-16 15:11:09 -07005194```
Sylvain Defresned46f92f2019-04-03 16:14:29 +02005195 bundle_resources_dir: Expansion of {{bundle_resources_dir}} in
5196 create_bundle.
Brett Wilson796ed472018-07-16 15:11:09 -07005197
5198 A string corresponding to a path in $root_build_dir.
5199
5200 This string is used by the "create_bundle" target to expand the
5201 {{bundle_resources_dir}} of the "bundle_data" target it depends on. This must
5202 correspond to a path under "bundle_root_dir".
5203
5204 See "gn help bundle_root_dir" for examples.
5205```
[email protected]449f3e42024-08-01 21:43:27 +08005206### <a name="var_bundle_root_dir"></a>**bundle_root_dir**: Expansion of {{bundle_root_dir}} in create_bundle.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005207
5208```
5209 A string corresponding to a path in root_build_dir.
5210
5211 This string is used by the "create_bundle" target to expand the
5212 {{bundle_root_dir}} of the "bundle_data" target it depends on. This must
5213 correspond to a path under root_build_dir.
5214```
5215
5216#### **Example**
5217
5218```
5219 bundle_data("info_plist") {
5220 sources = [ "Info.plist" ]
5221 outputs = [ "{{bundle_contents_dir}}/Info.plist" ]
5222 }
5223
5224 create_bundle("doom_melon.app") {
5225 deps = [ ":info_plist" ]
5226 bundle_root_dir = "${root_build_dir}/doom_melon.app"
5227 bundle_contents_dir = "${bundle_root_dir}/Contents"
5228 bundle_resources_dir = "${bundle_contents_dir}/Resources"
5229 bundle_executable_dir = "${bundle_contents_dir}/MacOS"
Brett Wilson796ed472018-07-16 15:11:09 -07005230 }
5231```
[email protected]449f3e42024-08-01 21:43:27 +08005232### <a name="var_cflags"></a>**cflags***: Flags passed to the C compiler.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005233
5234```
5235 A list of strings.
5236
5237 "cflags" are passed to all invocations of the C, C++, Objective C, and
5238 Objective C++ compilers.
5239
5240 To target one of these variants individually, use "cflags_c", "cflags_cc",
5241 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5242 versions of cflags* will be appended on the compiler command line after
5243 "cflags".
5244
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005245 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5246 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005247```
5248
5249#### **Ordering of flags and values**
5250
5251```
5252 1. Those set on the current target (not in a config).
5253 2. Those set on the "configs" on the target in order that the
5254 configs appear in the list.
5255 3. Those set on the "all_dependent_configs" on the target in order
5256 that the configs appear in the list.
5257 4. Those set on the "public_configs" on the target in order that
5258 those configs appear in the list.
5259 5. all_dependent_configs pulled from dependencies, in the order of
5260 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005261 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005262 6. public_configs pulled from dependencies, in the order of the
5263 "deps" list. If a dependency is public, they will be applied
5264 recursively.
5265```
[email protected]449f3e42024-08-01 21:43:27 +08005266### <a name="var_cflags_c"></a>**cflags***: Flags passed to the C compiler.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005267
5268```
5269 A list of strings.
5270
5271 "cflags" are passed to all invocations of the C, C++, Objective C, and
5272 Objective C++ compilers.
5273
5274 To target one of these variants individually, use "cflags_c", "cflags_cc",
5275 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5276 versions of cflags* will be appended on the compiler command line after
5277 "cflags".
5278
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005279 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5280 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005281```
5282
5283#### **Ordering of flags and values**
5284
5285```
5286 1. Those set on the current target (not in a config).
5287 2. Those set on the "configs" on the target in order that the
5288 configs appear in the list.
5289 3. Those set on the "all_dependent_configs" on the target in order
5290 that the configs appear in the list.
5291 4. Those set on the "public_configs" on the target in order that
5292 those configs appear in the list.
5293 5. all_dependent_configs pulled from dependencies, in the order of
5294 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005295 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005296 6. public_configs pulled from dependencies, in the order of the
5297 "deps" list. If a dependency is public, they will be applied
5298 recursively.
5299```
[email protected]449f3e42024-08-01 21:43:27 +08005300### <a name="var_cflags_cc"></a>**cflags***: Flags passed to the C compiler.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005301
5302```
5303 A list of strings.
5304
5305 "cflags" are passed to all invocations of the C, C++, Objective C, and
5306 Objective C++ compilers.
5307
5308 To target one of these variants individually, use "cflags_c", "cflags_cc",
5309 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5310 versions of cflags* will be appended on the compiler command line after
5311 "cflags".
5312
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005313 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5314 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005315```
5316
5317#### **Ordering of flags and values**
5318
5319```
5320 1. Those set on the current target (not in a config).
5321 2. Those set on the "configs" on the target in order that the
5322 configs appear in the list.
5323 3. Those set on the "all_dependent_configs" on the target in order
5324 that the configs appear in the list.
5325 4. Those set on the "public_configs" on the target in order that
5326 those configs appear in the list.
5327 5. all_dependent_configs pulled from dependencies, in the order of
5328 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005329 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005330 6. public_configs pulled from dependencies, in the order of the
5331 "deps" list. If a dependency is public, they will be applied
5332 recursively.
5333```
[email protected]449f3e42024-08-01 21:43:27 +08005334### <a name="var_cflags_objc"></a>**cflags***: Flags passed to the C compiler.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005335
5336```
5337 A list of strings.
5338
5339 "cflags" are passed to all invocations of the C, C++, Objective C, and
5340 Objective C++ compilers.
5341
5342 To target one of these variants individually, use "cflags_c", "cflags_cc",
5343 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5344 versions of cflags* will be appended on the compiler command line after
5345 "cflags".
5346
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005347 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5348 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005349```
5350
5351#### **Ordering of flags and values**
5352
5353```
5354 1. Those set on the current target (not in a config).
5355 2. Those set on the "configs" on the target in order that the
5356 configs appear in the list.
5357 3. Those set on the "all_dependent_configs" on the target in order
5358 that the configs appear in the list.
5359 4. Those set on the "public_configs" on the target in order that
5360 those configs appear in the list.
5361 5. all_dependent_configs pulled from dependencies, in the order of
5362 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005363 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005364 6. public_configs pulled from dependencies, in the order of the
5365 "deps" list. If a dependency is public, they will be applied
5366 recursively.
5367```
[email protected]449f3e42024-08-01 21:43:27 +08005368### <a name="var_cflags_objcc"></a>**cflags***: Flags passed to the C compiler.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005369
5370```
5371 A list of strings.
5372
5373 "cflags" are passed to all invocations of the C, C++, Objective C, and
5374 Objective C++ compilers.
5375
5376 To target one of these variants individually, use "cflags_c", "cflags_cc",
5377 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5378 versions of cflags* will be appended on the compiler command line after
5379 "cflags".
5380
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005381 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5382 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005383```
5384
5385#### **Ordering of flags and values**
5386
5387```
5388 1. Those set on the current target (not in a config).
5389 2. Those set on the "configs" on the target in order that the
5390 configs appear in the list.
5391 3. Those set on the "all_dependent_configs" on the target in order
5392 that the configs appear in the list.
5393 4. Those set on the "public_configs" on the target in order that
5394 those configs appear in the list.
5395 5. all_dependent_configs pulled from dependencies, in the order of
5396 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005397 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005398 6. public_configs pulled from dependencies, in the order of the
5399 "deps" list. If a dependency is public, they will be applied
5400 recursively.
5401```
[email protected]449f3e42024-08-01 21:43:27 +08005402### <a name="var_check_includes"></a>**check_includes**: [boolean] Controls whether a target's files are checked.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005403
5404```
5405 When true (the default), the "gn check" command (as well as "gn gen" with the
5406 --check flag) will check this target's sources and headers for proper
5407 dependencies.
5408
5409 When false, the files in this target will be skipped by default. This does
5410 not affect other targets that depend on the current target, it just skips
5411 checking the includes of the current target's files.
5412
5413 If there are a few conditionally included headers that trip up checking, you
5414 can exclude headers individually by annotating them with "nogncheck" (see "gn
5415 help nogncheck").
5416
5417 The topic "gn help check" has general information on how checking works and
5418 advice on how to pass a check in problematic cases.
5419```
5420
5421#### **Example**
5422
5423```
5424 source_set("busted_includes") {
5425 # This target's includes are messed up, exclude it from checking.
5426 check_includes = false
5427 ...
5428 }
5429```
[email protected]449f3e42024-08-01 21:43:27 +08005430### <a name="var_complete_static_lib"></a>**complete_static_lib**: [boolean] Links all deps into a static library.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005431
5432```
5433 A static library normally doesn't include code from dependencies, but instead
5434 forwards the static libraries and source sets in its deps up the dependency
5435 chain until a linkable target (an executable or shared library) is reached.
5436 The final linkable target only links each static library once, even if it
5437 appears more than once in its dependency graph.
5438
5439 In some cases the static library might be the final desired output. For
5440 example, you may be producing a static library for distribution to third
5441 parties. In this case, the static library should include code for all
5442 dependencies in one complete package. However, complete static libraries
5443 themselves are never linked into other complete static libraries. All
5444 complete static libraries are for distribution and linking them in would
5445 cause code duplication in this case. If the static library is not for
5446 distribution, it should not be complete.
5447
5448 GN treats non-complete static libraries as source sets when they are linked
5449 into complete static libraries. This is done because some tools like AR do
5450 not handle dependent static libraries properly. This makes it easier to write
5451 "alink" rules.
5452
5453 In rare cases it makes sense to list a header in more than one target if it
5454 could be considered conceptually a member of both. libraries.
5455```
5456
5457#### **Example**
5458
5459```
5460 static_library("foo") {
5461 complete_static_lib = true
5462 deps = [ "bar" ]
5463 }
5464```
[email protected]449f3e42024-08-01 21:43:27 +08005465### <a name="var_configs"></a>**configs**: Configs applying to this target or config.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005466
5467```
5468 A list of config labels.
5469```
5470
5471#### **Configs on a target**
5472
5473```
5474 When used on a target, the include_dirs, defines, etc. in each config are
5475 appended in the order they appear to the compile command for each file in the
5476 target. They will appear after the include_dirs, defines, etc. that the
5477 target sets directly.
5478
5479 Since configs apply after the values set on a target, directly setting a
5480 compiler flag will prepend it to the command line. If you want to append a
5481 flag instead, you can put that flag in a one-off config and append that
5482 config to the target's configs list.
5483
5484 The build configuration script will generally set up the default configs
5485 applying to a given target type (see "set_defaults"). When a target is being
5486 defined, it can add to or remove from this list.
5487```
5488
5489#### **Configs on a config**
5490
5491```
5492 It is possible to create composite configs by specifying configs on a config.
5493 One might do this to forward values, or to factor out blocks of settings from
5494 very large configs into more manageable named chunks.
5495
5496 In this case, the composite config is expanded to be the concatenation of its
5497 own values, and in order, the values from its sub-configs *before* anything
5498 else happens. This has some ramifications:
5499
5500 - A target has no visibility into a config's sub-configs. Target code only
5501 sees the name of the composite config. It can't remove sub-configs or opt
5502 in to only parts of it. The composite config may not even be defined
5503 before the target is.
5504
5505 - You can get duplication of values if a config is listed twice, say, on a
5506 target and in a sub-config that also applies. In other cases, the configs
5507 applying to a target are de-duped. It's expected that if a config is
5508 listed as a sub-config that it is only used in that context. (Note that
5509 it's possible to fix this and de-dupe, but it's not normally relevant and
5510 complicates the implementation.)
5511```
5512
5513#### **Ordering of flags and values**
5514
5515```
5516 1. Those set on the current target (not in a config).
5517 2. Those set on the "configs" on the target in order that the
5518 configs appear in the list.
5519 3. Those set on the "all_dependent_configs" on the target in order
5520 that the configs appear in the list.
5521 4. Those set on the "public_configs" on the target in order that
5522 those configs appear in the list.
5523 5. all_dependent_configs pulled from dependencies, in the order of
5524 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005525 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005526 6. public_configs pulled from dependencies, in the order of the
5527 "deps" list. If a dependency is public, they will be applied
5528 recursively.
5529```
5530
5531#### **Example**
5532
5533```
5534 # Configs on a target.
5535 source_set("foo") {
5536 # Don't use the default RTTI config that BUILDCONFIG applied to us.
5537 configs -= [ "//build:no_rtti" ]
5538
5539 # Add some of our own settings.
5540 configs += [ ":mysettings" ]
5541 }
5542
5543 # Create a default_optimization config that forwards to one of a set of more
5544 # specialized configs depending on build flags. This pattern is useful
5545 # because it allows a target to opt in to either a default set, or a more
5546 # specific set, while avoid duplicating the settings in two places.
5547 config("super_optimization") {
5548 cflags = [ ... ]
5549 }
5550 config("default_optimization") {
5551 if (optimize_everything) {
5552 configs = [ ":super_optimization" ]
5553 } else {
5554 configs = [ ":no_optimization" ]
5555 }
5556 }
5557```
[email protected]449f3e42024-08-01 21:43:27 +08005558### <a name="var_contents"></a>**contents**: Contents to write to file.&nbsp;[Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08005559
5560```
5561 The contents of the file for a generated_file target.
5562 See "gn help generated_file".
5563```
[email protected]449f3e42024-08-01 21:43:27 +08005564### <a name="var_crate_name"></a>**crate_name**: [string] The name for the compiled crate.&nbsp;[Back to Top](#gn-reference)
Julie Hockettce1fa072019-05-07 17:44:37 -07005565
5566```
5567 Valid for `rust_library` targets and `executable`, `static_library`,
5568 `shared_library`, and `source_set` targets that contain Rust sources.
5569
5570 If crate_name is not set, then this rule will use the target name.
5571```
[email protected]449f3e42024-08-01 21:43:27 +08005572### <a name="var_crate_root"></a>**crate_root**: [string] The root source file for a binary or library.&nbsp;[Back to Top](#gn-reference)
Julie Hockettce1fa072019-05-07 17:44:37 -07005573
5574```
5575 Valid for `rust_library` targets and `executable`, `static_library`,
5576 `shared_library`, and `source_set` targets that contain Rust sources.
5577
5578 This file is usually the `main.rs` or `lib.rs` for binaries and libraries,
5579 respectively.
5580
5581 If crate_root is not set, then this rule will look for a lib.rs file (or
5582 main.rs for executable) or a single file in sources, if sources contains
5583 only one file.
5584```
[email protected]449f3e42024-08-01 21:43:27 +08005585### <a name="var_crate_type"></a>**crate_type**: [string] The type of linkage to use on a shared_library.&nbsp;[Back to Top](#gn-reference)
Julie Hockettce1fa072019-05-07 17:44:37 -07005586
5587```
5588 Valid for `rust_library` targets and `executable`, `static_library`,
5589 `shared_library`, and `source_set` targets that contain Rust sources.
5590
5591 Options for this field are "cdylib", "staticlib", "proc-macro", and "dylib".
5592 This field sets the `crate-type` attribute for the `rustc` tool on static
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005593 libraries, as well as the appropriate output extension in the
Julie Hockettce1fa072019-05-07 17:44:37 -07005594 `rust_output_extension` attribute. Since outputs must be explicit, the `lib`
5595 crate type (where the Rust compiler produces what it thinks is the
5596 appropriate library type) is not supported.
5597
5598 It should be noted that the "dylib" crate type in Rust is unstable in the set
5599 of symbols it exposes, and most usages today are potentially wrong and will
5600 be broken in the future.
5601
5602 Static libraries, rust libraries, and executables have this field set
5603 automatically.
5604```
[email protected]449f3e42024-08-01 21:43:27 +08005605### <a name="var_data"></a>**data**: Runtime data file dependencies.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005606
5607```
5608 Lists files or directories required to run the given target. These are
5609 typically data files or directories of data files. The paths are interpreted
5610 as being relative to the current build file. Since these are runtime
5611 dependencies, they do not affect which targets are built or when. To declare
5612 input files to a script, use "inputs".
5613
5614 Appearing in the "data" section does not imply any special handling such as
5615 copying them to the output directory. This is just used for declaring runtime
5616 dependencies. Runtime dependencies can be queried using the "runtime_deps"
5617 category of "gn desc" or written during build generation via
5618 "--runtime-deps-list-file".
5619
5620 GN doesn't require data files to exist at build-time. So actions that produce
5621 files that are in turn runtime dependencies can list those generated files
5622 both in the "outputs" list as well as the "data" list.
5623
5624 By convention, directories are listed with a trailing slash:
5625 data = [ "test/data/" ]
5626 However, no verification is done on these so GN doesn't enforce this. The
5627 paths are just rebased and passed along when requested.
5628
5629 Note: On iOS and macOS, create_bundle targets will not be recursed into when
5630 gathering data. See "gn help create_bundle" for details.
5631
5632 See "gn help runtime_deps" for how these are used.
5633```
[email protected]449f3e42024-08-01 21:43:27 +08005634### <a name="var_data_deps"></a>**data_deps**: Non-linked dependencies.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005635
5636```
5637 A list of target labels.
5638
5639 Specifies dependencies of a target that are not actually linked into the
5640 current target. Such dependencies will be built and will be available at
5641 runtime.
5642
5643 This is normally used for things like plugins or helper programs that a
5644 target needs at runtime.
5645
5646 Note: On iOS and macOS, create_bundle targets will not be recursed into when
5647 gathering data_deps. See "gn help create_bundle" for details.
5648
5649 See also "gn help deps" and "gn help data".
5650```
5651
5652#### **Example**
5653
5654```
5655 executable("foo") {
5656 deps = [ "//base" ]
5657 data_deps = [ "//plugins:my_runtime_plugin" ]
5658 }
5659```
[email protected]449f3e42024-08-01 21:43:27 +08005660### <a name="var_data_keys"></a>**data_keys**: Keys from which to collect metadata.&nbsp;[Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08005661
5662```
5663 These keys are used to identify metadata to collect. If a walked target
5664 defines this key in its metadata, its value will be appended to the resulting
5665 collection.
5666
5667 See "gn help generated_file".
5668```
[email protected]449f3e42024-08-01 21:43:27 +08005669### <a name="var_defines"></a>**defines**: C preprocessor defines.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005670
5671```
5672 A list of strings
5673
5674 These strings will be passed to the C/C++ compiler as #defines. The strings
5675 may or may not include an "=" to assign a value.
5676```
5677
5678#### **Ordering of flags and values**
5679
5680```
5681 1. Those set on the current target (not in a config).
5682 2. Those set on the "configs" on the target in order that the
5683 configs appear in the list.
5684 3. Those set on the "all_dependent_configs" on the target in order
5685 that the configs appear in the list.
5686 4. Those set on the "public_configs" on the target in order that
5687 those configs appear in the list.
5688 5. all_dependent_configs pulled from dependencies, in the order of
5689 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005690 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005691 6. public_configs pulled from dependencies, in the order of the
5692 "deps" list. If a dependency is public, they will be applied
5693 recursively.
5694```
5695
5696#### **Example**
5697
5698```
5699 defines = [ "AWESOME_FEATURE", "LOG_LEVEL=3" ]
5700```
[email protected]449f3e42024-08-01 21:43:27 +08005701### <a name="var_depfile"></a>**depfile**: [string] File name for input dependencies for actions.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005702
5703```
5704 If nonempty, this string specifies that the current action or action_foreach
5705 target will generate the given ".d" file containing the dependencies of the
5706 input. Empty or unset means that the script doesn't generate the files.
5707
5708 A depfile should be used only when a target depends on files that are not
5709 already specified by a target's inputs and sources. Likewise, depfiles should
5710 specify only those dependencies not already included in sources or inputs.
5711
5712 The .d file should go in the target output directory. If you have more than
5713 one source file that the script is being run over, you can use the output
5714 file expansions described in "gn help action_foreach" to name the .d file
Nico Weberad9eab22020-11-15 22:20:28 -05005715 according to the input.
Brett Wilson796ed472018-07-16 15:11:09 -07005716
5717 The format is that of a Makefile and all paths must be relative to the root
5718 build directory. Only one output may be listed and it must match the first
5719 output of the action.
5720
5721 Although depfiles are created by an action, they should not be listed in the
5722 action's "outputs" unless another target will use the file as an input.
5723```
5724
5725#### **Example**
5726
5727```
5728 action_foreach("myscript_target") {
5729 script = "myscript.py"
5730 sources = [ ... ]
5731
5732 # Locate the depfile in the output directory named like the
5733 # inputs but with a ".d" appended.
Hector Dearman84c84312023-01-29 11:50:02 +00005734 depfile = "$target_gen_dir/{{source_name_part}}.d"
Brett Wilson796ed472018-07-16 15:11:09 -07005735
5736 # Say our script uses "-o <d file>" to indicate the depfile.
Hector Dearman84c84312023-01-29 11:50:02 +00005737 args = [ "{{source}}", "-o", rebase_path(depfile, root_build_dir)]
Brett Wilson796ed472018-07-16 15:11:09 -07005738 }
5739```
[email protected]449f3e42024-08-01 21:43:27 +08005740### <a name="var_deps"></a>**deps**: Private linked dependencies.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005741
5742```
5743 A list of target labels.
5744
5745 Specifies private dependencies of a target. Private dependencies are
5746 propagated up the dependency tree and linked to dependent targets, but do not
5747 grant the ability to include headers from the dependency. Public configs are
5748 not forwarded.
5749```
5750
5751#### **Details of dependency propagation**
5752
5753```
5754 Source sets, shared libraries, and non-complete static libraries will be
5755 propagated up the dependency tree across groups, non-complete static
5756 libraries and source sets.
5757
5758 Executables, shared libraries, and complete static libraries will link all
5759 propagated targets and stop propagation. Actions and copy steps also stop
5760 propagation, allowing them to take a library as an input but not force
5761 dependents to link to it.
5762
5763 Propagation of all_dependent_configs and public_configs happens independently
5764 of target type. all_dependent_configs are always propagated across all types
5765 of targets, and public_configs are always propagated across public deps of
5766 all types of targets.
5767
danakj2a92efd2023-07-06 14:16:38 -04005768 For Rust targets, deps ensures that Rust code can refer to the dependency
5769 target. If the dependency is a C/C++ target, the path to that target will
5770 be made available to Rust for `#[link]` directives.
5771
Brett Wilson796ed472018-07-16 15:11:09 -07005772 Data dependencies are propagated differently. See "gn help data_deps" and
5773 "gn help runtime_deps".
5774
5775 See also "public_deps".
5776```
[email protected]449f3e42024-08-01 21:43:27 +08005777### <a name="var_externs"></a>**externs**: [scope] Set of Rust crate-dependency pairs.&nbsp;[Back to Top](#gn-reference)
Petr Hoseka1413862020-01-03 12:54:33 -08005778
5779```
5780 A list, each value being a scope indicating a pair of crate name and the path
5781 to the Rust library.
5782
5783 These libraries will be passed as `--extern crate_name=path` to compiler
5784 invocation containing the current target.
5785```
5786
5787#### **Examples**
5788
5789```
5790 executable("foo") {
5791 sources = [ "main.rs" ]
5792 externs = [{
5793 crate_name = "bar",
5794 path = "path/to/bar.rlib"
5795 }]
5796 }
5797
5798 This target would compile the `foo` crate with the following `extern` flag:
5799 `--extern bar=path/to/bar.rlib`.
5800```
[email protected]449f3e42024-08-01 21:43:27 +08005801### <a name="var_framework_dirs"></a>**framework_dirs**: [directory list] Additional framework search directories.&nbsp;[Back to Top](#gn-reference)
Sylvain Defresnea09ec162020-01-16 12:36:40 +01005802
5803```
5804 A list of source directories.
5805
5806 The directories in this list will be added to the framework search path for
5807 the files in the affected target.
5808```
5809
5810#### **Ordering of flags and values**
5811
5812```
5813 1. Those set on the current target (not in a config).
5814 2. Those set on the "configs" on the target in order that the
5815 configs appear in the list.
5816 3. Those set on the "all_dependent_configs" on the target in order
5817 that the configs appear in the list.
5818 4. Those set on the "public_configs" on the target in order that
5819 those configs appear in the list.
5820 5. all_dependent_configs pulled from dependencies, in the order of
5821 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005822 more than once, only the first occurrence will be used.
Sylvain Defresnea09ec162020-01-16 12:36:40 +01005823 6. public_configs pulled from dependencies, in the order of the
5824 "deps" list. If a dependency is public, they will be applied
5825 recursively.
5826```
5827
5828#### **Example**
5829
5830```
5831 framework_dirs = [ "src/include", "//third_party/foo" ]
5832```
[email protected]449f3e42024-08-01 21:43:27 +08005833### <a name="var_frameworks"></a>**frameworks**: [name list] Name of frameworks that must be linked.&nbsp;[Back to Top](#gn-reference)
Sylvain Defresnea09ec162020-01-16 12:36:40 +01005834
5835```
5836 A list of framework names.
5837
5838 The frameworks named in that list will be linked with any dynamic link
5839 type target.
5840```
5841
5842#### **Ordering of flags and values**
5843
5844```
5845 1. Those set on the current target (not in a config).
5846 2. Those set on the "configs" on the target in order that the
5847 configs appear in the list.
5848 3. Those set on the "all_dependent_configs" on the target in order
5849 that the configs appear in the list.
5850 4. Those set on the "public_configs" on the target in order that
5851 those configs appear in the list.
5852 5. all_dependent_configs pulled from dependencies, in the order of
5853 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005854 more than once, only the first occurrence will be used.
Sylvain Defresnea09ec162020-01-16 12:36:40 +01005855 6. public_configs pulled from dependencies, in the order of the
5856 "deps" list. If a dependency is public, they will be applied
5857 recursively.
5858```
5859
5860#### **Example**
5861
5862```
5863 frameworks = [ "Foundation.framework", "Foo.framework" ]
5864```
[email protected]449f3e42024-08-01 21:43:27 +08005865### <a name="var_friend"></a>**friend**: Allow targets to include private headers.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005866
5867```
5868 A list of label patterns (see "gn help label_pattern") that allow dependent
5869 targets to include private headers. Applies to all binary targets.
5870
5871 Normally if a target lists headers in the "public" list (see "gn help
5872 public"), other headers are implicitly marked as private. Private headers
5873 can not be included by other targets, even with a public dependency path.
5874 The "gn check" function performs this validation.
5875
5876 A friend declaration allows one or more targets to include private headers.
5877 This is useful for things like unit tests that are closely associated with a
5878 target and require internal knowledge without opening up all headers to be
5879 included by all dependents.
5880
5881 A friend target does not allow that target to include headers when no
5882 dependency exists. A public dependency path must still exist between two
5883 targets to include any headers from a destination target. The friend
5884 annotation merely allows the use of headers that would otherwise be
5885 prohibited because they are private.
5886
5887 The friend annotation is matched only against the target containing the file
5888 with the include directive. Friend annotations are not propagated across
5889 public or private dependencies. Friend annotations do not affect visibility.
5890```
5891
5892#### **Example**
5893
5894```
5895 static_library("lib") {
5896 # This target can include our private headers.
5897 friend = [ ":unit_tests" ]
5898
5899 public = [
5900 "public_api.h", # Normal public API for dependent targets.
5901 ]
5902
5903 # Private API and sources.
5904 sources = [
5905 "a_source_file.cc",
5906
5907 # Normal targets that depend on this one won't be able to include this
5908 # because this target defines a list of "public" headers. Without the
5909 # "public" list, all headers are implicitly public.
5910 "private_api.h",
5911 ]
5912 }
5913
5914 executable("unit_tests") {
5915 sources = [
5916 # This can include "private_api.h" from the :lib target because it
5917 # depends on that target and because of the friend annotation.
5918 "my_test.cc",
5919 ]
5920
5921 deps = [
5922 ":lib", # Required for the include to be allowed.
5923 ]
5924 }
5925```
[email protected]449f3e42024-08-01 21:43:27 +08005926### <a name="var_gen_deps"></a>**gen_deps**: Declares targets that should generate when this one does.&nbsp;[Back to Top](#gn-reference)
Tyler Mandry4a648092022-02-15 19:47:09 +00005927
5928```
5929 A list of target labels.
5930
5931 Not all GN targets that get evaluated are actually turned into ninja targets
5932 (see "gn help execution"). If this target is generated, then any targets in
Ricardo Ribalda85bd0a62023-11-11 16:30:19 +00005933 the "gen_deps" list will also be generated, regardless of the usual criteria.
Tyler Mandry4a648092022-02-15 19:47:09 +00005934
5935 Since "gen_deps" are not build time dependencies, there can be cycles between
5936 "deps" and "gen_deps" or within "gen_deps" itself.
5937```
[email protected]449f3e42024-08-01 21:43:27 +08005938### <a name="var_include_dirs"></a>**include_dirs**: Additional include directories.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005939
5940```
5941 A list of source directories.
5942
5943 The directories in this list will be added to the include path for the files
5944 in the affected target.
5945```
5946
5947#### **Ordering of flags and values**
5948
5949```
5950 1. Those set on the current target (not in a config).
5951 2. Those set on the "configs" on the target in order that the
5952 configs appear in the list.
5953 3. Those set on the "all_dependent_configs" on the target in order
5954 that the configs appear in the list.
5955 4. Those set on the "public_configs" on the target in order that
5956 those configs appear in the list.
5957 5. all_dependent_configs pulled from dependencies, in the order of
5958 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005959 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005960 6. public_configs pulled from dependencies, in the order of the
5961 "deps" list. If a dependency is public, they will be applied
5962 recursively.
5963```
5964
5965#### **Example**
5966
5967```
5968 include_dirs = [ "src/include", "//third_party/foo" ]
5969```
[email protected]449f3e42024-08-01 21:43:27 +08005970### <a name="var_inputs"></a>**inputs**: Additional compile-time dependencies.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005971
5972```
5973 Inputs are compile-time dependencies of the current target. This means that
5974 all inputs must be available before compiling any of the sources or executing
5975 any actions.
5976
5977 Inputs are typically only used for action and action_foreach targets.
5978```
5979
5980#### **Inputs for actions**
5981
5982```
5983 For action and action_foreach targets, inputs should be the inputs to script
5984 that don't vary. These should be all .py files that the script uses via
5985 imports (the main script itself will be an implicit dependency of the action
5986 so need not be listed).
5987
5988 For action targets, inputs and sources are treated the same, but from a style
5989 perspective, it's recommended to follow the same rule as action_foreach and
5990 put helper files in the inputs, and the data used by the script (if any) in
5991 sources.
5992
5993 Note that another way to declare input dependencies from an action is to have
5994 the action write a depfile (see "gn help depfile"). This allows the script to
5995 dynamically write input dependencies, that might not be known until actually
5996 executing the script. This is more efficient than doing processing while
5997 running GN to determine the inputs, and is easier to keep in-sync than
5998 hardcoding the list.
5999```
6000
6001#### **Script input gotchas**
6002
6003```
6004 It may be tempting to write a script that enumerates all files in a directory
6005 as inputs. Don't do this! Even if you specify all the files in the inputs or
6006 sources in the GN target (or worse, enumerate the files in an exec_script
6007 call when running GN, which will be slow), the dependencies will be broken.
6008
6009 The problem happens if a file is ever removed because the inputs are not
6010 listed on the command line to the script. Because the script hasn't changed
6011 and all inputs are up to date, the script will not re-run and you will get a
6012 stale build. Instead, either list all inputs on the command line to the
6013 script, or if there are many, create a separate list file that the script
6014 reads. As long as this file is listed in the inputs, the build will detect
6015 when it has changed in any way and the action will re-run.
6016```
6017
6018#### **Inputs for binary targets**
6019
6020```
Julie Hockette2a29402018-07-31 10:11:42 -07006021 Any input dependencies will be resolved before compiling any sources or
6022 linking the target. Normally, all actions that a target depends on will be run
6023 before any files in a target are compiled. So if you depend on generated
6024 headers, you do not typically need to list them in the inputs section.
Brett Wilson796ed472018-07-16 15:11:09 -07006025
6026 Inputs for binary targets will be treated as implicit dependencies, meaning
6027 that changes in any of the inputs will force all sources in the target to be
6028 recompiled. If an input only applies to a subset of source files, you may
6029 want to split those into a separate target to avoid unnecessary recompiles.
6030```
6031
6032#### **Example**
6033
6034```
6035 action("myscript") {
6036 script = "domything.py"
6037 inputs = [ "input.data" ]
6038 }
6039```
[email protected]449f3e42024-08-01 21:43:27 +08006040### <a name="var_ldflags"></a>**ldflags**: Flags passed to the linker.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006041
6042```
6043 A list of strings.
6044
6045 These flags are passed on the command-line to the linker and generally
6046 specify various linking options. Most targets will not need these and will
6047 use "libs" and "lib_dirs" instead.
6048
6049 ldflags are NOT pushed to dependents, so applying ldflags to source sets or
6050 static libraries will be a no-op. If you want to apply ldflags to dependent
6051 targets, put them in a config and set it in the all_dependent_configs or
6052 public_configs.
6053```
6054
6055#### **Ordering of flags and values**
6056
6057```
6058 1. Those set on the current target (not in a config).
6059 2. Those set on the "configs" on the target in order that the
6060 configs appear in the list.
6061 3. Those set on the "all_dependent_configs" on the target in order
6062 that the configs appear in the list.
6063 4. Those set on the "public_configs" on the target in order that
6064 those configs appear in the list.
6065 5. all_dependent_configs pulled from dependencies, in the order of
6066 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006067 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07006068 6. public_configs pulled from dependencies, in the order of the
6069 "deps" list. If a dependency is public, they will be applied
6070 recursively.
6071```
[email protected]449f3e42024-08-01 21:43:27 +08006072### <a name="var_lib_dirs"></a>**lib_dirs**: Additional library directories.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006073
6074```
6075 A list of directories.
6076
6077 Specifies additional directories passed to the linker for searching for the
6078 required libraries. If an item is not an absolute path, it will be treated as
6079 being relative to the current build file.
6080
6081 libs and lib_dirs work differently than other flags in two respects.
Joe Armstrong23d22bc2019-06-28 15:31:03 +08006082 First, they are inherited across static library boundaries until a
Brett Wilson796ed472018-07-16 15:11:09 -07006083 shared library or executable target is reached. Second, they are
6084 uniquified so each one is only passed once (the first instance of it
6085 will be the one used).
6086```
6087
6088#### **Ordering of flags and values**
6089
6090```
6091 1. Those set on the current target (not in a config).
6092 2. Those set on the "configs" on the target in order that the
6093 configs appear in the list.
6094 3. Those set on the "all_dependent_configs" on the target in order
6095 that the configs appear in the list.
6096 4. Those set on the "public_configs" on the target in order that
6097 those configs appear in the list.
6098 5. all_dependent_configs pulled from dependencies, in the order of
6099 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006100 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07006101 6. public_configs pulled from dependencies, in the order of the
6102 "deps" list. If a dependency is public, they will be applied
6103 recursively.
6104
6105 For "libs" and "lib_dirs" only, the values propagated from
6106 dependencies (as described above) are applied last assuming they
6107 are not already in the list.
6108```
6109
6110#### **Example**
6111
6112```
6113 lib_dirs = [ "/usr/lib/foo", "lib/doom_melon" ]
6114```
[email protected]449f3e42024-08-01 21:43:27 +08006115### <a name="var_libs"></a>**libs**: Additional libraries to link.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006116
6117```
6118 A list of library names or library paths.
6119
6120 These libraries will be linked into the final binary (executable or shared
6121 library) containing the current target.
6122
6123 libs and lib_dirs work differently than other flags in two respects.
Joe Armstrong23d22bc2019-06-28 15:31:03 +08006124 First, they are inherited across static library boundaries until a
Brett Wilson796ed472018-07-16 15:11:09 -07006125 shared library or executable target is reached. Second, they are
6126 uniquified so each one is only passed once (the first instance of it
6127 will be the one used).
6128```
6129
6130#### **Types of libs**
6131
6132```
6133 There are several different things that can be expressed in libs:
6134
6135 File paths
6136 Values containing '/' will be treated as references to files in the
6137 checkout. They will be rebased to be relative to the build directory and
6138 specified in the "libs" for linker tools. This facility should be used
6139 for libraries that are checked in to the version control. For libraries
6140 that are generated by the build, use normal GN deps to link them.
6141
6142 System libraries
6143 Values not containing '/' will be treated as system library names. These
6144 will be passed unmodified to the linker and prefixed with the
6145 "lib_switch" attribute of the linker tool. Generally you would set the
6146 "lib_dirs" so the given library is found. Your BUILD.gn file should not
6147 specify the switch (like "-l"): this will be encoded in the "lib_switch"
6148 of the tool.
Brett Wilson796ed472018-07-16 15:11:09 -07006149```
6150
6151#### **Ordering of flags and values**
6152
6153```
6154 1. Those set on the current target (not in a config).
6155 2. Those set on the "configs" on the target in order that the
6156 configs appear in the list.
6157 3. Those set on the "all_dependent_configs" on the target in order
6158 that the configs appear in the list.
6159 4. Those set on the "public_configs" on the target in order that
6160 those configs appear in the list.
6161 5. all_dependent_configs pulled from dependencies, in the order of
6162 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006163 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07006164 6. public_configs pulled from dependencies, in the order of the
6165 "deps" list. If a dependency is public, they will be applied
6166 recursively.
6167
6168 For "libs" and "lib_dirs" only, the values propagated from
6169 dependencies (as described above) are applied last assuming they
6170 are not already in the list.
6171```
6172
6173#### **Examples**
6174
6175```
6176 On Windows:
6177 libs = [ "ctl3d.lib" ]
6178
6179 On Linux:
6180 libs = [ "ld" ]
6181```
[email protected]449f3e42024-08-01 21:43:27 +08006182### <a name="var_metadata"></a>**metadata**: Metadata of this target.&nbsp;[Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08006183
6184```
6185 Metadata is a collection of keys and values relating to a particular target.
Julie Hockettd69a9c32019-01-23 14:36:18 -08006186 Values must be lists, allowing for sane and predictable collection behavior.
6187 Generally, these keys will include three types of lists: lists of ordinary
6188 strings, lists of filenames intended to be rebased according to their
6189 particular source directory, and lists of target labels intended to be used
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006190 as barriers to the walk. Verification of these categories occurs at walk time,
Julie Hockettd69a9c32019-01-23 14:36:18 -08006191 not creation time (since it is not clear until the walk which values are
6192 intended for which purpose).
6193```
Nate Fischer8ed01d32019-01-08 17:32:01 -08006194
Julie Hockettd69a9c32019-01-23 14:36:18 -08006195#### **Example**
Nate Fischer8ed01d32019-01-08 17:32:01 -08006196
Julie Hockettd69a9c32019-01-23 14:36:18 -08006197```
Nate Fischer8ed01d32019-01-08 17:32:01 -08006198 group("doom_melon") {
6199 metadata = {
6200 # These keys are not built in to GN but are interpreted when consuming
6201 # metadata.
6202 my_barrier = []
6203 my_files = [ "a.txt", "b.txt" ]
6204 }
6205 }
6206```
[email protected]449f3e42024-08-01 21:43:27 +08006207### <a name="var_mnemonic"></a>**mnemonic**: [string] Prefix displayed when ninja runs this action.&nbsp;[Back to Top](#gn-reference)
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07006208
6209```
6210 Tools in GN can set their ninja "description" which is displayed when
6211 building a target. These are commonly set with the format "CXX $output"
6212 or "LINK $label". By default, all GN actions will have the description
6213 "ACTION $label". Setting a mnemonic will override the "ACTION" prefix
6214 with another string, but the label will still be unconditionally displayed.
6215
6216 Whitespace is not allowed within a mnemonic.
6217```
[email protected]449f3e42024-08-01 21:43:27 +08006218### <a name="var_module_name"></a>**module_name**: [string] The name for the compiled module.&nbsp;[Back to Top](#gn-reference)
Sylvain Defresne89e64252020-08-07 13:01:06 +02006219
6220```
6221 Valid for binary targets that contain Swift sources.
6222
6223 If module_name is not set, then this rule will use the target name.
6224```
[email protected]449f3e42024-08-01 21:43:27 +08006225### <a name="var_output_conversion"></a>**output_conversion**: Data format for generated_file targets.&nbsp;[Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08006226
6227```
6228 Controls how the "contents" of a generated_file target is formatted.
Sylvain Defresne72d5a6e2021-06-15 17:01:32 +02006229 See `gn help io_conversion`.
Nate Fischer8ed01d32019-01-08 17:32:01 -08006230```
[email protected]449f3e42024-08-01 21:43:27 +08006231### <a name="var_output_dir"></a>**output_dir**: [directory] Directory to put output file in.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006232
6233```
6234 For library and executable targets, overrides the directory for the final
6235 output. This must be in the root_build_dir or a child thereof.
6236
6237 This should generally be in the root_out_dir or a subdirectory thereof (the
6238 root_out_dir will be the same as the root_build_dir for the default
6239 toolchain, and will be a subdirectory for other toolchains). Not putting the
6240 output in a subdirectory of root_out_dir can result in collisions between
6241 different toolchains, so you will need to take steps to ensure that your
6242 target is only present in one toolchain.
6243
6244 Normally the toolchain specifies the output directory for libraries and
6245 executables (see "gn help tool"). You will have to consult that for the
6246 default location. The default location will be used if output_dir is
6247 undefined or empty.
6248```
6249
6250#### **Example**
6251
6252```
6253 shared_library("doom_melon") {
6254 output_dir = "$root_out_dir/plugin_libs"
6255 ...
6256 }
6257```
[email protected]449f3e42024-08-01 21:43:27 +08006258### <a name="var_output_extension"></a>**output_extension**: Value to use for the output's file extension.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006259
6260```
6261 Normally the file extension for a target is based on the target type and the
6262 operating system, but in rare cases you will need to override the name (for
6263 example to use "libfreetype.so.6" instead of libfreetype.so on Linux).
6264
6265 This value should not include a leading dot. If undefined, the default
6266 specified on the tool will be used. If set to the empty string, no output
6267 extension will be used.
6268
6269 The output_extension will be used to set the "{{output_extension}}" expansion
6270 which the linker tool will generally use to specify the output file name. See
6271 "gn help tool".
6272```
6273
6274#### **Example**
6275
6276```
6277 shared_library("freetype") {
6278 if (is_linux) {
6279 # Call the output "libfreetype.so.6"
6280 output_extension = "so.6"
6281 }
6282 ...
6283 }
6284
6285 # On Windows, generate a "mysettings.cpl" control panel applet. Control panel
6286 # applets are actually special shared libraries.
6287 if (is_win) {
6288 shared_library("mysettings") {
6289 output_extension = "cpl"
6290 ...
6291 }
6292 }
6293```
[email protected]449f3e42024-08-01 21:43:27 +08006294### <a name="var_output_name"></a>**output_name**: Define a name for the output file other than the default.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006295
6296```
6297 Normally the output name of a target will be based on the target name, so the
6298 target "//foo/bar:bar_unittests" will generate an output file such as
6299 "bar_unittests.exe" (using Windows as an example).
6300
6301 Sometimes you will want an alternate name to avoid collisions or if the
6302 internal name isn't appropriate for public distribution.
6303
6304 The output name should have no extension or prefixes, these will be added
6305 using the default system rules. For example, on Linux an output name of "foo"
6306 will produce a shared library "libfoo.so". There is no way to override the
6307 output prefix of a linker tool on a per- target basis. If you need more
6308 flexibility, create a copy target to produce the file you want.
6309
6310 This variable is valid for all binary output target types.
6311```
6312
6313#### **Example**
6314
6315```
6316 static_library("doom_melon") {
6317 output_name = "fluffy_bunny"
6318 }
6319```
[email protected]449f3e42024-08-01 21:43:27 +08006320### <a name="var_output_prefix_override"></a>**output_prefix_override**: Don't use prefix for output name.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006321
6322```
6323 A boolean that overrides the output prefix for a target. Defaults to false.
6324
6325 Some systems use prefixes for the names of the final target output file. The
6326 normal example is "libfoo.so" on Linux for a target named "foo".
6327
6328 The output prefix for a given target type is specified on the linker tool
6329 (see "gn help tool"). Sometimes this prefix is undesired.
6330
6331 See also "gn help output_extension".
6332```
6333
6334#### **Example**
6335
6336```
6337 shared_library("doom_melon") {
6338 # Normally this will produce "libdoom_melon.so" on Linux. Setting this flag
6339 # will produce "doom_melon.so".
6340 output_prefix_override = true
6341 ...
6342 }
6343```
[email protected]449f3e42024-08-01 21:43:27 +08006344### <a name="var_outputs"></a>**outputs**: Output files for actions and copy targets.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006345
6346```
6347 Outputs is valid for "copy", "action", and "action_foreach" target types and
6348 indicates the resulting files. Outputs must always refer to files in the
6349 build directory.
6350
6351 copy
6352 Copy targets should have exactly one entry in the outputs list. If there is
6353 exactly one source, this can be a literal file name or a source expansion.
6354 If there is more than one source, this must contain a source expansion to
6355 map a single input name to a single output name. See "gn help copy".
6356
6357 action_foreach
6358 Action_foreach targets must always use source expansions to map input files
6359 to output files. There can be more than one output, which means that each
6360 invocation of the script will produce a set of files (presumably based on
6361 the name of the input file). See "gn help action_foreach".
6362
6363 action
6364 Action targets (excluding action_foreach) must list literal output file(s)
6365 with no source expansions. See "gn help action".
6366```
[email protected]449f3e42024-08-01 21:43:27 +08006367### <a name="var_partial_info_plist"></a>**partial_info_plist**: [filename] Path plist from asset catalog compiler.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006368
6369```
6370 Valid for create_bundle target, corresponds to the path for the partial
6371 Info.plist created by the asset catalog compiler that needs to be merged
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006372 with the application Info.plist (usually done by the post-processing script).
Brett Wilson796ed472018-07-16 15:11:09 -07006373
6374 The file will be generated regardless of whether the asset compiler has
6375 been invoked or not. See "gn help create_bundle".
6376```
[email protected]449f3e42024-08-01 21:43:27 +08006377### <a name="var_pool"></a>**pool**: Label of the pool used by binary targets actions.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006378
6379```
Petr Hosek7a6231e2022-10-22 23:14:18 +00006380 A fully-qualified label representing the pool that will be used for binary
6381 targets and actions. Pools are defined using the pool() {...} declaration.
Brett Wilson796ed472018-07-16 15:11:09 -07006382```
6383
6384#### **Example**
6385
6386```
Petr Hosek7a6231e2022-10-22 23:14:18 +00006387 executable("binary") {
6388 pool = "//build:custom_pool"
6389 ...
6390 }
6391
Brett Wilson796ed472018-07-16 15:11:09 -07006392 action("action") {
6393 pool = "//build:custom_pool"
6394 ...
6395 }
6396```
[email protected]449f3e42024-08-01 21:43:27 +08006397### <a name="var_post_processing_args"></a>**post_processing_args**: [string list] Args for the post-processing script.&nbsp;[Back to Top](#gn-reference)
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006398
6399```
6400 For create_bundle targets, post_processing_args is the list of arguments to
6401 pass to the post-processing script. Typically you would use source expansion
6402 (see "gn help source_expansion") to insert the source file names.
6403
6404 See also "gn help create_bundle".
6405```
Sylvain Defresne19281422025-08-01 10:40:16 +02006406### <a name="var_post_processing_manifest"></a>**post_processing_manifest**: [file] Name of the generated bundle manifest.&nbsp;[Back to Top](#gn-reference)
6407
6408```
6409 Path where a manifest listing all the files found in the bundle will be
6410 written for the post processing step. The path must be outside of the
6411 bundle_root_dir.
6412
6413 See also "gen help create_bundle".
6414```
[email protected]449f3e42024-08-01 21:43:27 +08006415### <a name="var_post_processing_outputs"></a>**post_processing_outputs**: [file list] Outputs of the post-processing step.&nbsp;[Back to Top](#gn-reference)
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006416
6417```
6418 Outputs from the post-processing step of a create_bundle target. Must refer to
6419 files in the build directory.
6420
6421 See also "gn help create_bundle".
6422```
[email protected]449f3e42024-08-01 21:43:27 +08006423### <a name="var_post_processing_script"></a>**post_processing_script**: [file name] Script for the post-processing step."&nbsp;[Back to Top](#gn-reference)
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006424
6425```
6426 An absolute or buildfile-relative file name of a Python script to run for a
6427 create_bundle target to perform the post-processing step.
6428
6429 See also "gn help create_bundle".
6430```
[email protected]449f3e42024-08-01 21:43:27 +08006431### <a name="var_post_processing_sources"></a>**post_processing_sources**: [file list] Sources for the post-processing step.&nbsp;[Back to Top](#gn-reference)
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006432
6433```
6434 A list of files used as input for the post-processing step of a create_bundle
6435 target. Non-absolute paths will be resolved relative to the current build
6436 file.
6437
6438 See also "gn help create_bundle".
6439```
[email protected]449f3e42024-08-01 21:43:27 +08006440### <a name="var_precompiled_header"></a>**precompiled_header**: [string] Header file to precompile.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006441
6442```
6443 Precompiled headers will be used when a target specifies this value, or a
6444 config applying to this target specifies this value. In addition, the tool
6445 corresponding to the source files must also specify precompiled headers (see
6446 "gn help tool"). The tool will also specify what type of precompiled headers
6447 to use, by setting precompiled_header_type to either "gcc" or "msvc".
6448
6449 The precompiled header/source variables can be specified on a target or a
6450 config, but must be the same for all configs applying to a given target since
6451 a target can only have one precompiled header.
6452
6453 If you use both C and C++ sources, the precompiled header and source file
6454 will be compiled once per language. You will want to make sure to wrap C++
6455 includes in __cplusplus #ifdefs so the file will compile in C mode.
6456```
6457
6458#### **GCC precompiled headers**
6459
6460```
6461 When using GCC-style precompiled headers, "precompiled_source" contains the
6462 path of a .h file that is precompiled and then included by all source files
6463 in targets that set "precompiled_source".
6464
6465 The value of "precompiled_header" is not used with GCC-style precompiled
6466 headers.
6467```
6468
6469#### **MSVC precompiled headers**
6470
6471```
6472 When using MSVC-style precompiled headers, the "precompiled_header" value is
6473 a string corresponding to the header. This is NOT a path to a file that GN
6474 recognises, but rather the exact string that appears in quotes after
6475 an #include line in source code. The compiler will match this string against
6476 includes or forced includes (/FI).
6477
6478 MSVC also requires a source file to compile the header with. This must be
6479 specified by the "precompiled_source" value. In contrast to the header value,
6480 this IS a GN-style file name, and tells GN which source file to compile to
6481 make the .pch file used for subsequent compiles.
6482
6483 For example, if the toolchain specifies MSVC headers:
6484
6485 toolchain("vc_x64") {
6486 ...
6487 tool("cxx") {
6488 precompiled_header_type = "msvc"
6489 ...
6490
6491 You might make a config like this:
6492
6493 config("use_precompiled_headers") {
6494 precompiled_header = "build/precompile.h"
6495 precompiled_source = "//build/precompile.cc"
6496
6497 # Either your source files should #include "build/precompile.h"
6498 # first, or you can do this to force-include the header.
6499 cflags = [ "/FI$precompiled_header" ]
6500 }
6501
6502 And then define a target that uses the config:
6503
6504 executable("doom_melon") {
6505 configs += [ ":use_precompiled_headers" ]
6506 ...
6507```
[email protected]449f3e42024-08-01 21:43:27 +08006508### <a name="var_precompiled_header_type"></a>**precompiled_header_type**: [string] "gcc" or "msvc".&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006509
6510```
6511 See "gn help precompiled_header".
6512```
[email protected]449f3e42024-08-01 21:43:27 +08006513### <a name="var_precompiled_source"></a>**precompiled_source**: [file name] Source file to precompile.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006514
6515```
6516 The source file that goes along with the precompiled_header when using
6517 "msvc"-style precompiled headers. It will be implicitly added to the sources
6518 of the target. See "gn help precompiled_header".
6519```
[email protected]449f3e42024-08-01 21:43:27 +08006520### <a name="var_product_type"></a>**product_type**: [string] Product type for the bundle.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006521
6522```
Sylvain Defresnee5aee7b2023-06-08 10:08:10 -04006523 Valid for "create_bundle" and "bundle_data" targets.
Brett Wilson796ed472018-07-16 15:11:09 -07006524
Sylvain Defresnee5aee7b2023-06-08 10:08:10 -04006525 Correspond to the type of the bundle. Used by transparent "create_bundle"
6526 target to control whether a "bundle_data" needs to be propagated or not.
6527
6528 When generating Xcode project, the product_type is propagated and only
6529 "create_bundle" with a non-empty product_type will have a corresponding
6530 target in the project.
Brett Wilson796ed472018-07-16 15:11:09 -07006531```
[email protected]449f3e42024-08-01 21:43:27 +08006532### <a name="var_public"></a>**public**: Declare public header files for a target.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006533
6534```
6535 A list of files that other targets can include. These permissions are checked
6536 via the "check" command (see "gn help check").
6537
6538 If no public files are declared, other targets (assuming they have visibility
6539 to depend on this target) can include any file in the sources list. If this
6540 variable is defined on a target, dependent targets may only include files on
Dirk Prankeed1abc12025-01-10 17:41:03 -08006541 this allowlist unless that target is marked as a friend (see "gn help
Brett Wilson796ed472018-07-16 15:11:09 -07006542 friend").
6543
6544 Header file permissions are also subject to visibility. A target must be
6545 visible to another target to include any files from it at all and the public
6546 headers indicate which subset of those files are permitted. See "gn help
6547 visibility" for more.
6548
6549 Public files are inherited through the dependency tree. So if there is a
6550 dependency A -> B -> C, then A can include C's public headers. However, the
6551 same is NOT true of visibility, so unless A is in C's visibility list, the
6552 include will be rejected.
6553
6554 GN only knows about files declared in the "sources" and "public" sections of
6555 targets. If a file is included that is not known to the build, it will be
6556 allowed.
6557
6558 It is common for test targets to need to include private headers for their
6559 associated code. In this case, list the test target in the "friend" list of
6560 the target that owns the private header to allow the inclusion. See
6561 "gn help friend" for more.
Julie Hockette2a29402018-07-31 10:11:42 -07006562
6563 When a binary target has no explicit or implicit public headers (a "public"
6564 list is defined but is empty), GN assumes that the target can not propagate
6565 any compile-time dependencies up the dependency tree. In this case, the build
6566 can be parallelized more efficiently.
6567 Say there are dependencies:
6568 A (shared library) -> B (shared library) -> C (action).
6569 Normally C must complete before any source files in A can compile (because
6570 there might be generated includes). But when B explicitly declares no public
6571 headers, C can execute in parallel with A's compile steps. C must still be
6572 complete before any dependents link.
Brett Wilson796ed472018-07-16 15:11:09 -07006573```
6574
6575#### **Examples**
6576
6577```
6578 These exact files are public:
6579 public = [ "foo.h", "bar.h" ]
6580
6581 No files are public (no targets may include headers from this one):
Julie Hockette2a29402018-07-31 10:11:42 -07006582 # This allows starting compilation in dependent targets earlier.
Brett Wilson796ed472018-07-16 15:11:09 -07006583 public = []
6584```
[email protected]449f3e42024-08-01 21:43:27 +08006585### <a name="var_public_configs"></a>**public_configs**: Configs to be applied on dependents.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006586
6587```
6588 A list of config labels.
6589
6590 Targets directly depending on this one will have the configs listed in this
6591 variable added to them. These configs will also apply to the current target.
Julie Hockette2a29402018-07-31 10:11:42 -07006592 Generally, public configs are used to apply defines and include directories
6593 necessary to compile this target's header files.
Brett Wilson796ed472018-07-16 15:11:09 -07006594
Julie Hockette2a29402018-07-31 10:11:42 -07006595 See also "gn help all_dependent_configs".
6596```
6597
6598#### **Propagation of public configs**
6599
6600```
6601 Public configs are applied to all targets that depend directly on this one.
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006602 These dependent targets can further push this target's public configs
Julie Hockette2a29402018-07-31 10:11:42 -07006603 higher in the dependency tree by depending on it via public_deps (see "gn
6604 help public_deps").
6605
6606 static_library("toplevel") {
6607 # This target will get "my_config" applied to it. However, since this
6608 # target uses "deps" and not "public_deps", targets that depend on this
6609 # one won't get it.
6610 deps = [ ":intermediate" ]
6611 }
6612
6613 static_library("intermediate") {
6614 # Depending on "lower" in any way will apply "my_config" to this target.
6615 # Additionall, since this target depends on "lower" via public_deps,
6616 # targets that depend on this one will also get "my_config".
6617 public_deps = [ ":lower" ]
6618 }
6619
6620 static_library("lower") {
6621 # This will get applied to all targets that depend on this one.
6622 public_configs = [ ":my_config" ]
6623 }
6624
6625 Public config propagation happens in a second phase once a target and all of
6626 its dependencies have been resolved. Therefore, a target will not see these
Brett Wilson796ed472018-07-16 15:11:09 -07006627 force-added configs in their "configs" variable while the script is running,
6628 and they can not be removed. As a result, this capability should generally
Julie Hockette2a29402018-07-31 10:11:42 -07006629 only be used to add defines and include directories rather than setting
6630 complicated flags that some targets may not want.
Brett Wilson796ed472018-07-16 15:11:09 -07006631
Julie Hockette2a29402018-07-31 10:11:42 -07006632 Public configs may or may not be propagated across toolchain boundaries
6633 depending on the value of the propagates_configs flag (see "gn help
6634 toolchain") on the toolchain of the target declaring the public_config.
6635```
6636
6637#### **Avoiding applying public configs to this target**
6638
6639```
6640 If you want the config to apply to targets that depend on this one, but NOT
6641 this one, define an extra layer of indirection using a group:
6642
6643 # External targets depend on this group.
6644 group("my_target") {
6645 # Config to apply to all targets that depend on this one.
6646 public_configs = [ ":external_settings" ]
6647 deps = [ ":internal_target" ]
6648 }
6649
6650 # Internal target to actually compile the sources.
6651 static_library("internal_target") {
6652 # Force all external targets to depend on the group instead of directly
6653 # on this so the "external_settings" config will get applied.
6654 visibility = [ ":my_target" ]
6655 ...
6656 }
Brett Wilson796ed472018-07-16 15:11:09 -07006657```
6658
6659#### **Ordering of flags and values**
6660
6661```
6662 1. Those set on the current target (not in a config).
6663 2. Those set on the "configs" on the target in order that the
6664 configs appear in the list.
6665 3. Those set on the "all_dependent_configs" on the target in order
6666 that the configs appear in the list.
6667 4. Those set on the "public_configs" on the target in order that
6668 those configs appear in the list.
6669 5. all_dependent_configs pulled from dependencies, in the order of
6670 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006671 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07006672 6. public_configs pulled from dependencies, in the order of the
6673 "deps" list. If a dependency is public, they will be applied
6674 recursively.
6675```
[email protected]449f3e42024-08-01 21:43:27 +08006676### <a name="var_public_deps"></a>**public_deps**: Declare public dependencies.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006677
6678```
6679 Public dependencies are like private dependencies (see "gn help deps") but
6680 additionally express that the current target exposes the listed deps as part
6681 of its public API.
6682
6683 This has several ramifications:
6684
6685 - public_configs that are part of the dependency are forwarded to direct
6686 dependents.
6687
6688 - Public headers in the dependency are usable by dependents (includes do
6689 not require a direct dependency or visibility).
6690
6691 - If the current target is a shared library, other shared libraries that it
6692 publicly depends on (directly or indirectly) are propagated up the
6693 dependency tree to dependents for linking.
Julie Hockette2a29402018-07-31 10:11:42 -07006694
6695 See also "gn help public_configs".
Brett Wilson796ed472018-07-16 15:11:09 -07006696```
6697
6698#### **Discussion**
6699
6700```
6701 Say you have three targets: A -> B -> C. C's visibility may allow B to depend
6702 on it but not A. Normally, this would prevent A from including any headers
6703 from C, and C's public_configs would apply only to B.
6704
6705 If B lists C in its public_deps instead of regular deps, A will now inherit
6706 C's public_configs and the ability to include C's public headers.
6707
6708 Generally if you are writing a target B and you include C's headers as part
6709 of B's public headers, or targets depending on B should consider B and C to
6710 be part of a unit, you should use public_deps instead of deps.
6711```
6712
6713#### **Example**
6714
6715```
6716 # This target can include files from "c" but not from
6717 # "super_secret_implementation_details".
6718 executable("a") {
6719 deps = [ ":b" ]
6720 }
6721
6722 shared_library("b") {
6723 deps = [ ":super_secret_implementation_details" ]
6724 public_deps = [ ":c" ]
6725 }
6726```
[email protected]449f3e42024-08-01 21:43:27 +08006727### <a name="var_rebase"></a>**rebase**: Rebase collected metadata as files.&nbsp;[Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08006728
6729```
6730 A boolean that triggers a rebase of collected metadata strings based on their
6731 declared file. Defaults to false.
6732
6733 Metadata generally declares files as strings relative to the local build file.
6734 However, this data is often used in other contexts, and so setting this flag
6735 will force the metadata collection to be rebased according to the local build
6736 file's location and thus allow the filename to be used anywhere.
6737
6738 Setting this flag will raise an error if any target's specified metadata is
6739 not a string value.
6740
6741 See also "gn help generated_file".
6742```
[email protected]449f3e42024-08-01 21:43:27 +08006743### <a name="var_response_file_contents"></a>**response_file_contents**: Contents of a response file for actions.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006744
6745```
6746 Sometimes the arguments passed to a script can be too long for the system's
6747 command-line capabilities. This is especially the case on Windows where the
6748 maximum command-line length is less than 8K. A response file allows you to
6749 pass an unlimited amount of data to a script in a temporary file for an
6750 action or action_foreach target.
6751
6752 If the response_file_contents variable is defined and non-empty, the list
6753 will be treated as script args (including possibly substitution patterns)
6754 that will be written to a temporary file at build time. The name of the
6755 temporary file will be substituted for "{{response_file_name}}" in the script
6756 args.
6757
6758 The response file contents will always be quoted and escaped according to
6759 Unix shell rules. To parse the response file, the Python script should use
6760 "shlex.split(file_contents)".
6761```
6762
6763#### **Example**
6764
6765```
6766 action("process_lots_of_files") {
6767 script = "process.py",
6768 inputs = [ ... huge list of files ... ]
6769
6770 # Write all the inputs to a response file for the script. Also,
6771 # make the paths relative to the script working directory.
6772 response_file_contents = rebase_path(inputs, root_build_dir)
6773
6774 # The script expects the name of the response file in --file-list.
6775 args = [
6776 "--enable-foo",
6777 "--file-list={{response_file_name}}",
6778 ]
6779 }
6780```
[email protected]449f3e42024-08-01 21:43:27 +08006781### <a name="var_rustflags"></a>**rustflags**: Flags passed to the Rust compiler.&nbsp;[Back to Top](#gn-reference)
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01006782
6783```
6784 A list of strings.
6785
6786 "rustflags" are passed to all invocations of the Rust compiler.
6787```
[email protected]449f3e42024-08-01 21:43:27 +08006788### <a name="var_script"></a>**script**: Script file for actions.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006789
6790```
6791 An absolute or buildfile-relative file name of a Python script to run for a
6792 action and action_foreach targets (see "gn help action" and "gn help
6793 action_foreach").
6794```
[email protected]449f3e42024-08-01 21:43:27 +08006795### <a name="var_sources"></a>**sources**: Source files for a target&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006796
6797```
6798 A list of files. Non-absolute paths will be resolved relative to the current
6799 build file.
6800```
6801
6802#### **Sources for binary targets**
6803
6804```
6805 For binary targets (source sets, executables, and libraries), the known file
6806 types will be compiled with the associated tools. Unknown file types and
6807 headers will be skipped. However, you should still list all C/C+ header files
6808 so GN knows about the existence of those files for the purposes of include
6809 checking.
6810
6811 As a special case, a file ending in ".def" will be treated as a Windows
6812 module definition file. It will be appended to the link line with a
6813 preceding "/DEF:" string. There must be at most one .def file in a target
6814 and they do not cross dependency boundaries (so specifying a .def file in a
6815 static library or source set will have no effect on the executable or shared
6816 library they're linked into).
Julie Hockettce1fa072019-05-07 17:44:37 -07006817
6818 For Rust targets that do not specify a crate_root, then the crate_root will
6819 look for a lib.rs file (or main.rs for executable) or a single file in
6820 sources, if sources contains only one file.
Brett Wilson796ed472018-07-16 15:11:09 -07006821```
6822
6823#### **Sources for non-binary targets**
6824
6825```
6826 action_foreach
6827 The sources are the set of files that the script will be executed over. The
6828 script will run once per file.
6829
6830 action
6831 The sources will be treated the same as inputs. See "gn help inputs" for
6832 more information and usage advice.
6833
6834 copy
6835 The source are the source files to copy.
6836```
[email protected]449f3e42024-08-01 21:43:27 +08006837### <a name="var_swiftflags"></a>**swiftflags**: Flags passed to the swift compiler.&nbsp;[Back to Top](#gn-reference)
Sylvain Defresne89e64252020-08-07 13:01:06 +02006838
6839```
6840 A list of strings.
6841
6842 "swiftflags" are passed to any invocation of a tool that takes an .swift
6843 file as input.
6844```
6845
6846#### **Ordering of flags and values**
6847
6848```
6849 1. Those set on the current target (not in a config).
6850 2. Those set on the "configs" on the target in order that the
6851 configs appear in the list.
6852 3. Those set on the "all_dependent_configs" on the target in order
6853 that the configs appear in the list.
6854 4. Those set on the "public_configs" on the target in order that
6855 those configs appear in the list.
6856 5. all_dependent_configs pulled from dependencies, in the order of
6857 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006858 more than once, only the first occurrence will be used.
Sylvain Defresne89e64252020-08-07 13:01:06 +02006859 6. public_configs pulled from dependencies, in the order of the
6860 "deps" list. If a dependency is public, they will be applied
6861 recursively.
6862```
Julie Jeongeun Kimebc8f162025-05-19 11:45:26 +09006863### <a name="var_target_xcode_platform"></a>**target_xcode_platform**: The desired platform for the build.&nbsp;[Back to Top](#gn-reference)
6864
6865```
6866 This value should be used to indicate the kind of iOS or iOS-based platform
6867 that is being the desired platform for the primary object(s) of the build.
6868
6869 This should be set to the most specific value possible. So, "iphoneos" or
6870 "tvos" should be used instead of "ios" where applicable, even though
6871 iPhoneOS and tvOS are both iOS variants.
6872
6873 GN defaults this value to "iphoneos" and the configuration files should set
6874 it to an appropriate value if it is not set via the command line or in the
6875 args.gn file.
6876
6877 This value configures the base SDK and the targeted device families of the
6878 generated Xcode project. only meaningful when generating with --ide=xcode.
6879
6880 Possible values
6881
6882 - "iphoneos"
6883 - "tvos"
6884```
[email protected]449f3e42024-08-01 21:43:27 +08006885### <a name="var_testonly"></a>**testonly**: Declares a target must only be used for testing.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006886
6887```
6888 Boolean. Defaults to false.
6889
6890 When a target is marked "testonly = true", it must only be depended on by
6891 other test-only targets. Otherwise, GN will issue an error that the
6892 depenedency is not allowed.
6893
6894 This feature is intended to prevent accidentally shipping test code in a
6895 final product.
6896```
6897
6898#### **Example**
6899
6900```
6901 source_set("test_support") {
6902 testonly = true
6903 ...
6904 }
6905```
[email protected]449f3e42024-08-01 21:43:27 +08006906### <a name="var_transparent"></a>**transparent**: [bool] True if the bundle is transparent.&nbsp;[Back to Top](#gn-reference)
Sylvain Defresnee5aee7b2023-06-08 10:08:10 -04006907
6908```
6909 A boolean.
6910
6911 Valid for "create_bundle" target. If true, the "create_bundle" target will
6912 not package the "bundle_data" deps but will forward them to all targets that
6913 depends on it (unless the "bundle_data" target sets "product_type" to the
6914 same value as the "create_bundle" target).
6915```
[email protected]449f3e42024-08-01 21:43:27 +08006916### <a name="var_visibility"></a>**visibility**: A list of labels that can depend on a target.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006917
6918```
6919 A list of labels and label patterns that define which targets can depend on
6920 the current one. These permissions are checked via the "check" command (see
6921 "gn help check").
6922
6923 If visibility is not defined, it defaults to public ("*").
6924
6925 If visibility is defined, only the targets with labels that match it can
6926 depend on the current target. The empty list means no targets can depend on
6927 the current target.
6928
6929 Tip: Often you will want the same visibility for all targets in a BUILD file.
6930 In this case you can just put the definition at the top, outside of any
6931 target, and the targets will inherit that scope and see the definition.
6932```
6933
6934#### **Patterns**
6935
6936```
6937 See "gn help label_pattern" for more details on what types of patterns are
6938 supported. If a toolchain is specified, only targets in that toolchain will
6939 be matched. If a toolchain is not specified on a pattern, targets in all
6940 toolchains will be matched.
6941```
6942
6943#### **Examples**
6944
6945```
6946 Only targets in the current buildfile ("private"):
6947 visibility = [ ":*" ]
6948
6949 No targets (used for targets that should be leaf nodes):
6950 visibility = []
6951
6952 Any target ("public", the default):
6953 visibility = [ "*" ]
6954
6955 All targets in the current directory and any subdirectory:
6956 visibility = [ "./*" ]
6957
6958 Any target in "//bar/BUILD.gn":
6959 visibility = [ "//bar:*" ]
6960
6961 Any target in "//bar/" or any subdirectory thereof:
6962 visibility = [ "//bar/*" ]
6963
6964 Just these specific targets:
6965 visibility = [ ":mything", "//foo:something_else" ]
6966
6967 Any target in the current directory and any subdirectory thereof, plus
Petr Hosek7a6231e2022-10-22 23:14:18 +00006968 any targets in "//bar/" and any subdirectory thereof.
Brett Wilson796ed472018-07-16 15:11:09 -07006969 visibility = [ "./*", "//bar/*" ]
6970```
[email protected]449f3e42024-08-01 21:43:27 +08006971### <a name="var_walk_keys"></a>**walk_keys**: Key(s) for managing the metadata collection walk.&nbsp;[Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08006972
6973```
Julie Hockett152c5142019-07-12 09:53:43 -06006974 Defaults to [""].
Nate Fischer8ed01d32019-01-08 17:32:01 -08006975
6976 These keys are used to control the next step in a collection walk, acting as
6977 barriers. If a specified key is defined in a target's metadata, the walk will
6978 use the targets listed in that value to determine which targets are walked.
6979
Julie Hockett152c5142019-07-12 09:53:43 -06006980 If no walk_keys are specified for a generated_file target (i.e. "[""]"), the
Nate Fischer8ed01d32019-01-08 17:32:01 -08006981 walk will touch all deps and data_deps of the specified target recursively.
6982
6983 See "gn help generated_file".
6984```
[email protected]449f3e42024-08-01 21:43:27 +08006985### <a name="var_weak_frameworks"></a>**weak_frameworks**: [name list] Name of frameworks that must be weak linked.&nbsp;[Back to Top](#gn-reference)
Robert Sesekd0a6f072020-05-15 11:21:22 -04006986
6987```
6988 A list of framework names.
6989
6990 The frameworks named in that list will be weak linked with any dynamic link
6991 type target. Weak linking instructs the dynamic loader to attempt to load
6992 the framework, but if it is not able to do so, it leaves any imported symbols
6993 unresolved. This is typically used when a framework is present in a new
6994 version of an SDK but not on older versions of the OS that the software runs
6995 on.
6996```
6997
6998#### **Ordering of flags and values**
6999
7000```
7001 1. Those set on the current target (not in a config).
7002 2. Those set on the "configs" on the target in order that the
7003 configs appear in the list.
7004 3. Those set on the "all_dependent_configs" on the target in order
7005 that the configs appear in the list.
7006 4. Those set on the "public_configs" on the target in order that
7007 those configs appear in the list.
7008 5. all_dependent_configs pulled from dependencies, in the order of
7009 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01007010 more than once, only the first occurrence will be used.
Robert Sesekd0a6f072020-05-15 11:21:22 -04007011 6. public_configs pulled from dependencies, in the order of the
7012 "deps" list. If a dependency is public, they will be applied
7013 recursively.
7014```
7015
7016#### **Example**
7017
7018```
7019 weak_frameworks = [ "OnlyOnNewerOSes.framework" ]
7020```
[email protected]449f3e42024-08-01 21:43:27 +08007021### <a name="var_write_runtime_deps"></a>**write_runtime_deps**: Writes the target's runtime_deps to the given path.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007022
7023```
7024 Does not synchronously write the file, but rather schedules it to be written
7025 at the end of generation.
7026
7027 If the file exists and the contents are identical to that being written, the
7028 file will not be updated. This will prevent unnecessary rebuilds of targets
7029 that depend on this file.
7030
7031 Path must be within the output directory.
7032
7033 See "gn help runtime_deps" for how the runtime dependencies are computed.
7034
7035 The format of this file will list one file per line with no escaping. The
7036 files will be relative to the root_build_dir. The first line of the file will
7037 be the main output file of the target itself. The file contents will be the
7038 same as requesting the runtime deps be written on the command line (see "gn
7039 help --runtime-deps-list-file").
7040```
[email protected]449f3e42024-08-01 21:43:27 +08007041### <a name="var_xcasset_compiler_flags"></a>**xcasset_compiler_flags**: Flags passed to xcassets compiler.&nbsp;[Back to Top](#gn-reference)
Harley Li0a9affb2020-06-03 10:38:42 -04007042
7043```
7044 A list of strings.
7045
7046 Valid for create_bundle target. Those flags are directly passed to
7047 xcassets compiler, corresponding to {{xcasset_compiler_flags}} substitution
7048 in compile_xcassets tool.
7049```
[email protected]449f3e42024-08-01 21:43:27 +08007050### <a name="var_xcode_extra_attributes"></a>**xcode_extra_attributes**: [scope] Extra attributes for Xcode projects.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007051
7052```
7053 The value defined in this scope will be copied to the EXTRA_ATTRIBUTES
7054 property of the generated Xcode project. They are only meaningful when
7055 generating with --ide=xcode.
7056
7057 See "gn help create_bundle" for more information.
7058```
[email protected]449f3e42024-08-01 21:43:27 +08007059### <a name="var_xcode_test_application_name"></a>**xcode_test_application_name**: Name for Xcode test target.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007060
7061```
7062 Each unit and ui test target must have a test application target, and this
7063 value is used to specify the relationship. Only meaningful to Xcode (used as
7064 part of the Xcode project generation).
7065
7066 See "gn help create_bundle" for more information.
7067```
7068
Julie Hockette2a29402018-07-31 10:11:42 -07007069#### **Example**
Brett Wilson796ed472018-07-16 15:11:09 -07007070
7071```
7072 create_bundle("chrome_xctest") {
7073 test_application_name = "chrome"
7074 ...
7075 }
7076```
7077## <a name="other"></a>Other help topics
7078
[email protected]449f3e42024-08-01 21:43:27 +08007079### <a name="buildargs"></a>**Build Arguments Overview**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007080
7081```
7082 Build arguments are variables passed in from outside of the build that build
7083 files can query to determine how the build works.
7084```
7085
7086#### **How build arguments are set**
7087
7088```
7089 First, system default arguments are set based on the current system. The
7090 built-in arguments are:
Dirk Pranke7f109842025-04-09 16:48:38 -07007091 - gn_version
Brett Wilson796ed472018-07-16 15:11:09 -07007092 - host_cpu
7093 - host_os
7094 - current_cpu
7095 - current_os
7096 - target_cpu
7097 - target_os
7098
7099 Next, project-specific overrides are applied. These are specified inside
Dirk Pranke7f109842025-04-09 16:48:38 -07007100 the default_args variable of //.gn. See "gn help dotfile" for more. Note
7101 that during processing of the dotfile itself, only `gn_version` is defined.
Brett Wilson796ed472018-07-16 15:11:09 -07007102
7103 If specified, arguments from the --args command line flag are used. If that
7104 flag is not specified, args from previous builds in the build directory will
7105 be used (this is in the file args.gn in the build directory).
7106
7107 Last, for targets being compiled with a non-default toolchain, the toolchain
7108 overrides are applied. These are specified in the toolchain_args section of a
7109 toolchain definition. The use-case for this is that a toolchain may be
7110 building code for a different platform, and that it may want to always
7111 specify Posix, for example. See "gn help toolchain" for more.
7112
7113 If you specify an override for a build argument that never appears in a
7114 "declare_args" call, a nonfatal error will be displayed.
7115```
7116
7117#### **Examples**
7118
7119```
7120 gn args out/FooBar
7121 Create the directory out/FooBar and open an editor. You would type
7122 something like this into that file:
7123 enable_doom_melon=false
7124 os="android"
7125
7126 gn gen out/FooBar --args="enable_doom_melon=true os=\"android\""
7127 This will overwrite the build directory with the given arguments. (Note
7128 that the quotes inside the args command will usually need to be escaped
7129 for your shell to pass through strings values.)
7130```
7131
7132#### **How build arguments are used**
7133
7134```
7135 If you want to use an argument, you use declare_args() and specify default
7136 values. These default values will apply if none of the steps listed in the
7137 "How build arguments are set" section above apply to the given argument, but
7138 the defaults will not override any of these.
7139
7140 Often, the root build config file will declare global arguments that will be
7141 passed to all buildfiles. Individual build files can also specify arguments
7142 that apply only to those files. It is also useful to specify build args in an
7143 "import"-ed file if you want such arguments to apply to multiple buildfiles.
7144```
[email protected]449f3e42024-08-01 21:43:27 +08007145### <a name="dotfile"></a>**.gn file**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007146
7147```
7148 When gn starts, it will search the current directory and parent directories
7149 for a file called ".gn". This indicates the source root. You can override
7150 this detection by using the --root command-line argument
7151
7152 The .gn file in the source root will be executed. The syntax is the same as a
7153 buildfile, but with very limited build setup-specific meaning.
7154
7155 If you specify --root, by default GN will look for the file .gn in that
7156 directory. If you want to specify a different file, you can additionally pass
7157 --dotfile:
7158
7159 gn gen out/Debug --root=/home/build --dotfile=/home/my_gn_file.gn
Dirk Pranke7f109842025-04-09 16:48:38 -07007160
7161 The system variable `gn_version` is available in the dotfile, but none of
7162 the other variables are, because the dotfile is processed before args.gn
7163 or anything else is processed.
Brett Wilson796ed472018-07-16 15:11:09 -07007164```
7165
7166#### **Variables**
7167
7168```
7169 arg_file_template [optional]
7170 Path to a file containing the text that should be used as the default
7171 args.gn content when you run `gn args`.
7172
7173 buildconfig [required]
7174 Path to the build config file. This file will be used to set up the
7175 build file execution environment for each toolchain.
7176
7177 check_targets [optional]
7178 A list of labels and label patterns that should be checked when running
Erik Staab5d109d72020-06-29 22:53:23 -07007179 "gn check" or "gn gen --check". If neither check_targets or
7180 no_check_targets (see below) is specified, all targets will be checked.
7181 It is an error to specify both check_targets and no_check_targets. If it
7182 is the empty list, no targets will be checked. To bypass this list,
7183 request an explicit check of targets, like "//*".
7184
7185 The format of this list is identical to that of "visibility" so see "gn
7186 help visibility" for examples.
7187
7188 no_check_targets [optional]
7189 A list of labels and label patterns that should *not* be checked when
7190 running "gn check" or "gn gen --check". All other targets will be checked.
7191 If neither check_targets (see above) or no_check_targets is specified, all
7192 targets will be checked. It is an error to specify both check_targets and
7193 no_check_targets.
Brett Wilson796ed472018-07-16 15:11:09 -07007194
7195 The format of this list is identical to that of "visibility" so see "gn
7196 help visibility" for examples.
7197
James Robinson49f59032020-01-08 14:05:51 -08007198 check_system_includes [optional]
7199 Boolean to control whether system style includes are checked by default
7200 when running "gn check" or "gn gen --check". System style includes are
7201 includes that use angle brackets <> instead of double quotes "". If this
7202 setting is omitted or set to false, these includes will be ignored by
7203 default. They can be checked explicitly by running
7204 "gn check --check-system" or "gn gen --check=system"
7205
Dirk Prankeed1abc12025-01-10 17:41:03 -08007206 exec_script_allowlist [optional]
Brett Wilson796ed472018-07-16 15:11:09 -07007207 A list of .gn/.gni files (not labels) that have permission to call the
7208 exec_script function. If this list is defined, calls to exec_script will
7209 be checked against this list and GN will fail if the current file isn't
7210 in the list.
7211
7212 This is to allow the use of exec_script to be restricted since is easy to
7213 use inappropriately. Wildcards are not supported. Files in the
7214 secondary_source tree (if defined) should be referenced by ignoring the
7215 secondary tree and naming them as if they are in the main tree.
7216
7217 If unspecified, the ability to call exec_script is unrestricted.
7218
7219 Example:
Dirk Prankeed1abc12025-01-10 17:41:03 -08007220 exec_script_allowlist = [
Brett Wilson796ed472018-07-16 15:11:09 -07007221 "//base/BUILD.gn",
7222 "//build/my_config.gni",
7223 ]
7224
Dirk Prankeed1abc12025-01-10 17:41:03 -08007225 exec_script_whitelist [optional]
7226 A synonym for "exec_script_allowlist" that exists for backwards
7227 compatibility. New code should use "exec_script_allowlist" instead.
7228 If both values are set, only the value in "exec_script_allowlist" will
7229 have any effect (so don't set both!).
7230
Brett Wilson1da84bb2022-09-14 15:35:29 -07007231 export_compile_commands [optional]
7232 A list of label patterns for which to generate a Clang compilation
7233 database (see "gn help label_pattern" for the string format).
7234
7235 When specified, GN will generate a compile_commands.json file in the root
7236 of the build directory containing information on how to compile each
7237 source file reachable from any label matching any pattern in the list.
7238 This is used for Clang-based tooling and some editor integration. See
7239 https://clang.llvm.org/docs/JSONCompilationDatabase.html
7240
7241 The switch --add-export-compile-commands to "gn gen" (see "gn help gen")
7242 appends to this value which provides a per-user way to customize it.
7243
7244 The deprecated switch --export-compile-commands to "gn gen" (see "gn help
7245 gen") adds to the export target list using a different format.
7246
7247 Example:
7248 export_compile_commands = [
7249 "//base/*",
7250 "//tools:doom_melon",
7251 ]
7252
Brett Wilson796ed472018-07-16 15:11:09 -07007253 root [optional]
7254 Label of the root build target. The GN build will start by loading the
7255 build file containing this target name. This defaults to "//:" which will
Harley Li0a9affb2020-06-03 10:38:42 -04007256 cause the file //BUILD.gn to be loaded. Note that build_file_extension
7257 applies to the default case as well.
Brett Wilson796ed472018-07-16 15:11:09 -07007258
Nico Weberad9eab22020-11-15 22:20:28 -05007259 The command-line switch --root-target will override this value (see "gn
7260 help --root-target").
7261
David 'Digit' Turnerb8562a42023-10-23 18:05:37 +02007262 root_patterns [optional]
7263 A list of label pattern strings. When not defined or empty, the GN build
7264 graph will contain all targets from any BUILD.gn evaluated in the default
7265 toolchain context, and their transitive dependencies.
7266
7267 When set to a non empty list, only the targets in the default toolchain
7268 matching these patterns, and their transitive dependencies, will be defined
7269 instead.
7270
7271 The command-line switch --root-pattern will override this value (see
7272 "gn help --root-pattern")
7273
Brett Wilson796ed472018-07-16 15:11:09 -07007274 script_executable [optional]
Brett Wilsond0f8bc92022-04-22 14:01:40 -07007275 By default, GN runs the scripts used in action targets and exec_script
7276 calls using the Python interpreter found in PATH. This value specifies the
7277 Python executable or other interpreter to use instead.
James Robinson61377e32020-02-13 15:20:07 -08007278
Brett Wilsond0f8bc92022-04-22 14:01:40 -07007279 If set to the empty string, the scripts will be executed directly.
7280
7281 The command-line switch --script-executable will override this value (see
7282 "gn help --script-executable")
Brett Wilson796ed472018-07-16 15:11:09 -07007283
7284 secondary_source [optional]
7285 Label of an alternate directory tree to find input files. When searching
7286 for a BUILD.gn file (or the build config file discussed above), the file
7287 will first be looked for in the source root. If it's not found, the
7288 secondary source root will be checked (which would contain a parallel
7289 directory hierarchy).
7290
7291 This behavior is intended to be used when BUILD.gn files can't be checked
7292 in to certain source directories for whatever reason.
7293
7294 The secondary source root must be inside the main source tree.
7295
7296 default_args [optional]
7297 Scope containing the default overrides for declared arguments. These
7298 overrides take precedence over the default values specified in the
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01007299 declare_args() block, but can be overridden using --args or the
Brett Wilson796ed472018-07-16 15:11:09 -07007300 args.gn file.
7301
7302 This is intended to be used when subprojects declare arguments with
7303 default values that need to be changed for whatever reason.
Harley Li0a9affb2020-06-03 10:38:42 -04007304
7305 build_file_extension [optional]
7306 If set to a non-empty string, this is added to the name of all build files
7307 to load.
7308 GN will look for build files named "BUILD.$build_file_extension.gn".
7309 This is intended to be used during migrations or other situations where
7310 there are two independent GN builds in the same directories.
Petr Hosek317fdc12020-05-28 10:23:42 -07007311
7312 ninja_required_version [optional]
7313 When set specifies the minimum required version of Ninja. The default
7314 required version is 1.7.2. Specifying a higher version might enable the
7315 use of some of newer features that can make the build more efficient.
Takuto Ikuta60a28b62024-09-05 17:45:42 +09007316
7317 no_stamp_files [optional]
7318 A boolean flag that can be set to generate Ninja files that use phony
7319 rules instead of stamp files whenever possible. This results in smaller
7320 Ninja build plans, but requires at least Ninja 1.11.
Brett Wilson796ed472018-07-16 15:11:09 -07007321```
7322
7323#### **Example .gn file contents**
7324
7325```
7326 buildconfig = "//build/config/BUILDCONFIG.gn"
7327
7328 check_targets = [
7329 "//doom_melon/*", # Check everything in this subtree.
7330 "//tools:mind_controlling_ant", # Check this specific target.
7331 ]
7332
7333 root = "//:root"
7334
7335 secondary_source = "//build/config/temporary_buildfiles/"
7336
7337 default_args = {
7338 # Default to release builds for this project.
7339 is_debug = false
7340 is_component_build = false
7341 }
7342```
[email protected]449f3e42024-08-01 21:43:27 +08007343### <a name="execution"></a>**Build graph and execution overview**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007344
7345#### **Overall build flow**
7346
7347```
7348 1. Look for ".gn" file (see "gn help dotfile") in the current directory and
7349 walk up the directory tree until one is found. Set this directory to be
7350 the "source root" and interpret this file to find the name of the build
7351 config file.
7352
7353 2. Execute the build config file identified by .gn to set up the global
7354 variables and default toolchain name. Any arguments, variables, defaults,
7355 etc. set up in this file will be visible to all files in the build.
Dirk Pranke12a6f482025-04-09 16:52:34 -07007356 Any values set in the `default_args` scope will be merged into
7357 subsequent `declare_args()` scopes and override the default values.
Brett Wilson796ed472018-07-16 15:11:09 -07007358
Dirk Pranke12a6f482025-04-09 16:52:34 -07007359 3. Process the --args command line option or load the arguments from
7360 the args.gn file in the build directory. These values will be merged
7361 into any subsequent declare_args() scope (after the `default_args`
7362 are merged in) to override the default values. See `help buildargs`
7363 for more on how args are handled.
7364
7365 4. Load the BUILDCONFIG.gn file and create a dedicated scope for it.
7366
7367 5. Load the //BUILD.gn (in the source root directory). The BUILD.gn
Dirk Prankec0a46c52025-04-08 18:09:33 -07007368 file is executed in a scope whose parent scope is the BUILDCONFIG.gn
7369 file, i.e., only the definitions in the BUILDCONFIG.gn file exist.
Brett Wilson796ed472018-07-16 15:11:09 -07007370
Dirk Pranke12a6f482025-04-09 16:52:34 -07007371 5. If the BUILD.gn file imports other files, each of those other
Dirk Prankec0a46c52025-04-08 18:09:33 -07007372 files is executed in a separate scope whose parent is the BUILDCONFIG.gn
7373 file, i.e., no definitions from the importing BUILD.gn file are
7374 available. When the imported file has been fully processed, its scope
7375 is merged into the BUILD.gn file's scope. If there is a conflict
7376 (both the BUILD.gn file and the imported file define some variable
7377 or rule with the same name but different values), a runtime error
7378 will be thrown. See "gn help import" for more on this.
7379
Dirk Pranke12a6f482025-04-09 16:52:34 -07007380 6. Recursively evaluate rules and load BUILD.gn in other directories as
Brett Wilson796ed472018-07-16 15:11:09 -07007381 necessary to resolve dependencies. If a BUILD file isn't found in the
7382 specified location, GN will look in the corresponding location inside
7383 the secondary_source defined in the dotfile (see "gn help dotfile").
Dirk Pranke6d326e92025-04-09 12:49:26 -07007384 Each BUILD.gn file will again be executed in a new scope whose only
7385 parent is BUILDCONFIG.gn's scope.
Brett Wilson796ed472018-07-16 15:11:09 -07007386
Dirk Pranke12a6f482025-04-09 16:52:34 -07007387 7. If a target is referenced using an alternate toolchain, then
7388
7389 1. The toolchain file is loaded in a scope whose parent is the
7390 BUILDCONFIG.gn file.
7391 2. The BUILDCONFIG.gn file is re-loaded and re-parsed into a new
7392 scope, with any `toolchain_args` merged into the defaults. See
7393 `help buildargs` for more on how args are handled.
7394 3. The BUILD.gn containing the target is then parsed as in step 5,
7395 only we use the scope from step 7.2 instead of the default
7396 BUILDCONFIG.gn scope.
7397
7398 8. When a target's dependencies are resolved, write out the `.ninja`
Brett Wilson796ed472018-07-16 15:11:09 -07007399 file to disk.
7400
Dirk Pranke12a6f482025-04-09 16:52:34 -07007401 9. When all targets are resolved, write out the root build.ninja file.
Harley Li0a9affb2020-06-03 10:38:42 -04007402
7403 Note that the BUILD.gn file name may be modulated by .gn arguments such as
7404 build_file_extension.
Brett Wilson796ed472018-07-16 15:11:09 -07007405```
7406
7407#### **Executing target definitions and templates**
7408
7409```
7410 Build files are loaded in parallel. This means it is impossible to
7411 interrogate a target from GN code for any information not derivable from its
7412 label (see "gn help label"). The exception is the get_target_outputs()
7413 function which requires the target being interrogated to have been defined
7414 previously in the same file.
7415
7416 Targets are declared by their type and given a name:
7417
7418 static_library("my_static_library") {
7419 ... target parameter definitions ...
7420 }
7421
7422 There is also a generic "target" function for programmatically defined types
Dirk Prankec0a46c52025-04-08 18:09:33 -07007423 (see "gn help target").
7424
7425 You can define new types using templates (see "gn help template"). A template
7426 defines some custom code that expands to one or more other targets. When a
7427 template is invoked, it is executed in the scope of the file that defined the
7428 template (as described above). To access values from the caller's scope, you
7429 must use the `invoker` variable (see "gn help template" for more on the
7430 invoker).
Brett Wilson796ed472018-07-16 15:11:09 -07007431
7432 Before executing the code inside the target's { }, the target defaults are
7433 applied (see "gn help set_defaults"). It will inject implicit variable
7434 definitions that can be overridden by the target code as necessary. Typically
7435 this mechanism is used to inject a default set of configs that define the
7436 global compiler and linker flags.
7437```
7438
7439#### **Which targets are built**
7440
7441```
7442 All targets encountered in the default toolchain (see "gn help toolchain")
7443 will have build rules generated for them, even if no other targets reference
7444 them. Their dependencies must resolve and they will be added to the implicit
7445 "all" rule (see "gn help ninja_rules").
7446
7447 Targets in non-default toolchains will only be generated when they are
7448 required (directly or transitively) to build a target in the default
7449 toolchain.
7450
Tyler Mandry4a648092022-02-15 19:47:09 +00007451 Some targets might be associated but without a formal build dependency (for
7452 example, related tools or optional variants). A target that is marked as
7453 "generated" can propagate its generated state to an associated target using
7454 "gen_deps". This will make the referenced dependency have Ninja rules
7455 generated in the same cases the source target has but without a build-time
7456 dependency and even in non-default toolchains.
7457
Brett Wilson796ed472018-07-16 15:11:09 -07007458 See also "gn help ninja_rules".
7459```
7460
7461#### **Dependencies**
7462
7463```
7464 The only difference between "public_deps" and "deps" except for pushing
7465 configs around the build tree and allowing includes for the purposes of "gn
7466 check".
7467
7468 A target's "data_deps" are guaranteed to be built whenever the target is
7469 built, but the ordering is not defined. The meaning of this is dependencies
7470 required at runtime. Currently data deps will be complete before the target
7471 is linked, but this is not semantically guaranteed and this is undesirable
7472 from a build performance perspective. Since we hope to change this in the
7473 future, do not rely on this behavior.
7474```
[email protected]449f3e42024-08-01 21:43:27 +08007475### <a name="grammar"></a>**Language and grammar for GN build files**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007476
7477#### **Tokens**
7478
7479```
7480 GN build files are read as sequences of tokens. While splitting the file
7481 into tokens, the next token is the longest sequence of characters that form a
7482 valid token.
7483```
7484
7485#### **White space and comments**
7486
7487```
7488 White space is comprised of spaces (U+0020), horizontal tabs (U+0009),
7489 carriage returns (U+000D), and newlines (U+000A).
7490
7491 Comments start at the character "#" and stop at the next newline.
7492
7493 White space and comments are ignored except that they may separate tokens
7494 that would otherwise combine into a single token.
7495```
7496
7497#### **Identifiers**
7498
7499```
7500 Identifiers name variables and functions.
7501
7502 identifier = letter { letter | digit } .
7503 letter = "A" ... "Z" | "a" ... "z" | "_" .
7504 digit = "0" ... "9" .
7505```
7506
7507#### **Keywords**
7508
7509```
7510 The following keywords are reserved and may not be used as identifiers:
7511
7512 else false if true
7513```
7514
7515#### **Integer literals**
7516
7517```
7518 An integer literal represents a decimal integer value.
7519
7520 integer = [ "-" ] digit { digit } .
7521
7522 Leading zeros and negative zero are disallowed.
7523```
7524
7525#### **String literals**
7526
7527```
7528 A string literal represents a string value consisting of the quoted
7529 characters with possible escape sequences and variable expansions.
7530
7531 string = `"` { char | escape | expansion } `"` .
7532 escape = `\` ( "$" | `"` | char ) .
Nico Weberad9eab22020-11-15 22:20:28 -05007533 BracketExpansion = "{" ( identifier | ArrayAccess | ScopeAccess ) "}" .
Brett Wilson796ed472018-07-16 15:11:09 -07007534 Hex = "0x" [0-9A-Fa-f][0-9A-Fa-f]
7535 expansion = "$" ( identifier | BracketExpansion | Hex ) .
Nico Weberad9eab22020-11-15 22:20:28 -05007536 char = /* any character except "$", `"`, or newline */ .
Brett Wilson796ed472018-07-16 15:11:09 -07007537
7538 After a backslash, certain sequences represent special characters:
7539
7540 \" U+0022 quotation mark
7541 \$ U+0024 dollar sign
7542 \\ U+005C backslash
7543
7544 All other backslashes represent themselves.
7545
7546 To insert an arbitrary byte value, use $0xFF. For example, to insert a
7547 newline character: "Line one$0x0ALine two".
7548
7549 An expansion will evaluate the variable following the '$' and insert a
7550 stringified version of it into the result. For example, to concat two path
7551 components with a slash separating them:
7552 "$var_one/$var_two"
7553 Use the "${var_one}" format to be explicitly deliniate the variable for
7554 otherwise-ambiguous cases.
7555```
7556
7557#### **Punctuation**
7558
7559```
7560 The following character sequences represent punctuation:
7561
7562 + += == != ( )
7563 - -= < <= [ ]
7564 ! = > >= { }
7565 && || . ,
7566```
7567
7568#### **Grammar**
7569
7570```
7571 The input tokens form a syntax tree following a context-free grammar:
7572
7573 File = StatementList .
7574
7575 Statement = Assignment | Call | Condition .
7576 LValue = identifier | ArrayAccess | ScopeAccess .
7577 Assignment = LValue AssignOp Expr .
7578 Call = identifier "(" [ ExprList ] ")" [ Block ] .
7579 Condition = "if" "(" Expr ")" Block
7580 [ "else" ( Condition | Block ) ] .
7581 Block = "{" StatementList "}" .
7582 StatementList = { Statement } .
7583
7584 ArrayAccess = identifier "[" Expr "]" .
7585 ScopeAccess = identifier "." identifier .
7586 Expr = UnaryExpr | Expr BinaryOp Expr .
7587 UnaryExpr = PrimaryExpr | UnaryOp UnaryExpr .
7588 PrimaryExpr = identifier | integer | string | Call
7589 | ArrayAccess | ScopeAccess | Block
7590 | "(" Expr ")"
7591 | "[" [ ExprList [ "," ] ] "]" .
7592 ExprList = Expr { "," Expr } .
7593
7594 AssignOp = "=" | "+=" | "-=" .
7595 UnaryOp = "!" .
7596 BinaryOp = "+" | "-" // highest priority
7597 | "<" | "<=" | ">" | ">="
7598 | "==" | "!="
7599 | "&&"
7600 | "||" . // lowest priority
7601
7602 All binary operators are left-associative.
7603```
7604
7605#### **Types**
7606
7607```
7608 The GN language is dynamically typed. The following types are used:
7609
7610 - Boolean: Uses the keywords "true" and "false". There is no implicit
7611 conversion between booleans and integers.
7612
7613 - Integers: All numbers in GN are signed 64-bit integers.
7614
7615 - Strings: Strings are 8-bit with no enforced encoding. When a string is
7616 used to interact with other systems with particular encodings (like the
7617 Windows and Mac filesystems) it is assumed to be UTF-8. See "String
7618 literals" above for more.
7619
7620 - Lists: Lists are arbitrary-length ordered lists of values. See "Lists"
7621 below for more.
7622
7623 - Scopes: Scopes are like dictionaries that use variable names for keys. See
7624 "Scopes" below for more.
7625```
7626
7627#### **Lists**
7628
7629```
7630 Lists are created with [] and using commas to separate items:
7631
7632 mylist = [ 0, 1, 2, "some string" ]
7633
7634 A comma after the last item is optional. Lists are dereferenced using 0-based
7635 indexing:
7636
7637 mylist[0] += 1
7638 var = mylist[2]
7639
7640 Lists can be concatenated using the '+' and '+=' operators. Bare values can
7641 not be concatenated with lists, to add a single item, it must be put into a
7642 list of length one.
7643
7644 Items can be removed from lists using the '-' and '-=' operators. This will
7645 remove all occurrences of every item in the right-hand list from the
7646 left-hand list. It is an error to remove an item not in the list. This is to
7647 prevent common typos and to detect dead code that is removing things that no
7648 longer apply.
7649
7650 It is an error to use '=' to replace a nonempty list with another nonempty
7651 list. This is to prevent accidentally overwriting data when in most cases
7652 '+=' was intended. To overwrite a list on purpose, first assign it to the
7653 empty list:
7654
7655 mylist = []
7656 mylist = otherlist
Brett Wilson796ed472018-07-16 15:11:09 -07007657```
7658
7659#### **Scopes**
7660
7661```
7662 All execution happens in the context of a scope which holds the current state
7663 (like variables). With the exception of loops and conditions, '{' introduces
Tyler Mandry4a648092022-02-15 19:47:09 +00007664 a new scope.
Brett Wilson796ed472018-07-16 15:11:09 -07007665
Tyler Mandry4a648092022-02-15 19:47:09 +00007666 Most scopes have a parent reference to the old scope. Variable reads
7667 recursively search all parent scopes until the variable is found or there are
7668 no more scopes. Variable writes always go into the current scope. This means
7669 that after the closing '}' (again excepting loops and conditions), all local
7670 variables will be restored to the previous values. This also means that "foo
7671 = foo" can do useful work by copying a variable into the current scope that
7672 was defined in a containing scope.
Brett Wilson796ed472018-07-16 15:11:09 -07007673
Tyler Mandry4a648092022-02-15 19:47:09 +00007674 Scopes can be assigned to variables. Examples of such scopes are the
7675 implicitly-created "invoker" when invoking a template (which refers to the
7676 variables set by the invoking code), scopes created by functions like
7677 exec_script, and scopes explicitly created like
Brett Wilson796ed472018-07-16 15:11:09 -07007678
7679 empty_scope = {}
7680 myvalues = {
7681 foo = 21
7682 bar = "something"
7683 }
7684
Tyler Mandry4a648092022-02-15 19:47:09 +00007685 In the case of explicitly created scopes and scopes created by functions like
7686 exec_script, there is no reference to the parent scope. Such scopes are fully
7687 self-contained and do not "inherit" values from their defining scope.
7688
7689 Inside an explicit scope definition can be any GN code including conditionals
7690 and function calls. After the close of the scope, it will contain all
7691 variables explicitly set by the code contained inside it. After this, the
7692 values can be read, modified, or added to:
Brett Wilson796ed472018-07-16 15:11:09 -07007693
7694 myvalues.foo += 2
7695 empty_scope.new_thing = [ 1, 2, 3 ]
Nate Fischer8ed01d32019-01-08 17:32:01 -08007696
7697 Scope equality is defined as single-level scopes identical within the current
7698 scope. That is, all values in the first scope must be present and identical
7699 within the second, and vice versa. Note that this means inherited scopes are
7700 always unequal by definition.
Brett Wilson796ed472018-07-16 15:11:09 -07007701```
[email protected]449f3e42024-08-01 21:43:27 +08007702### <a name="io_conversion"></a>**Input and output conversion**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007703
7704```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007705 Input and output conversions are arguments to file and process functions
7706 that specify how to convert data to or from external formats. The possible
7707 values for parameters specifying conversions are:
7708
Brett Wilson796ed472018-07-16 15:11:09 -07007709 "" (the default)
Julie Hockett09171292018-07-31 14:35:10 -07007710 input: Discard the result and return None.
7711
7712 output: If value is a list, then "list lines"; otherwise "value".
Brett Wilson796ed472018-07-16 15:11:09 -07007713
7714 "list lines"
Julie Hockett09171292018-07-31 14:35:10 -07007715 input:
7716 Return the file contents as a list, with a string for each line. The
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007717 newlines will not be present in the result. The last line may or may
7718 not end in a newline.
Brett Wilson796ed472018-07-16 15:11:09 -07007719
Julie Hockett09171292018-07-31 14:35:10 -07007720 After splitting, each individual line will be trimmed of whitespace on
7721 both ends.
7722
7723 output:
7724 Renders the value contents as a list, with a string for each line. The
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007725 newlines will not be present in the result. The last line will end in
7726 with a newline.
Brett Wilson796ed472018-07-16 15:11:09 -07007727
7728 "scope"
Julie Hockett09171292018-07-31 14:35:10 -07007729 input:
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007730 Execute the block as GN code and return a scope with the resulting
7731 values in it. If the input was:
Julie Hockett09171292018-07-31 14:35:10 -07007732 a = [ "hello.cc", "world.cc" ]
7733 b = 26
7734 and you read the result into a variable named "val", then you could
7735 access contents the "." operator on "val":
7736 sources = val.a
7737 some_count = val.b
7738
7739 output:
7740 Renders the value contents as a GN code block, reversing the input
7741 result above.
Brett Wilson796ed472018-07-16 15:11:09 -07007742
7743 "string"
Julie Hockett09171292018-07-31 14:35:10 -07007744 input: Return the file contents into a single string.
7745
7746 output:
7747 Render the value contents into a single string. The output is:
7748 a string renders with quotes, e.g. "str"
7749 an integer renders as a stringified integer, e.g. "6"
7750 a boolean renders as the associated string, e.g. "true"
7751 a list renders as a representation of its contents, e.g. "[\"str\", 6]"
7752 a scope renders as a GN code block of its values. If the Value was:
7753 Value val;
7754 val.a = [ "hello.cc", "world.cc" ];
7755 val.b = 26
7756 the resulting output would be:
7757 "{
7758 a = [ \"hello.cc\", \"world.cc\" ]
7759 b = 26
7760 }"
Brett Wilson796ed472018-07-16 15:11:09 -07007761
7762 "value"
Julie Hockett09171292018-07-31 14:35:10 -07007763 input:
7764 Parse the input as if it was a literal rvalue in a buildfile. Examples of
7765 typical program output using this mode:
7766 [ "foo", "bar" ] (result will be a list)
7767 or
7768 "foo bar" (result will be a string)
7769 or
7770 5 (result will be an integer)
Brett Wilson796ed472018-07-16 15:11:09 -07007771
Julie Hockett09171292018-07-31 14:35:10 -07007772 Note that if the input is empty, the result will be a null value which
7773 will produce an error if assigned to a variable.
7774
7775 output:
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007776 Render the value contents as a literal rvalue. Strings render with
7777 escaped quotes.
Brett Wilson796ed472018-07-16 15:11:09 -07007778
7779 "json"
Julie Hockett09171292018-07-31 14:35:10 -07007780 input: Parse the input as a JSON and convert it to equivalent GN rvalue.
7781
7782 output: Convert the Value to equivalent JSON value.
7783
7784 The data type mapping is:
Brett Wilson796ed472018-07-16 15:11:09 -07007785 a string in JSON maps to string in GN
7786 an integer in JSON maps to integer in GN
7787 a float in JSON is unsupported and will result in an error
7788 an object in JSON maps to scope in GN
7789 an array in JSON maps to list in GN
7790 a boolean in JSON maps to boolean in GN
7791 a null in JSON is unsupported and will result in an error
7792
Julie Hockett09171292018-07-31 14:35:10 -07007793 Nota that the input dictionary keys have to be valid GN identifiers
7794 otherwise they will produce an error.
Brett Wilson796ed472018-07-16 15:11:09 -07007795
Julie Hockett09171292018-07-31 14:35:10 -07007796 "trim ..." (input only)
Brett Wilson796ed472018-07-16 15:11:09 -07007797 Prefixing any of the other transformations with the word "trim" will
7798 result in whitespace being trimmed from the beginning and end of the
7799 result before processing.
7800
7801 Examples: "trim string" or "trim list lines"
7802
7803 Note that "trim value" is useless because the value parser skips
7804 whitespace anyway.
7805```
[email protected]449f3e42024-08-01 21:43:27 +08007806### <a name="file_pattern"></a>**File patterns**&nbsp;[Back to Top](#gn-reference)
Sylvain Defresneaff489a2020-03-11 18:27:43 +01007807
7808```
7809 File patterns are VERY limited regular expressions. They must match the
7810 entire input string to be counted as a match. In regular expression parlance,
7811 there is an implicit "^...$" surrounding your input. If you want to match a
7812 substring, you need to use wildcards at the beginning and end.
7813
7814 There are only two special tokens understood by the pattern matcher.
7815 Everything else is a literal.
7816
7817 - "*" Matches zero or more of any character. It does not depend on the
7818 preceding character (in regular expression parlance it is equivalent to
7819 ".*").
7820
7821 - "\b" Matches a path boundary. This will match the beginning or end of a
7822 string, or a slash.
7823```
7824
7825#### **Pattern examples**
7826
7827```
7828 "*asdf*"
7829 Matches a string containing "asdf" anywhere.
7830
7831 "asdf"
7832 Matches only the exact string "asdf".
7833
7834 "*.cc"
7835 Matches strings ending in the literal ".cc".
7836
7837 "\bwin/*"
7838 Matches "win/foo" and "foo/win/bar.cc" but not "iwin/foo".
7839```
[email protected]449f3e42024-08-01 21:43:27 +08007840### <a name="label_pattern"></a>**Label patterns**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007841
7842```
7843 A label pattern is a way of expressing one or more labels in a portion of the
7844 source tree. They are not general regular expressions.
7845
7846 They can take the following forms only:
7847
7848 - Explicit (no wildcard):
7849 "//foo/bar:baz"
7850 ":baz"
7851
7852 - Wildcard target names:
7853 "//foo/bar:*" (all targets in the //foo/bar/BUILD.gn file)
7854 ":*" (all targets in the current build file)
7855
7856 - Wildcard directory names ("*" is only supported at the end)
7857 "*" (all targets)
7858 "//foo/bar/*" (all targets in any subdir of //foo/bar)
7859 "./*" (all targets in the current build file or sub dirs)
7860
Julie Hockette2a29402018-07-31 10:11:42 -07007861 Any of the above forms can additionally take an explicit toolchain
7862 in parenthesis at the end of the label pattern. In this case, the
7863 toolchain must be fully qualified (no wildcards are supported in the
7864 toolchain name).
Brett Wilson796ed472018-07-16 15:11:09 -07007865
Julie Hockette2a29402018-07-31 10:11:42 -07007866 "//foo:bar(//build/toolchain:mac)"
Brett Wilson796ed472018-07-16 15:11:09 -07007867 An explicit target in an explicit toolchain.
7868
7869 ":*(//build/toolchain/linux:32bit)"
7870 All targets in the current build file using the 32-bit Linux toolchain.
7871
7872 "//foo/*(//build/toolchain:win)"
7873 All targets in //foo and any subdirectory using the Windows
7874 toolchain.
7875```
[email protected]449f3e42024-08-01 21:43:27 +08007876### <a name="labels"></a>**About labels**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007877
7878```
7879 Everything that can participate in the dependency graph (targets, configs,
7880 and toolchains) are identified by labels. A common label looks like:
7881
7882 //base/test:test_support
7883
7884 This consists of a source-root-absolute path, a colon, and a name. This means
7885 to look for the thing named "test_support" in "base/test/BUILD.gn".
7886
7887 You can also specify system absolute paths if necessary. Typically such
7888 paths would be specified via a build arg so the developer can specify where
7889 the component is on their system.
7890
7891 /usr/local/foo:bar (Posix)
7892 /C:/Program Files/MyLibs:bar (Windows)
7893```
7894
7895#### **Toolchains**
7896
7897```
7898 A canonical label includes the label of the toolchain being used. Normally,
7899 the toolchain label is implicitly inherited from the current execution
7900 context, but you can override this to specify cross-toolchain dependencies:
7901
7902 //base/test:test_support(//build/toolchain/win:msvc)
7903
7904 Here GN will look for the toolchain definition called "msvc" in the file
7905 "//build/toolchain/win" to know how to compile this target.
7906```
7907
7908#### **Relative labels**
7909
7910```
7911 If you want to refer to something in the same buildfile, you can omit
7912 the path name and just start with a colon. This format is recommended for
7913 all same-file references.
7914
7915 :base
7916
7917 Labels can be specified as being relative to the current directory.
7918 Stylistically, we prefer to use absolute paths for all non-file-local
7919 references unless a build file needs to be run in different contexts (like a
7920 project needs to be both standalone and pulled into other projects in
7921 difference places in the directory hierarchy).
7922
7923 source/plugin:myplugin
7924 ../net:url_request
7925```
7926
7927#### **Implicit names**
7928
7929```
7930 If a name is unspecified, it will inherit the directory name. Stylistically,
7931 we prefer to omit the colon and name when possible:
7932
7933 //net -> //net:net
7934 //tools/gn -> //tools/gn:gn
7935```
[email protected]449f3e42024-08-01 21:43:27 +08007936### <a name="metadata_collection"></a>**Metadata Collection**&nbsp;[Back to Top](#gn-reference)
Julie Hockett152c5142019-07-12 09:53:43 -06007937
7938```
7939 Metadata is information attached to targets throughout the dependency tree. GN
7940 allows for the collection of this data into files written during the generation
Keir Mierle45611e32019-11-12 11:18:00 -08007941 step, enabling users to expose and aggregate this data based on the dependency
Julie Hockett152c5142019-07-12 09:53:43 -06007942 tree.
7943```
7944
7945#### **generated_file targets**
7946
7947```
7948 Similar to the write_file() function, the generated_file target type
7949 creates a file in the specified location with the specified content. The
Keir Mierle45611e32019-11-12 11:18:00 -08007950 primary difference between write_file() and this target type is that the
Julie Hockett152c5142019-07-12 09:53:43 -06007951 write_file function does the file write at parse time, while the
7952 generated_file target type writes at target resolution time. See
7953 "gn help generated_file" for more detail.
7954
Keir Mierle45611e32019-11-12 11:18:00 -08007955 When written at target resolution time, generated_file enables GN to
Julie Hockett152c5142019-07-12 09:53:43 -06007956 collect and write aggregated metadata from dependents.
7957
Keir Mierle45611e32019-11-12 11:18:00 -08007958 A generated_file target can declare either 'contents' to write statically
7959 known contents to a file or 'data_keys' to aggregate metadata and write the
7960 result to a file. It can also specify 'walk_keys' (to restrict the metadata
Julie Hockett152c5142019-07-12 09:53:43 -06007961 collection), 'output_conversion', and 'rebase'.
7962```
7963
7964#### **Collection and Aggregation**
7965
7966```
7967 Targets can declare a 'metadata' variable containing a scope, and this
Keir Mierle45611e32019-11-12 11:18:00 -08007968 metadata may be collected and written out to a file specified by
7969 generated_file aggregation targets. The 'metadata' scope must contain
7970 only list values since the aggregation step collects a list of these values.
Julie Hockett152c5142019-07-12 09:53:43 -06007971
7972 During the target resolution, generated_file targets will walk their
7973 dependencies recursively, collecting metadata based on the specified
7974 'data_keys'. 'data_keys' is specified as a list of strings, used by the walk
7975 to identify which variables in dependencies' 'metadata' scopes to collect.
7976
Keir Mierle45611e32019-11-12 11:18:00 -08007977 The walk begins with the listed dependencies of the 'generated_file' target.
7978 The 'metadata' scope for each dependency is inspected for matching elements
7979 of the 'generated_file' target's 'data_keys' list. If a match is found, the
7980 data from the dependent's matching key list is appended to the aggregate walk
7981 list. Note that this means that if more than one walk key is specified, the
7982 data in all of them will be aggregated into one list. From there, the walk
7983 will then recurse into the dependencies of each target it encounters,
7984 collecting the specified metadata for each.
Julie Hockett152c5142019-07-12 09:53:43 -06007985
7986 For example:
7987
7988 group("a") {
7989 metadata = {
7990 doom_melon = [ "enable" ]
7991 my_files = [ "foo.cpp" ]
7992 my_extra_files = [ "bar.cpp" ]
7993 }
7994
7995 deps = [ ":b" ]
7996 }
7997
7998 group("b") {
7999 metadata = {
8000 my_files = [ "baz.cpp" ]
8001 }
8002 }
8003
8004 generated_file("metadata") {
8005 outputs = [ "$root_build_dir/my_files.json" ]
8006 data_keys = [ "my_files", "my_extra_files" ]
8007
8008 deps = [ ":a" ]
8009 }
8010
8011 The above will produce the following file data:
8012
8013 foo.cpp
8014 bar.cpp
8015 baz.cpp
8016
Keir Mierle45611e32019-11-12 11:18:00 -08008017 The dependency walk can be limited by using the 'walk_keys'. This is a list of
Julie Hockett152c5142019-07-12 09:53:43 -06008018 labels that should be included in the walk. All labels specified here should
8019 also be in one of the deps lists. These keys act as barriers, where the walk
Keir Mierle45611e32019-11-12 11:18:00 -08008020 will only recurse into the targets listed. An empty list in all specified
Julie Hockett152c5142019-07-12 09:53:43 -06008021 barriers will end that portion of the walk.
8022
8023 group("a") {
8024 metadata = {
8025 my_files = [ "foo.cpp" ]
Sylvain Defresne3028c6a2020-07-20 11:28:59 +02008026 my_files_barrier = [ ":b" ]
Julie Hockett152c5142019-07-12 09:53:43 -06008027 }
8028
8029 deps = [ ":b", ":c" ]
8030 }
8031
8032 group("b") {
8033 metadata = {
8034 my_files = [ "bar.cpp" ]
8035 }
8036 }
8037
8038 group("c") {
8039 metadata = {
8040 my_files = [ "doom_melon.cpp" ]
8041 }
8042 }
8043
8044 generated_file("metadata") {
8045 outputs = [ "$root_build_dir/my_files.json" ]
Sylvain Defresne3028c6a2020-07-20 11:28:59 +02008046 data_keys = [ "my_files" ]
8047 walk_keys = [ "my_files_barrier" ]
Julie Hockett152c5142019-07-12 09:53:43 -06008048
8049 deps = [ ":a" ]
8050 }
8051
8052 The above will produce the following file data (note that `doom_melon.cpp` is
8053 not included):
8054
8055 foo.cpp
8056 bar.cpp
8057
8058 A common example of this sort of barrier is in builds that have host tools
8059 built as part of the tree, but do not want the metadata from those host tools
8060 to be collected with the target-side code.
8061```
8062
8063#### **Common Uses**
8064
8065```
8066 Metadata can be used to collect information about the different targets in the
8067 build, and so a common use is to provide post-build tooling with a set of data
8068 necessary to do aggregation tasks. For example, if each test target specifies
8069 the output location of its binary to run in a metadata field, that can be
8070 collected into a single file listing the locations of all tests in the
8071 dependency tree. A local build tool (or continuous integration infrastructure)
8072 can then use that file to know which tests exist, and where, and run them
8073 accordingly.
8074
8075 Another use is in image creation, where a post-build image tool needs to know
8076 various pieces of information about the components it should include in order
8077 to put together the correct image.
8078```
[email protected]449f3e42024-08-01 21:43:27 +08008079### <a name="ninja_rules"></a>**Ninja build rules**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008080
8081#### **The "all" and "default" rules**
8082
8083```
8084 All generated targets (see "gn help execution") will be added to an implicit
8085 build rule called "all" so "ninja all" will always compile everything. The
8086 default rule will be used by Ninja if no specific target is specified (just
8087 typing "ninja"). If there is a target named "default" in the root build file,
8088 it will be the default build rule, otherwise the implicit "all" rule will be
8089 used.
8090```
8091
8092#### **Phony rules**
8093
8094```
8095 GN generates Ninja "phony" rules for targets in the default toolchain. The
8096 phony rules can collide with each other and with the names of generated files
8097 so are generated with the following priority:
8098
8099 1. Actual files generated by the build always take precedence.
8100
8101 2. Targets in the toplevel //BUILD.gn file.
8102
8103 3. Targets in toplevel directories matching the names of the directories.
8104 So "ninja foo" can be used to compile "//foo:foo". This only applies to
8105 the first level of directories since usually these are the most
8106 important (so this won't apply to "//foo/bar:bar").
8107
8108 4. The short names of executables if there is only one executable with that
8109 short name. Use "ninja doom_melon" to compile the
8110 "//tools/fruit:doom_melon" executable.
8111
Sylvain Defresne5e19d2f2022-12-12 18:20:36 +01008112 Note that for Apple platforms, create_bundle targets with a product_type
8113 of "com.apple.product-type.application" are considered as executable
8114 for this rule (as they define application bundles).
8115
Brett Wilson796ed472018-07-16 15:11:09 -07008116 5. The short names of all targets if there is only one target with that
8117 short name.
8118
8119 6. Full label name with no leading slashes. So you can use
8120 "ninja tools/fruit:doom_melon" to build "//tools/fruit:doom_melon".
8121
8122 7. Labels with an implicit name part (when the short names match the
8123 directory). So you can use "ninja foo/bar" to compile "//foo/bar:bar".
8124
8125 These "phony" rules are provided only for running Ninja since this matches
8126 people's historical expectations for building. For consistency with the rest
8127 of the program, GN introspection commands accept explicit labels.
8128
8129 To explicitly compile a target in a non-default toolchain, you must give
8130 Ninja the exact name of the output file relative to the build directory.
8131```
[email protected]449f3e42024-08-01 21:43:27 +08008132### <a name="nogncheck"></a>**nogncheck**: Skip an include line from checking.&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008133
8134```
8135 GN's header checker helps validate that the includes match the build
8136 dependency graph. Sometimes an include might be conditional or otherwise
8137 problematic, but you want to specifically allow it. In this case, it can be
Dirk Prankeed1abc12025-01-10 17:41:03 -08008138 allowlisted.
Brett Wilson796ed472018-07-16 15:11:09 -07008139
8140 Include lines containing the substring "nogncheck" will be excluded from
8141 header checking. The most common case is a conditional include:
8142
8143 #if defined(ENABLE_DOOM_MELON)
8144 #include "tools/doom_melon/doom_melon.h" // nogncheck
8145 #endif
8146
8147 If the build file has a conditional dependency on the corresponding target
8148 that matches the conditional include, everything will always link correctly:
8149
8150 source_set("mytarget") {
8151 ...
8152 if (enable_doom_melon) {
8153 defines = [ "ENABLE_DOOM_MELON" ]
8154 deps += [ "//tools/doom_melon" ]
8155 }
8156
8157 But GN's header checker does not understand preprocessor directives, won't
8158 know it matches the build dependencies, and will flag this include as
8159 incorrect when the condition is false.
8160```
8161
8162#### **More information**
8163
8164```
8165 The topic "gn help check" has general information on how checking works and
8166 advice on fixing problems. Targets can also opt-out of checking, see
8167 "gn help check_includes".
8168```
[email protected]449f3e42024-08-01 21:43:27 +08008169### <a name="runtime_deps"></a>**Runtime dependencies**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008170
8171```
8172 Runtime dependencies of a target are exposed via the "runtime_deps" category
8173 of "gn desc" (see "gn help desc") or they can be written at build generation
8174 time via write_runtime_deps(), or --runtime-deps-list-file (see "gn help
8175 --runtime-deps-list-file").
8176
8177 To a first approximation, the runtime dependencies of a target are the set of
8178 "data" files, data directories, and the shared libraries from all transitive
8179 dependencies. Executables, shared libraries, and loadable modules are
8180 considered runtime dependencies of themselves.
8181```
8182
8183#### **Executables**
8184
8185```
8186 Executable targets and those executable targets' transitive dependencies are
8187 not considered unless that executable is listed in "data_deps". Otherwise, GN
8188 assumes that the executable (and everything it requires) is a build-time
8189 dependency only.
8190```
8191
8192#### **Actions and copies**
8193
8194```
8195 Action and copy targets that are listed as "data_deps" will have all of their
8196 outputs and data files considered as runtime dependencies. Action and copy
8197 targets that are "deps" or "public_deps" will have only their data files
8198 considered as runtime dependencies. These targets can list an output file in
8199 both the "outputs" and "data" lists to force an output file as a runtime
8200 dependency in all cases.
8201
8202 The different rules for deps and data_deps are to express build-time (deps)
8203 vs. run-time (data_deps) outputs. If GN counted all build-time copy steps as
8204 data dependencies, there would be a lot of extra stuff, and if GN counted all
8205 run-time dependencies as regular deps, the build's parallelism would be
8206 unnecessarily constrained.
8207
8208 This rule can sometimes lead to unintuitive results. For example, given the
8209 three targets:
8210 A --[data_deps]--> B --[deps]--> ACTION
8211 GN would say that A does not have runtime deps on the result of the ACTION,
8212 which is often correct. But the purpose of the B target might be to collect
8213 many actions into one logic unit, and the "data"-ness of A's dependency is
8214 lost. Solutions:
8215
8216 - List the outputs of the action in its data section (if the results of
8217 that action are always runtime files).
8218 - Have B list the action in data_deps (if the outputs of the actions are
8219 always runtime files).
8220 - Have B list the action in both deps and data deps (if the outputs might be
8221 used in both contexts and you don't care about unnecessary entries in the
8222 list of files required at runtime).
8223 - Split B into run-time and build-time versions with the appropriate "deps"
8224 for each.
8225```
8226
8227#### **Static libraries and source sets**
8228
8229```
8230 The results of static_library or source_set targets are not considered
8231 runtime dependencies since these are assumed to be intermediate targets only.
8232 If you need to list a static library as a runtime dependency, you can
8233 manually compute the .a/.lib file name for the current platform and list it
8234 in the "data" list of a target (possibly on the static library target
8235 itself).
8236```
8237
8238#### **Multiple outputs**
8239
8240```
8241 Linker tools can specify which of their outputs should be considered when
8242 computing the runtime deps by setting runtime_outputs. If this is unset on
8243 the tool, the default will be the first output only.
8244```
[email protected]449f3e42024-08-01 21:43:27 +08008245### <a name="source_expansion"></a>**How Source Expansion Works**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008246
8247```
8248 Source expansion is used for the action_foreach and copy target types to map
8249 source file names to output file names or arguments.
8250
8251 To perform source expansion in the outputs, GN maps every entry in the
8252 sources to every entry in the outputs list, producing the cross product of
8253 all combinations, expanding placeholders (see below).
8254
8255 Source expansion in the args works similarly, but performing the placeholder
8256 substitution produces a different set of arguments for each invocation of the
8257 script.
8258
8259 If no placeholders are found, the outputs or args list will be treated as a
8260 static list of literal file names that do not depend on the sources.
8261
8262 See "gn help copy" and "gn help action_foreach" for more on how this is
8263 applied.
8264```
8265
8266#### **Placeholders**
8267
8268```
8269 This section discusses only placeholders for actions. There are other
8270 placeholders used in the definition of tools. See "gn help tool" for those.
8271
8272 {{source}}
8273 The name of the source file including directory (*). This will generally
8274 be used for specifying inputs to a script in the "args" variable.
8275 "//foo/bar/baz.txt" => "../../foo/bar/baz.txt"
8276
8277 {{source_file_part}}
8278 The file part of the source including the extension.
8279 "//foo/bar/baz.txt" => "baz.txt"
8280
8281 {{source_name_part}}
8282 The filename part of the source file with no directory or extension. This
8283 will generally be used for specifying a transformation from a source file
8284 to a destination file with the same name but different extension.
8285 "//foo/bar/baz.txt" => "baz"
8286
8287 {{source_dir}}
8288 The directory (*) containing the source file with no trailing slash.
8289 "//foo/bar/baz.txt" => "../../foo/bar"
8290
8291 {{source_root_relative_dir}}
8292 The path to the source file's directory relative to the source root, with
8293 no leading "//" or trailing slashes. If the path is system-absolute,
8294 (beginning in a single slash) this will just return the path with no
8295 trailing slash. This value will always be the same, regardless of whether
8296 it appears in the "outputs" or "args" section.
8297 "//foo/bar/baz.txt" => "foo/bar"
8298
8299 {{source_gen_dir}}
8300 The generated file directory (*) corresponding to the source file's path.
8301 This will be different than the target's generated file directory if the
8302 source file is in a different directory than the BUILD.gn file.
8303 "//foo/bar/baz.txt" => "gen/foo/bar"
8304
8305 {{source_out_dir}}
8306 The object file directory (*) corresponding to the source file's path,
8307 relative to the build directory. this us be different than the target's
8308 out directory if the source file is in a different directory than the
8309 build.gn file.
8310 "//foo/bar/baz.txt" => "obj/foo/bar"
8311
8312 {{source_target_relative}}
8313 The path to the source file relative to the target's directory. This will
8314 generally be used for replicating the source directory layout in the
Robert Sesek252674d2019-05-10 14:08:52 -04008315 output directory. This can only be used in actions and bundle_data
8316 targets. It is an error to use in process_file_template where there is no
8317 "target".
Brett Wilson796ed472018-07-16 15:11:09 -07008318 "//foo/bar/baz.txt" => "baz.txt"
8319```
8320
8321#### **(*) Note on directories**
8322
8323```
8324 Paths containing directories (except the source_root_relative_dir) will be
8325 different depending on what context the expansion is evaluated in. Generally
8326 it should "just work" but it means you can't concatenate strings containing
8327 these values with reasonable results.
8328
8329 Details: source expansions can be used in the "outputs" variable, the "args"
8330 variable, and in calls to "process_file_template". The "args" are passed to a
8331 script which is run from the build directory, so these directories will
8332 relative to the build directory for the script to find. In the other cases,
8333 the directories will be source- absolute (begin with a "//") because the
8334 results of those expansions will be handled by GN internally.
8335```
8336
8337#### **Examples**
8338
8339```
8340 Non-varying outputs:
8341 action("hardcoded_outputs") {
8342 sources = [ "input1.idl", "input2.idl" ]
8343 outputs = [ "$target_out_dir/output1.dat",
8344 "$target_out_dir/output2.dat" ]
8345 }
8346 The outputs in this case will be the two literal files given.
8347
8348 Varying outputs:
8349 action_foreach("varying_outputs") {
8350 sources = [ "input1.idl", "input2.idl" ]
8351 outputs = [ "{{source_gen_dir}}/{{source_name_part}}.h",
8352 "{{source_gen_dir}}/{{source_name_part}}.cc" ]
8353 }
8354 Performing source expansion will result in the following output names:
8355 //out/Debug/obj/mydirectory/input1.h
8356 //out/Debug/obj/mydirectory/input1.cc
8357 //out/Debug/obj/mydirectory/input2.h
8358 //out/Debug/obj/mydirectory/input2.cc
8359```
[email protected]449f3e42024-08-01 21:43:27 +08008360### <a name="switch_list"></a>**Available global switches**&nbsp;[Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008361
8362```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08008363 Do "gn help --the_switch_you_want_help_on" for more. Individual commands may
8364 take command-specific switches not listed here. See the help on your specific
8365 command for more.
8366```
8367```
8368 * --args: Specifies build arguments overrides.
8369 * --color: Force colored output.
8370 * --dotfile: Override the name of the ".gn" file.
8371 * --fail-on-unused-args: Treat unused build args as fatal errors.
8372 * --markdown: Write help output in the Markdown format.
RJ Ascani6966efb2020-10-19 16:50:11 -07008373 * --ninja-executable: Set the Ninja executable.
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08008374 * --nocolor: Force non-colored output.
8375 * -q: Quiet mode. Don't print output on success.
8376 * --root: Explicitly specify source root.
David 'Digit' Turner85cc21e2025-04-25 17:28:31 +02008377 * --root-pattern: Add root pattern override.
Nico Weberad9eab22020-11-15 22:20:28 -05008378 * --root-target: Override the root target.
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08008379 * --runtime-deps-list-file: Save runtime dependencies for targets in file.
8380 * --script-executable: Set the executable used to execute scripts.
8381 * --threads: Specify number of worker threads.
8382 * --time: Outputs a summary of how long everything took.
8383 * --tracelog: Writes a Chrome-compatible trace log to the given file.
8384 * -v: Verbose logging.
8385 * --version: Prints the GN version number and exits.
Brett Wilson796ed472018-07-16 15:11:09 -07008386```
8387