blob: 2c8aa92ce3b7e1330d1fb7ee68a32055bf017dd7 [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)
57 * [pool: Defines a pool object.](#func_pool)
58 * [print: Prints to the console.](#func_print)
Aaron Wood24062bb2022-04-25 20:37:48 -070059 * [print_stack_trace: Prints a stack trace.](#func_print_stack_trace)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080060 * [process_file_template: Do template expansion over a list of files.](#func_process_file_template)
61 * [read_file: Read a file into a variable.](#func_read_file)
62 * [rebase_path: Rebase a file or directory to another location.](#func_rebase_path)
63 * [set_default_toolchain: Sets the default toolchain name.](#func_set_default_toolchain)
64 * [set_defaults: Set default values for a target type.](#func_set_defaults)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080065 * [split_list: Splits a list into N different sub-lists.](#func_split_list)
Keir Mierle6ae63302019-11-08 23:02:18 -080066 * [string_join: Concatenates a list of strings with a separator.](#func_string_join)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080067 * [string_replace: Replaces substring in the given string.](#func_string_replace)
Keir Mierle6ae63302019-11-08 23:02:18 -080068 * [string_split: Split string into a list of strings.](#func_string_split)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080069 * [template: Define a template rule.](#func_template)
70 * [tool: Specify arguments to a toolchain tool.](#func_tool)
71 * [toolchain: Defines a toolchain.](#func_toolchain)
72 * [write_file: Write a file to disk.](#func_write_file)
Brett Wilson796ed472018-07-16 15:11:09 -070073* [Built-in predefined variables](#predefined_variables)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080074 * [current_cpu: [string] The processor architecture of the current toolchain.](#var_current_cpu)
75 * [current_os: [string] The operating system of the current toolchain.](#var_current_os)
76 * [current_toolchain: [string] Label of the current toolchain.](#var_current_toolchain)
77 * [default_toolchain: [string] Label of the default toolchain.](#var_default_toolchain)
James Robinson61377e32020-02-13 15:20:07 -080078 * [gn_version: [number] The version of gn.](#var_gn_version)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080079 * [host_cpu: [string] The processor architecture that GN is running on.](#var_host_cpu)
80 * [host_os: [string] The operating system that GN is running on.](#var_host_os)
81 * [invoker: [string] The invoking scope inside a template.](#var_invoker)
82 * [python_path: [string] Absolute path of Python.](#var_python_path)
83 * [root_build_dir: [string] Directory where build commands are run.](#var_root_build_dir)
84 * [root_gen_dir: [string] Directory for the toolchain's generated files.](#var_root_gen_dir)
85 * [root_out_dir: [string] Root directory for toolchain output files.](#var_root_out_dir)
86 * [target_cpu: [string] The desired cpu architecture for the build.](#var_target_cpu)
87 * [target_gen_dir: [string] Directory for a target's generated files.](#var_target_gen_dir)
88 * [target_name: [string] The name of the current target.](#var_target_name)
89 * [target_os: [string] The desired operating system for the build.](#var_target_os)
90 * [target_out_dir: [string] Directory for target output files.](#var_target_out_dir)
Brett Wilson796ed472018-07-16 15:11:09 -070091* [Variables you set in targets](#target_variables)
Julie Hockettce1fa072019-05-07 17:44:37 -070092 * [aliased_deps: [scope] Set of crate-dependency pairs.](#var_aliased_deps)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080093 * [all_dependent_configs: [label list] Configs to be forced on dependents.](#var_all_dependent_configs)
94 * [allow_circular_includes_from: [label list] Permit includes from deps.](#var_allow_circular_includes_from)
95 * [arflags: [string list] Arguments passed to static_library archiver.](#var_arflags)
96 * [args: [string list] Arguments passed to an action.](#var_args)
97 * [asmflags: [string list] Flags passed to the assembler.](#var_asmflags)
98 * [assert_no_deps: [label pattern list] Ensure no deps on these targets.](#var_assert_no_deps)
Sylvain Defresne89e64252020-08-07 13:01:06 +020099 * [bridge_header: [string] Path to C/Objective-C compatibility header.](#var_bridge_header)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800100 * [bundle_contents_dir: Expansion of {{bundle_contents_dir}} in create_bundle.](#var_bundle_contents_dir)
101 * [bundle_deps_filter: [label list] A list of labels that are filtered out.](#var_bundle_deps_filter)
102 * [bundle_executable_dir: Expansion of {{bundle_executable_dir}} in create_bundle](#var_bundle_executable_dir)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800103 * [bundle_resources_dir: Expansion of {{bundle_resources_dir}} in create_bundle.](#var_bundle_resources_dir)
104 * [bundle_root_dir: Expansion of {{bundle_root_dir}} in create_bundle.](#var_bundle_root_dir)
105 * [cflags: [string list] Flags passed to all C compiler variants.](#var_cflags)
106 * [cflags_c: [string list] Flags passed to the C compiler.](#var_cflags_c)
107 * [cflags_cc: [string list] Flags passed to the C++ compiler.](#var_cflags_cc)
108 * [cflags_objc: [string list] Flags passed to the Objective C compiler.](#var_cflags_objc)
109 * [cflags_objcc: [string list] Flags passed to the Objective C++ compiler.](#var_cflags_objcc)
110 * [check_includes: [boolean] Controls whether a target's files are checked.](#var_check_includes)
Sylvain Defresnef07499a2024-04-04 13:06:37 +0200111 * [code_signing_args: [string list] [deprecated] Args for the post-processing script.](#var_code_signing_args)
112 * [code_signing_outputs: [file list] [deprecated] Outputs of the post-processing step.](#var_code_signing_outputs)
113 * [code_signing_script: [file name] [deprecated] Script for the post-processing step.](#var_code_signing_script)
114 * [code_signing_sources: [file list] [deprecated] Sources for the post-processing step.](#var_code_signing_sources)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800115 * [complete_static_lib: [boolean] Links all deps into a static library.](#var_complete_static_lib)
116 * [configs: [label list] Configs applying to this target or config.](#var_configs)
117 * [contents: Contents to write to file.](#var_contents)
Julie Hockettce1fa072019-05-07 17:44:37 -0700118 * [crate_name: [string] The name for the compiled crate.](#var_crate_name)
119 * [crate_root: [string] The root source file for a binary or library.](#var_crate_root)
120 * [crate_type: [string] The type of linkage to use on a shared_library.](#var_crate_type)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800121 * [data: [file list] Runtime data file dependencies.](#var_data)
122 * [data_deps: [label list] Non-linked dependencies.](#var_data_deps)
123 * [data_keys: [string list] Keys from which to collect metadata.](#var_data_keys)
124 * [defines: [string list] C preprocessor defines.](#var_defines)
125 * [depfile: [string] File name for input dependencies for actions.](#var_depfile)
126 * [deps: [label list] Private linked dependencies.](#var_deps)
Petr Hoseka1413862020-01-03 12:54:33 -0800127 * [externs: [scope] Set of Rust crate-dependency pairs.](#var_externs)
Sylvain Defresnea09ec162020-01-16 12:36:40 +0100128 * [framework_dirs: [directory list] Additional framework search directories.](#var_framework_dirs)
129 * [frameworks: [name list] Name of frameworks that must be linked.](#var_frameworks)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800130 * [friend: [label pattern list] Allow targets to include private headers.](#var_friend)
Tyler Mandry4a648092022-02-15 19:47:09 +0000131 * [gen_deps: [label list] Declares targets that should generate when this one does.](#var_gen_deps)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800132 * [include_dirs: [directory list] Additional include directories.](#var_include_dirs)
133 * [inputs: [file list] Additional compile-time dependencies.](#var_inputs)
134 * [ldflags: [string list] Flags passed to the linker.](#var_ldflags)
135 * [lib_dirs: [directory list] Additional library directories.](#var_lib_dirs)
136 * [libs: [string list] Additional libraries to link.](#var_libs)
137 * [metadata: [scope] Metadata of this target.](#var_metadata)
Joseph Ryanad1e5ce2023-04-26 13:48:01 -0700138 * [mnemonic: [string] Prefix displayed when ninja runs this action.](#var_mnemonic)
Sylvain Defresne89e64252020-08-07 13:01:06 +0200139 * [module_name: [string] The name for the compiled module.](#var_module_name)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800140 * [output_conversion: Data format for generated_file targets.](#var_output_conversion)
141 * [output_dir: [directory] Directory to put output file in.](#var_output_dir)
142 * [output_extension: [string] Value to use for the output's file extension.](#var_output_extension)
143 * [output_name: [string] Name for the output file other than the default.](#var_output_name)
144 * [output_prefix_override: [boolean] Don't use prefix for output name.](#var_output_prefix_override)
145 * [outputs: [file list] Output files for actions and copy targets.](#var_outputs)
146 * [partial_info_plist: [filename] Path plist from asset catalog compiler.](#var_partial_info_plist)
Petr Hosek7a6231e2022-10-22 23:14:18 +0000147 * [pool: [string] Label of the pool used by binary targets and actions.](#var_pool)
Sylvain Defresnef07499a2024-04-04 13:06:37 +0200148 * [post_processing_args: [string list] Args for the post-processing script.](#var_post_processing_args)
149 * [post_processing_outputs: [file list] Outputs of the post-processing step.](#var_post_processing_outputs)
150 * [post_processing_script: [file name] Script for the post-processing step.](#var_post_processing_script)
151 * [post_processing_sources: [file list] Sources for the post-processing step.](#var_post_processing_sources)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800152 * [precompiled_header: [string] Header file to precompile.](#var_precompiled_header)
153 * [precompiled_header_type: [string] "gcc" or "msvc".](#var_precompiled_header_type)
154 * [precompiled_source: [file name] Source file to precompile.](#var_precompiled_source)
Sylvain Defresnee5aee7b2023-06-08 10:08:10 -0400155 * [product_type: [string] Product type for the bundle.](#var_product_type)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800156 * [public: [file list] Declare public header files for a target.](#var_public)
157 * [public_configs: [label list] Configs applied to dependents.](#var_public_configs)
158 * [public_deps: [label list] Declare public dependencies.](#var_public_deps)
159 * [rebase: [boolean] Rebase collected metadata as files.](#var_rebase)
160 * [response_file_contents: [string list] Contents of .rsp file for actions.](#var_response_file_contents)
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +0100161 * [rustflags: [string list] Flags passed to the Rust compiler.](#var_rustflags)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800162 * [script: [file name] Script file for actions.](#var_script)
163 * [sources: [file list] Source files for a target.](#var_sources)
Sylvain Defresne89e64252020-08-07 13:01:06 +0200164 * [swiftflags: [string list] Flags passed to the swift compiler.](#var_swiftflags)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800165 * [testonly: [boolean] Declares a target must only be used for testing.](#var_testonly)
Sylvain Defresnee5aee7b2023-06-08 10:08:10 -0400166 * [transparent: [bool] True if the bundle is transparent.](#var_transparent)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800167 * [visibility: [label list] A list of labels that can depend on a target.](#var_visibility)
168 * [walk_keys: [string list] Key(s) for managing the metadata collection walk.](#var_walk_keys)
Robert Sesekd0a6f072020-05-15 11:21:22 -0400169 * [weak_frameworks: [name list] Name of frameworks that must be weak linked.](#var_weak_frameworks)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800170 * [write_runtime_deps: Writes the target's runtime_deps to the given path.](#var_write_runtime_deps)
Harley Li0a9affb2020-06-03 10:38:42 -0400171 * [xcasset_compiler_flags: [string list] Flags passed to xcassets compiler](#var_xcasset_compiler_flags)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800172 * [xcode_extra_attributes: [scope] Extra attributes for Xcode projects.](#var_xcode_extra_attributes)
173 * [xcode_test_application_name: [string] Name for Xcode test target.](#var_xcode_test_application_name)
Brett Wilson796ed472018-07-16 15:11:09 -0700174* [Other help topics](#other)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800175 * all: Print all the help at once
Brett Wilson796ed472018-07-16 15:11:09 -0700176 * [buildargs: How build arguments work.](#buildargs)
177 * [dotfile: Info about the toplevel .gn file.](#dotfile)
178 * [execution: Build graph and execution overview.](#execution)
179 * [grammar: Language and grammar for GN build files.](#grammar)
Julie Hockett81ee1962019-05-13 11:24:42 -0700180 * [input_conversion: Processing input from exec_script and read_file.](#io_conversion)
Sylvain Defresneaff489a2020-03-11 18:27:43 +0100181 * [file_pattern: Matching more than one file.](#file_pattern)
Brett Wilson796ed472018-07-16 15:11:09 -0700182 * [label_pattern: Matching more than one label.](#label_pattern)
183 * [labels: About labels.](#labels)
Julie Hockett152c5142019-07-12 09:53:43 -0600184 * [metadata_collection: About metadata and its collection.](#metadata_collection)
Brett Wilson796ed472018-07-16 15:11:09 -0700185 * [ninja_rules: How Ninja build rules are named.](#ninja_rules)
186 * [nogncheck: Annotating includes for checking.](#nogncheck)
Julie Hockett81ee1962019-05-13 11:24:42 -0700187 * [output_conversion: Specifies how to transform a value to output.](#io_conversion)
Brett Wilson796ed472018-07-16 15:11:09 -0700188 * [runtime_deps: How runtime dependency computation works.](#runtime_deps)
189 * [source_expansion: Map sources to outputs for scripts.](#source_expansion)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800190 * [switches: Show available command-line switches.](#switch_list)
Brett Wilson796ed472018-07-16 15:11:09 -0700191
192## Commands
193
[email protected]449f3e42024-08-01 21:43:27 +0800194### **gn analyze <out_dir> <input_path> <output_path>** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700195
196```
197 Analyze which targets are affected by a list of files.
198
199 This command takes three arguments:
200
201 out_dir is the path to the build directory.
202
203 input_path is a path to a file containing a JSON object with three fields:
204
205 - "files": A list of the filenames to check.
206
207 - "test_targets": A list of the labels for targets that are needed to run
208 the tests we wish to run.
209
Nico Weberdba01722021-04-06 08:56:46 -0400210 - "additional_compile_targets" (optional): A list of the labels for targets
211 that we wish to rebuild, but aren't necessarily needed for testing. The
212 important difference between this field and "test_targets" is that if an
213 item in the additional_compile_targets list refers to a group, then any
Brett Wilson796ed472018-07-16 15:11:09 -0700214 dependencies of that group will be returned if they are out of date, but
215 the group itself does not need to be. If the dependencies themselves are
216 groups, the same filtering is repeated. This filtering can be used to
217 avoid rebuilding dependencies of a group that are unaffected by the input
218 files. The list may also contain the string "all" to refer to a
219 pseudo-group that contains every root target in the build graph.
220
221 This filtering behavior is also known as "pruning" the list of compile
222 targets.
223
Nico Weberdba01722021-04-06 08:56:46 -0400224 If "additional_compile_targets" is absent, it defaults to the empty list.
225
Keir Mierle45611e32019-11-12 11:18:00 -0800226 If input_path is -, input is read from stdin.
227
Brett Wilson796ed472018-07-16 15:11:09 -0700228 output_path is a path indicating where the results of the command are to be
229 written. The results will be a file containing a JSON object with one or more
230 of following fields:
231
232 - "compile_targets": A list of the labels derived from the input
233 compile_targets list that are affected by the input files. Due to the way
234 the filtering works for compile targets as described above, this list may
235 contain targets that do not appear in the input list.
236
237 - "test_targets": A list of the labels from the input test_targets list that
238 are affected by the input files. This list will be a proper subset of the
239 input list.
240
241 - "invalid_targets": A list of any names from the input that do not exist in
242 the build graph. If this list is non-empty, the "error" field will also be
243 set to "Invalid targets".
244
245 - "status": A string containing one of three values:
246
247 - "Found dependency"
248 - "No dependency"
Sylvain Defresne7b0690e2020-06-26 15:33:01 +0200249 - "Found dependency (all)"
Brett Wilson796ed472018-07-16 15:11:09 -0700250
251 In the first case, the lists returned in compile_targets and test_targets
252 should be passed to ninja to build. In the second case, nothing was
253 affected and no build is necessary. In the third case, GN could not
254 determine the correct answer and returned the input as the output in order
255 to be safe.
256
257 - "error": This will only be present if an error occurred, and will contain
258 a string describing the error. This includes cases where the input file is
259 not in the right format, or contains invalid targets.
260
Keir Mierle45611e32019-11-12 11:18:00 -0800261 If output_path is -, output is written to stdout.
262
Brett Wilson796ed472018-07-16 15:11:09 -0700263 The command returns 1 if it is unable to read the input file or write the
264 output file, or if there is something wrong with the build such that gen
265 would also fail, and 0 otherwise. In particular, it returns 0 even if the
266 "error" key is non-empty and a non-fatal error occurred. In other words, it
267 tries really hard to always write something to the output JSON and convey
268 errors that way rather than via return codes.
269```
[email protected]449f3e42024-08-01 21:43:27 +0800270### **gn args**: (command-line tool) [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700271
272```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800273 Display or configure arguments declared by the build.
274
275 gn args [--list] [--short] [--args] [--overrides-only]
276
Brett Wilson796ed472018-07-16 15:11:09 -0700277 See also "gn help buildargs" for a more high-level overview of how
278 build arguments work.
279```
280
281#### **Usage**
282
283```
284 gn args
285 Open the arguments for the given build directory in an editor. If the
286 given build directory doesn't exist, it will be created and an empty args
287 file will be opened in the editor. You would type something like this
288 into that file:
289 enable_doom_melon=false
290 os="android"
291
292 To find your editor on Posix, GN will search the environment variables in
293 order: GN_EDITOR, VISUAL, and EDITOR. On Windows GN will open the command
294 associated with .txt files.
295
296 Note: you can edit the build args manually by editing the file "args.gn"
297 in the build directory and then running "gn gen ".
298
299 gn args --list[=] [--short] [--overrides-only] [--json]
300 Lists all build arguments available in the current configuration, or, if
301 an exact_arg is specified for the list flag, just that one build
302 argument.
303
304 The output will list the declaration location, current value for the
305 build, default value (if different than the current value), and comment
306 preceding the declaration.
307
308 If --short is specified, only the names and current values will be
309 printed.
310
311 If --overrides-only is specified, only the names and current values of
312 arguments that have been overridden (i.e. non-default arguments) will
313 be printed. Overrides come from the /args.gn file and //.gn
314
315 If --json is specified, the output will be emitted in json format.
316 JSON schema for output:
317 [
318 {
319 "name": variable_name,
320 "current": {
321 "value": overridden_value,
322 "file": file_name,
323 "line": line_no
324 },
325 "default": {
326 "value": default_value,
327 "file": file_name,
328 "line": line_no
329 },
330 "comment": comment_string
331 },
332 ...
333 ]
334```
335
336#### **Examples**
337
338```
339 gn args out/Debug
340 Opens an editor with the args for out/Debug.
341
342 gn args out/Debug --list --short
343 Prints all arguments with their default values for the out/Debug
344 build.
345
346 gn args out/Debug --list --short --overrides-only
347 Prints overridden arguments for the out/Debug build.
348
349 gn args out/Debug --list=target_cpu
350 Prints information about the "target_cpu" argument for the "
351 "out/Debug
352 build.
353
354 gn args --list --args="os=\"android\" enable_doom_melon=true"
355 Prints all arguments with the default values for a build with the
356 given arguments set (which may affect the values of other
357 arguments).
358```
[email protected]449f3e42024-08-01 21:43:27 +0800359### **gn check <out_dir> [<label_pattern>] [\--force] [\--check-generated]** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700360
361```
362 GN's include header checker validates that the includes for C-like source
363 files match the build dependency graph.
364
365 "gn check" is the same thing as "gn gen" with the "--check" flag except that
366 this command does not write out any build files. It's intended to be an easy
367 way to manually trigger include file checking.
368
369 The can take exact labels or patterns that match more than
370 one (although not general regular expressions). If specified, only those
371 matching targets will be checked. See "gn help label_pattern" for details.
372```
373
374#### **Command-specific switches**
375
376```
Joe Armstrong39413942019-03-15 10:34:03 +0800377 --check-generated
378 Generated files are normally not checked since they do not exist
379 until after a build. With this flag, those generated files that
380 can be found on disk are also checked.
James Robinson49f59032020-01-08 14:05:51 -0800381
382 --check-system
383 Check system style includes (using ) in addition to
384 "double quote" includes.
Robert Sesekd0a6f072020-05-15 11:21:22 -0400385
386 --default-toolchain
387 Normally wildcard targets are matched in all toolchains. This
388 switch makes wildcard labels with no explicit toolchain reference
389 only match targets in the default toolchain.
390
391 Non-wildcard inputs with no explicit toolchain specification will
392 always match only a target in the default toolchain if one exists.
393
394 --force
395 Ignores specifications of "check_includes = false" and checks all
396 target's files that match the target label.
Brett Wilson796ed472018-07-16 15:11:09 -0700397```
398
399#### **What gets checked**
400
401```
Nate Fischer8ed01d32019-01-08 17:32:01 -0800402 The .gn file may specify a list of targets to be checked in the list
Erik Staab5d109d72020-06-29 22:53:23 -0700403 check_targets (see "gn help dotfile"). Alternatively, the .gn file may
404 specify a list of targets not to be checked in no_check_targets. If a label
405 pattern is specified on the command line, neither check_targets or
406 no_check_targets is used.
Brett Wilson796ed472018-07-16 15:11:09 -0700407
408 Targets can opt-out from checking with "check_includes = false" (see
409 "gn help check_includes").
410
411 For targets being checked:
412
413 - GN opens all C-like source files in the targets to be checked and scans
414 the top for includes.
415
Joe Armstrong39413942019-03-15 10:34:03 +0800416 - Generated files (that might not exist yet) are ignored unless
417 the --check-generated flag is provided.
418
Brett Wilson796ed472018-07-16 15:11:09 -0700419 - Includes with a "nogncheck" annotation are skipped (see
420 "gn help nogncheck").
421
James Robinson49f59032020-01-08 14:05:51 -0800422 - Includes using "quotes" are always checked.
423 If system style checking is enabled, includes using
424 are also checked.
Brett Wilson796ed472018-07-16 15:11:09 -0700425
426 - Include paths are assumed to be relative to any of the "include_dirs" for
427 the target (including the implicit current dir).
428
429 - GN does not run the preprocessor so will not understand conditional
430 includes.
431
432 - Only includes matching known files in the build are checked: includes
433 matching unknown paths are ignored.
434
435 For an include to be valid:
436
437 - The included file must be in the current target, or there must be a path
438 following only public dependencies to a target with the file in it
439 ("gn path" is a good way to diagnose problems).
440
441 - There can be multiple targets with an included file: only one needs to be
442 valid for the include to be allowed.
443
444 - If there are only "sources" in a target, all are considered to be public
445 and can be included by other targets with a valid public dependency path.
446
447 - If a target lists files as "public", only those files are able to be
448 included by other targets. Anything in the sources will be considered
449 private and will not be includable regardless of dependency paths.
450
451 - Outputs from actions are treated like public sources on that target.
452
453 - A target can include headers from a target that depends on it if the
454 other target is annotated accordingly. See "gn help
455 allow_circular_includes_from".
456```
457
458#### **Advice on fixing problems**
459
460```
461 If you have a third party project that is difficult to fix or doesn't care
462 about include checks it's generally best to exclude that target from checking
463 altogether via "check_includes = false".
464
465 If you have conditional includes, make sure the build conditions and the
466 preprocessor conditions match, and annotate the line with "nogncheck" (see
467 "gn help nogncheck" for an example).
468
469 If two targets are hopelessly intertwined, use the
470 "allow_circular_includes_from" annotation. Ideally each should have identical
471 dependencies so configs inherited from those dependencies are consistent (see
472 "gn help allow_circular_includes_from").
473
474 If you have a standalone header file or files that need to be shared between
475 a few targets, you can consider making a source_set listing only those
476 headers as public sources. With only header files, the source set will be a
477 no-op from a build perspective, but will give a central place to refer to
478 those headers. That source set's files will still need to pass "gn check" in
479 isolation.
480
481 In rare cases it makes sense to list a header in more than one target if it
482 could be considered conceptually a member of both.
483```
484
485#### **Examples**
486
487```
488 gn check out/Debug
489 Check everything.
490
491 gn check out/Default //foo:bar
492 Check only the files in the //foo:bar target.
493
494 gn check out/Default "//foo/*
495 Check only the files in targets in the //foo directory tree.
496```
[email protected]449f3e42024-08-01 21:43:27 +0800497### **gn clean <out_dir>...** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700498
499```
500 Deletes the contents of the output directory except for args.gn and
501 creates a Ninja build environment sufficient to regenerate the build.
502```
[email protected]449f3e42024-08-01 21:43:27 +0800503### **gn clean_stale [\--ninja-executable=...] <out_dir>...** [Back to Top](#gn-reference)
RJ Ascani4e260f12020-10-19 17:41:51 -0700504
505```
506 Removes the no longer needed output files from the build directory and prunes
507 their records from the ninja build log and dependency database. These are
508 output files that were generated from previous builds, but the current build
509 graph no longer references them.
510
511 This command requires a ninja executable of at least version 1.10.0. The
512 executable must be provided by the --ninja-executable switch.
513```
514
515#### **Options**
516
517```
518 --ninja-executable=
519 Can be used to specify the ninja executable to use.
520```
[email protected]449f3e42024-08-01 21:43:27 +0800521### **gn desc** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700522
523```
Joe Armstrongb199e542019-03-21 09:40:08 +0800524 gn desc
525 [--format=json]
526
Julie Hockette2a29402018-07-31 10:11:42 -0700527 Displays information about a given target or config. The build parameters
528 will be taken for the build in the given .
Brett Wilson796ed472018-07-16 15:11:09 -0700529
530 The
531 pattern (see "gn help label_pattern"). A label pattern will only match
532 targets.
533```
534
Nico Weber75eb3c72018-08-28 16:01:52 -0400535#### **Possibilities for <what to show>**
Brett Wilson796ed472018-07-16 15:11:09 -0700536
537```
538 (If unspecified an overall summary will be displayed.)
539
540 all_dependent_configs
541 allow_circular_includes_from
542 arflags [--blame]
543 args
544 cflags [--blame]
Julie Hockette2a29402018-07-31 10:11:42 -0700545 cflags_c [--blame]
Brett Wilson796ed472018-07-16 15:11:09 -0700546 cflags_cc [--blame]
Brett Wilson796ed472018-07-16 15:11:09 -0700547 check_includes
548 configs [--tree] (see below)
Nate Fischer8ed01d32019-01-08 17:32:01 -0800549 data_keys
Brett Wilson796ed472018-07-16 15:11:09 -0700550 defines [--blame]
551 depfile
552 deps [--all] [--tree] (see below)
Sylvain Defresnea09ec162020-01-16 12:36:40 +0100553 framework_dirs
554 frameworks
Brett Wilson796ed472018-07-16 15:11:09 -0700555 include_dirs [--blame]
556 inputs
557 ldflags [--blame]
558 lib_dirs
559 libs
Nate Fischer8ed01d32019-01-08 17:32:01 -0800560 metadata
561 output_conversion
Brett Wilson796ed472018-07-16 15:11:09 -0700562 outputs
563 public_configs
564 public
Nate Fischer8ed01d32019-01-08 17:32:01 -0800565 rebase
Brett Wilson796ed472018-07-16 15:11:09 -0700566 script
567 sources
568 testonly
569 visibility
Nate Fischer8ed01d32019-01-08 17:32:01 -0800570 walk_keys
Robert Sesekd0a6f072020-05-15 11:21:22 -0400571 weak_frameworks
Brett Wilson796ed472018-07-16 15:11:09 -0700572
573 runtime_deps
574 Compute all runtime deps for the given target. This is a computed list
575 and does not correspond to any GN variable, unlike most other values
576 here.
577
578 The output is a list of file names relative to the build directory. See
579 "gn help runtime_deps" for how this is computed. This also works with
580 "--blame" to see the source of the dependency.
581```
582
583#### **Shared flags**
Brett Wilson796ed472018-07-16 15:11:09 -0700584
Robert Sesekd0a6f072020-05-15 11:21:22 -0400585```
586 --default-toolchain
587 Normally wildcard targets are matched in all toolchains. This
588 switch makes wildcard labels with no explicit toolchain reference
589 only match targets in the default toolchain.
590
591 Non-wildcard inputs with no explicit toolchain specification will
592 always match only a target in the default toolchain if one exists.
Brett Wilson796ed472018-07-16 15:11:09 -0700593
594 --format=json
595 Format the output as JSON instead of text.
596```
597
598#### **Target flags**
599
600```
601 --blame
602 Used with any value specified on a config, this will name the config that
Sylvain Defresnea09ec162020-01-16 12:36:40 +0100603 causes that target to get the flag. This doesn't currently work for libs,
Robert Sesekd0a6f072020-05-15 11:21:22 -0400604 lib_dirs, frameworks, weak_frameworks and framework_dirs because those are
605 inherited and are more complicated to figure out the blame (patches
606 welcome).
Brett Wilson796ed472018-07-16 15:11:09 -0700607```
608
609#### **Configs**
610
611```
612 The "configs" section will list all configs that apply. For targets this will
613 include configs specified in the "configs" variable of the target, and also
614 configs pushed onto this target via public or "all dependent" configs.
615
616 Configs can have child configs. Specifying --tree will show the hierarchy.
617```
618
619#### **Printing outputs**
620
621```
622 The "outputs" section will list all outputs that apply, including the outputs
623 computed from the tool definition (eg for "executable", "static_library", ...
624 targets).
625```
626
627#### **Printing deps**
628
629```
630 Deps will include all public, private, and data deps (TODO this could be
631 clarified and enhanced) sorted in order applying. The following may be used:
632
633 --all
634 Collects all recursive dependencies and prints a sorted flat list. Also
635 usable with --tree (see below).
Robert Sesekd0a6f072020-05-15 11:21:22 -0400636
Brett Wilson796ed472018-07-16 15:11:09 -0700637 --as=(buildfile|label|output)
638 How to print targets.
639
640 buildfile
641 Prints the build files where the given target was declared as
642 file names.
643 label (default)
644 Prints the label of the target.
645 output
646 Prints the first output file for the target relative to the
647 root build directory.
648
649 --testonly=(true|false)
650 Restrict outputs to targets with the testonly flag set
651 accordingly. When unspecified, the target's testonly flags are
652 ignored.
653
654 --tree
655 Print a dependency tree. By default, duplicates will be elided with "..."
656 but when --all and -tree are used together, no eliding will be performed.
657
658 The "deps", "public_deps", and "data_deps" will all be included in the
659 tree.
660
661 Tree output can not be used with the filtering or output flags: --as,
662 --type, --testonly.
Robert Sesekd0a6f072020-05-15 11:21:22 -0400663
Brett Wilson796ed472018-07-16 15:11:09 -0700664 --type=(action|copy|executable|group|loadable_module|shared_library|
665 source_set|static_library)
666 Restrict outputs to targets matching the given type. If
667 unspecified, no filtering will be performed.
668```
669
670#### **Note**
671
672```
673 This command will show the full name of directories and source files, but
674 when directories and source paths are written to the build file, they will be
675 adjusted to be relative to the build directory. So the values for paths
676 displayed by this command won't match (but should mean the same thing).
677```
678
679#### **Examples**
680
681```
682 gn desc out/Debug //base:base
683 Summarizes the given target.
684
685 gn desc out/Foo :base_unittests deps --tree
686 Shows a dependency tree of the "base_unittests" project in
687 the current directory.
688
689 gn desc out/Debug //base defines --blame
690 Shows defines set for the //base:base target, annotated by where
691 each one was set from.
692```
[email protected]449f3e42024-08-01 21:43:27 +0800693### **gn format [\--dump-tree] (\--stdin | <list of build_files...>)** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700694
695```
696 Formats .gn file to a standard format.
697
698 The contents of some lists ('sources', 'deps', etc.) will be sorted to a
699 canonical order. To suppress this, you can add a comment of the form "#
700 NOSORT" immediately preceding the assignment. e.g.
701
702 # NOSORT
703 sources = [
704 "z.cc",
705 "a.cc",
706 ]
707```
708
709#### **Arguments**
710
711```
712 --dry-run
Nico Weberad9eab22020-11-15 22:20:28 -0500713 Prints the list of files that would be reformatted but does not write
714 anything to disk. This is useful for presubmit/lint-type checks.
Brett Wilson796ed472018-07-16 15:11:09 -0700715 - Exit code 0: successful format, matches on disk.
716 - Exit code 1: general failure (parse error, etc.)
717 - Exit code 2: successful format, but differs from on disk.
718
Julie Hockettd69a9c32019-01-23 14:36:18 -0800719 --dump-tree[=( text | json )]
720 Dumps the parse tree to stdout and does not update the file or print
721 formatted output. If no format is specified, text format will be used.
Brett Wilson796ed472018-07-16 15:11:09 -0700722
723 --stdin
724 Read input from stdin and write to stdout rather than update a file
725 in-place.
RJ Ascani4e260f12020-10-19 17:41:51 -0700726
727 --read-tree=json
728 Reads an AST from stdin in the format output by --dump-tree=json and
729 uses that as the parse tree. (The only read-tree format currently
730 supported is json.) The given .gn file will be overwritten. This can be
731 used to programmatically transform .gn files.
Brett Wilson796ed472018-07-16 15:11:09 -0700732```
733
734#### **Examples**
735```
Julie Hockettd69a9c32019-01-23 14:36:18 -0800736 gn format //some/BUILD.gn //some/other/BUILD.gn //and/another/BUILD.gn
Brett Wilson796ed472018-07-16 15:11:09 -0700737 gn format some\\BUILD.gn
738 gn format /abspath/some/BUILD.gn
739 gn format --stdin
RJ Ascani4e260f12020-10-19 17:41:51 -0700740 gn format --read-tree=json //rewritten/BUILD.gn
Brett Wilson796ed472018-07-16 15:11:09 -0700741```
[email protected]449f3e42024-08-01 21:43:27 +0800742### **gn gen [\--check] [<ide options>] <out_dir>** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700743
744```
745 Generates ninja files from the current tree and puts them in the given output
746 directory.
747
748 The output directory can be a source-repo-absolute path name such as:
749 //out/foo
750 Or it can be a directory relative to the current directory such as:
751 out/foo
752
James Robinson49f59032020-01-08 14:05:51 -0800753 "gn gen --check" is the same as running "gn check". "gn gen --check=system" is
754 the same as running "gn check --check-system". See "gn help check" for
755 documentation on that mode.
Brett Wilson796ed472018-07-16 15:11:09 -0700756
757 See "gn help switches" for the common command-line switches.
758```
759
RJ Ascani6966efb2020-10-19 16:50:11 -0700760#### **General options**
761
762```
763 --ninja-executable=
764 Can be used to specify the ninja executable to use. This executable will
765 be used as an IDE option to indicate which ninja to use for building. This
766 executable will also be used as part of the gen process for triggering a
RJ Ascani4e260f12020-10-19 17:41:51 -0700767 restat on generated ninja files and for use with --clean-stale.
768
769 --clean-stale
770 This option will cause no longer needed output files to be removed from
771 the build directory, and their records pruned from the ninja build log and
772 dependency database after the ninja build graph has been generated. This
773 option requires a ninja executable of at least version 1.10.0. It can be
774 provided by the --ninja-executable switch. Also see "gn help clean_stale".
RJ Ascani6966efb2020-10-19 16:50:11 -0700775```
776
Brett Wilson796ed472018-07-16 15:11:09 -0700777#### **IDE options**
778
779```
Harley Li0a9affb2020-06-03 10:38:42 -0400780 GN optionally generates files for IDE. Files won't be overwritten if their
781 contents don't change. Possibilities for
Brett Wilson796ed472018-07-16 15:11:09 -0700782
783 --ide=
784 Generate files for an IDE. Currently supported values:
785 "eclipse" - Eclipse CDT settings file.
786 "vs" - Visual Studio project/solution files.
Aaron Gablea5bcbd72019-12-30 15:08:52 -0800787 (default Visual Studio version: 2019)
Brett Wilson796ed472018-07-16 15:11:09 -0700788 "vs2013" - Visual Studio 2013 project/solution files.
789 "vs2015" - Visual Studio 2015 project/solution files.
790 "vs2017" - Visual Studio 2017 project/solution files.
Sylvain Defresned46f92f2019-04-03 16:14:29 +0200791 "vs2019" - Visual Studio 2019 project/solution files.
Tyler Mandry4a648092022-02-15 19:47:09 +0000792 "vs2022" - Visual Studio 2022 project/solution files.
Brett Wilson796ed472018-07-16 15:11:09 -0700793 "xcode" - Xcode workspace/solution files.
794 "qtcreator" - QtCreator project files.
795 "json" - JSON file containing target information
796
797 --filters=
798 Semicolon-separated list of label patterns used to limit the set of
799 generated projects (see "gn help label_pattern"). Only matching targets
800 and their dependencies will be included in the solution. Only used for
801 Visual Studio, Xcode and JSON.
802```
803
804#### **Visual Studio Flags**
805
806```
807 --sln=
808 Override default sln file name ("all"). Solution file is written to the
809 root build directory.
810
811 --no-deps
812 Don't include targets dependencies to the solution. Changes the way how
813 --filters option works. Only directly matching targets are included.
814
815 --winsdk=
816 Use the specified Windows 10 SDK version to generate project files.
817 As an example, "10.0.15063.0" can be specified to use Creators Update SDK
818 instead of the default one.
819
Shezan Baigc0a2d232021-07-01 00:29:49 -0400820 --ninja-executable=
821 Can be used to specify the ninja executable to use when building.
822
Brett Wilson796ed472018-07-16 15:11:09 -0700823 --ninja-extra-args=
824 This string is passed without any quoting to the ninja invocation
825 command-line. Can be used to configure ninja flags, like "-j".
826```
827
828#### **Xcode Flags**
829
830```
Sylvain Defresnedb55efd2020-06-16 12:23:03 +0200831 --xcode-project=
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +0100832 Override default Xcode project file name ("all"). The project file is
Brett Wilson796ed472018-07-16 15:11:09 -0700833 written to the root build directory.
834
Sylvain Defresne7b0690e2020-06-26 15:33:01 +0200835 --xcode-build-system=
836 Configure the build system to use for the Xcode project. Supported
837 values are (default to "legacy"):
838 "legacy" - Legacy Build system
839 "new" - New Build System
840
Sylvain Defresne88830702022-06-20 17:11:49 +0200841 --xcode-configs=
842 Configure the list of build configuration supported by the generated
843 project. If specified, must be a list of semicolon-separated strings.
Ricardo Ribalda85bd0a62023-11-11 16:30:19 +0000844 If omitted, a single configuration will be used in the generated
Sylvain Defresne88830702022-06-20 17:11:49 +0200845 project derived from the build directory.
846
847 --xcode-config-build-dir=
848 If present, must be a path relative to the source directory. It will
Ricardo Ribalda85bd0a62023-11-11 16:30:19 +0000849 default to $root_out_dir if omitted. The path is assumed to point to
Sylvain Defresne88830702022-06-20 17:11:49 +0200850 the directory where ninja needs to be invoked. This variable can be
851 used to build for multiple configuration / platform / environment from
852 the same generated Xcode project (assuming that the user has created a
853 gn build directory with the correct args.gn for each).
854
855 One useful value is to use Xcode variables such as '${CONFIGURATION}'
856 or '${EFFECTIVE_PLATFORM}'.
857
Sylvain Defresneae474cc2022-06-21 14:44:02 +0200858 --xcode-additional-files-patterns=
859 If present, must be a list of semicolon-separated file patterns. It
860 will be used to add all files matching the pattern located in the
861 source tree to the project. It can be used to add, e.g. documentation
862 files to the project to allow easily edit them.
863
864 --xcode-additional-files-roots=
865 If present, must be a list of semicolon-separated paths. It will be used
Ricardo Ribalda85bd0a62023-11-11 16:30:19 +0000866 as roots when looking for additional files to add. If omitted, defaults
Sylvain Defresneae474cc2022-06-21 14:44:02 +0200867 to "//".
868
Sylvain Defresneaff489a2020-03-11 18:27:43 +0100869 --ninja-executable=
870 Can be used to specify the ninja executable to use when building.
871
Brett Wilson796ed472018-07-16 15:11:09 -0700872 --ninja-extra-args=
873 This string is passed without any quoting to the ninja invocation
874 command-line. Can be used to configure ninja flags, like "-j".
875
Sylvain Defresnee431b2f2020-11-04 10:49:47 +0100876 --ide-root-target=
Brett Wilson796ed472018-07-16 15:11:09 -0700877 Name of the target corresponding to "All" target in Xcode. If unset,
878 "All" invokes ninja without any target and builds everything.
879```
880
881#### **QtCreator Flags**
882
883```
Sylvain Defresnee431b2f2020-11-04 10:49:47 +0100884 --ide-root-target=
Brett Wilson796ed472018-07-16 15:11:09 -0700885 Name of the root target for which the QtCreator project will be generated
886 to contain files of it and its dependencies. If unset, the whole build
887 graph will be emitted.
888```
889
890#### **Eclipse IDE Support**
891
892```
893 GN DOES NOT generate Eclipse CDT projects. Instead, it generates a settings
894 file which can be imported into an Eclipse CDT project. The XML file contains
895 a list of include paths and defines. Because GN does not generate a full
896 .cproject definition, it is not possible to properly define includes/defines
897 for each file individually. Instead, one set of includes/defines is generated
898 for the entire project. This works fairly well but may still result in a few
899 indexer issues here and there.
900```
901
902#### **Generic JSON Output**
903
904```
905 Dumps target information to a JSON file and optionally invokes a
906 python script on the generated file. See the comments at the beginning
907 of json_project_writer.cc and desc_builder.cc for an overview of the JSON
908 file format.
909
910 --json-file-name=
911 Overrides default file name (project.json) of generated JSON file.
912
913 --json-ide-script=
Harley Li0a9affb2020-06-03 10:38:42 -0400914 Executes python script after the JSON file is generated or updated with
915 new content. Path can be project absolute (//), system absolute (/) or
916 relative, in which case the output directory will be base. Path to
917 generated JSON file will be first argument when invoking script.
Brett Wilson796ed472018-07-16 15:11:09 -0700918
919 --json-ide-script-args=
David 'Digit' Turner6253a392024-02-20 19:55:35 +0100920 Optional second argument that will be passed to executed script.
921```
922
923#### **Ninja Outputs**
924
925```
926 The --ninja-outputs-file= option dumps a JSON file that maps GN labels
927 to their Ninja output paths. This can be later processed to build an index
928 to convert between Ninja targets and GN ones before or after the build itself.
929 It looks like:
930
931 {
932 "label1": [
933 "path1",
934 "path2"
935 ],
936 "label2": [
937 "path3"
938 ]
939 }
940
941 --ninja-outputs-script=
942 Executes python script after the outputs file is generated or updated
943 with new content. Path can be project absolute (//), system absolute (/) or
944 relative, in which case the output directory will be base. Path to
945 generated file will be first argument when invoking script.
946
947 --ninja-outputs-script-args=
948 Optional second argument that will be passed to executed script.
Brett Wilson796ed472018-07-16 15:11:09 -0700949```
Julie Hockett11e09912018-07-31 13:15:08 -0700950
951#### **Compilation Database**
952
953```
Robert Sesekd0a6f072020-05-15 11:21:22 -0400954 --export-rust-project
955 Produces a rust-project.json file in the root of the build directory
956 This is used for various tools in the Rust ecosystem allowing for the
957 replay of individual compilations independent of the build system.
958 This is an unstable format and likely to change without warning.
959
Brett Wilson1da84bb2022-09-14 15:35:29 -0700960 --add-export-compile-commands=
961 Adds an additional label pattern (see "gn help label_pattern") of a
962 target to add to the compilation database. This pattern is appended to any
963 list values specified in the export_compile_commands variable in the
964 .gn file (see "gn help dotfile"). This allows the user to add additional
965 targets to the compilation database that the project doesn't add by default.
966
967 To add more than one value, specify this switch more than once. Each
968 invocation adds an additional label pattern.
969
970 Example:
971 --add-export-compile-commands=//tools:my_tool
972 --add-export-compile-commands="//base/*"
973
Robert Sesek252674d2019-05-10 14:08:52 -0400974 --export-compile-commands[=]
Brett Wilson1da84bb2022-09-14 15:35:29 -0700975 DEPRECATED https://bugs.chromium.org/p/gn/issues/detail?id=302.
976 Please use --add-export-compile-commands for per-user configuration, and
977 the "export_compile_commands" value in the project-level .gn file (see
978 "gn help dotfile") for per-project configuration.
979
980 Overrides the value of the export_compile_commands in the .gn file (see
981 "gn help dotfile") as well as the --add-export-compile-commands switch.
982
983 Unlike the .gn setting, this switch takes a legacy format which is a list
984 of target names that are matched in any directory. For example, "foo" will
985 match:
986 - "//path/to/src:foo"
987 - "//other/path:foo"
988 - "//foo:foo"
Aaron Wood2d9fd622020-12-10 21:28:19 -0800989 and not match:
Brett Wilson1da84bb2022-09-14 15:35:29 -0700990 - "//foo:bar"
Julie Hockett11e09912018-07-31 13:15:08 -0700991```
[email protected]449f3e42024-08-01 21:43:27 +0800992### **gn help <anything>** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -0700993
994```
995 Yo dawg, I heard you like help on your help so I put help on the help in the
996 help.
997
998 You can also use "all" as the parameter to get all help at once.
999```
1000
1001#### **Switches**
1002
1003```
1004 --markdown
1005 Format output in markdown syntax.
1006```
1007
1008#### **Example**
1009
1010```
1011 gn help --markdown all
1012 Dump all help to stdout in markdown format.
1013```
[email protected]449f3e42024-08-01 21:43:27 +08001014### **gn ls <out_dir> [<label_pattern>] [\--default-toolchain] [\--as=...]** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001015```
1016 [--type=...] [--testonly=...]
1017
1018 Lists all targets matching the given pattern for the given build directory.
1019 By default, only targets in the default toolchain will be matched unless a
1020 toolchain is explicitly supplied.
1021
1022 If the label pattern is unspecified, list all targets. The label pattern is
1023 not a general regular expression (see "gn help label_pattern"). If you need
1024 more complex expressions, pipe the result through grep.
1025```
1026
1027#### **Options**
1028
1029```
1030 --as=(buildfile|label|output)
1031 How to print targets.
1032
1033 buildfile
1034 Prints the build files where the given target was declared as
1035 file names.
1036 label (default)
1037 Prints the label of the target.
1038 output
1039 Prints the first output file for the target relative to the
1040 root build directory.
1041
Robert Sesekd0a6f072020-05-15 11:21:22 -04001042 --default-toolchain
1043 Normally wildcard targets are matched in all toolchains. This
1044 switch makes wildcard labels with no explicit toolchain reference
1045 only match targets in the default toolchain.
Brett Wilson796ed472018-07-16 15:11:09 -07001046
Robert Sesekd0a6f072020-05-15 11:21:22 -04001047 Non-wildcard inputs with no explicit toolchain specification will
1048 always match only a target in the default toolchain if one exists.
Brett Wilson796ed472018-07-16 15:11:09 -07001049
1050 --testonly=(true|false)
1051 Restrict outputs to targets with the testonly flag set
1052 accordingly. When unspecified, the target's testonly flags are
1053 ignored.
1054
1055 --type=(action|copy|executable|group|loadable_module|shared_library|
1056 source_set|static_library)
1057 Restrict outputs to targets matching the given type. If
1058 unspecified, no filtering will be performed.
1059```
1060
1061#### **Examples**
1062
1063```
1064 gn ls out/Debug
1065 Lists all targets in the default toolchain.
1066
1067 gn ls out/Debug "//base/*"
1068 Lists all targets in the directory base and all subdirectories.
1069
1070 gn ls out/Debug "//base:*"
1071 Lists all targets defined in //base/BUILD.gn.
1072
1073 gn ls out/Debug //base --as=output
1074 Lists the build output file for //base:base
1075
1076 gn ls out/Debug --type=executable
1077 Lists all executables produced by the build.
1078
1079 gn ls out/Debug "//base/*" --as=output | xargs ninja -C out/Debug
1080 Builds all targets in //base and all subdirectories.
Brett Wilson796ed472018-07-16 15:11:09 -07001081```
[email protected]449f3e42024-08-01 21:43:27 +08001082### **gn meta** [Back to Top](#gn-reference)
Joe Armstrongb199e542019-03-21 09:40:08 +08001083
Nate Fischer8ed01d32019-01-08 17:32:01 -08001084```
Joe Armstrongb199e542019-03-21 09:40:08 +08001085 gn meta * --data=[,*]* [--walk=[,*]*]
1086 [--rebase=]
Nate Fischer8ed01d32019-01-08 17:32:01 -08001087
1088 Lists collected metaresults of all given targets for the given data key(s),
1089 collecting metadata dependencies as specified by the given walk key(s).
1090
1091 See `gn help generated_file` for more information on the walk.
1092```
1093
1094#### **Arguments**
1095
1096```
1097
1098 A list of target labels from which to initiate the walk.
1099
1100 --data
Tyler Mandry4a648092022-02-15 19:47:09 +00001101 A comma-separated list of keys from which to extract data. In each target
1102 walked, its metadata scope is checked for the presence of these keys. If
1103 present, the contents of those variable in the scope are appended to the
1104 results list.
Nate Fischer8ed01d32019-01-08 17:32:01 -08001105
1106 --walk (optional)
Tyler Mandry4a648092022-02-15 19:47:09 +00001107 A comma-separated list of keys from which to control the walk. In each
1108 target walked, its metadata scope is checked for the presence of any of
1109 these keys. If present, the contents of those variables is checked to ensure
1110 that it is a label of a valid dependency of the target and then added to the
1111 set of targets to walk. If the empty string ("") is present in any of these
1112 keys, all deps and data_deps are added to the walk set.
Nate Fischer8ed01d32019-01-08 17:32:01 -08001113
1114 --rebase (optional)
1115 A destination directory onto which to rebase any paths found. If set, all
1116 collected metadata will be rebased onto this path. This option will throw errors
1117 if collected metadata is not a list of strings.
1118```
1119
1120#### **Examples**
1121
1122```
1123 gn meta out/Debug "//base/foo" --data=files
1124 Lists collected metaresults for the `files` key in the //base/foo:foo
1125 target and all of its dependency tree.
1126
Tyler Mandry4a648092022-02-15 19:47:09 +00001127 gn meta out/Debug "//base/foo" --data=files,other
Nate Fischer8ed01d32019-01-08 17:32:01 -08001128 Lists collected metaresults for the `files` and `other` keys in the
1129 //base/foo:foo target and all of its dependency tree.
1130
1131 gn meta out/Debug "//base/foo" --data=files --walk=stop
1132 Lists collected metaresults for the `files` key in the //base/foo:foo
1133 target and all of the dependencies listed in the `stop` key (and so on).
1134
1135 gn meta out/Debug "//base/foo" --data=files --rebase="/"
1136 Lists collected metaresults for the `files` key in the //base/foo:foo
1137 target and all of its dependency tree, rebasing the strings in the `files`
1138 key onto the source directory of the target's declaration relative to "/".
1139```
[email protected]449f3e42024-08-01 21:43:27 +08001140### **gn outputs <out_dir> <list of target or file names...>** [Back to Top](#gn-reference)
Brett Wilson74397092020-03-18 16:34:14 -07001141
1142```
1143 Lists the output files corresponding to the given target(s) or file name(s).
1144 There can be multiple outputs because there can be more than one output
1145 generated by a build step, and there can be more than one toolchain matched.
1146 You can also list multiple inputs which will generate a union of all the
1147 outputs from those inputs.
1148
1149 - The input target/file names are relative to the current directory.
1150
1151 - The output file names are relative to the root build directory.
1152
1153 This command is useful for finding a ninja command that will build only a
1154 portion of the build.
1155```
1156
1157#### **Target outputs**
1158
1159```
1160 If the parameter is a target name that includes a toolchain, it will match
1161 only that target in that toolchain. If no toolchain is specified, it will
1162 match all targets with that name in any toolchain.
1163
1164 The result will be the outputs specified by that target which could be a
1165 library, executable, output of an action, a stamp file, etc.
1166```
1167
1168#### **File outputs**
1169
1170```
1171 If the parameter is a file name it will compute the output for that compile
1172 step for all targets in all toolchains that contain that file as a source
1173 file.
1174
1175 If the source is not compiled (e.g. a header or text file), the command will
1176 produce no output.
1177
1178 If the source is listed as an "input" to a binary target or action will
1179 resolve to that target's outputs.
1180```
1181
1182#### **Example**
1183
1184```
1185 gn outputs out/debug some/directory:some_target
1186 Find the outputs of a given target.
1187
1188 gn outputs out/debug src/project/my_file.cc | xargs ninja -C out/debug
1189 Compiles just the given source file in all toolchains it's referenced in.
1190
1191 git diff --name-only | xargs gn outputs out/x64 | xargs ninja -C out/x64
1192 Compiles all files changed in git.
1193```
[email protected]449f3e42024-08-01 21:43:27 +08001194### **gn path <out_dir> <target_one> <target_two>** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001195
1196```
1197 Finds paths of dependencies between two targets. Each unique path will be
1198 printed in one group, and groups will be separate by newlines. The two
1199 targets can appear in either order (paths will be found going in either
1200 direction).
1201
1202 By default, a single path will be printed. If there is a path with only
1203 public dependencies, the shortest public path will be printed. Otherwise, the
1204 shortest path using either public or private dependencies will be printed. If
1205 --with-data is specified, data deps will also be considered. If there are
1206 multiple shortest paths, an arbitrary one will be selected.
1207```
1208
1209#### **Interesting paths**
1210
1211```
1212 In a large project, there can be 100's of millions of unique paths between a
1213 very high level and a common low-level target. To make the output more useful
1214 (and terminate in a reasonable time), GN will not revisit sub-paths
1215 previously known to lead to the target.
1216```
1217
1218#### **Options**
1219
1220```
1221 --all
1222 Prints all "interesting" paths found rather than just the first one.
1223 Public paths will be printed first in order of increasing length, followed
1224 by non-public paths in order of increasing length.
1225
1226 --public
1227 Considers only public paths. Can't be used with --with-data.
1228
1229 --with-data
1230 Additionally follows data deps. Without this flag, only public and private
1231 linked deps will be followed. Can't be used with --public.
1232```
1233
1234#### **Example**
1235
1236```
Keir Mierle45611e32019-11-12 11:18:00 -08001237 gn path out/Default //base //gn
Brett Wilson796ed472018-07-16 15:11:09 -07001238```
[email protected]449f3e42024-08-01 21:43:27 +08001239### **gn refs** [Back to Top](#gn-reference)
Joe Armstrongb199e542019-03-21 09:40:08 +08001240
Brett Wilson796ed472018-07-16 15:11:09 -07001241```
Nico Weberad9eab22020-11-15 22:20:28 -05001242 gn refs (|
1243 [--default-toolchain] [--as=...] [--testonly=...] [--type=...]
Brett Wilson796ed472018-07-16 15:11:09 -07001244
1245 Finds reverse dependencies (which targets reference something). The input is
1246 a list containing:
1247
1248 - Target label: The result will be which targets depend on it.
1249
1250 - Config label: The result will be which targets list the given config in
1251 its "configs" or "public_configs" list.
1252
1253 - Label pattern: The result will be which targets depend on any target
1254 matching the given pattern. Patterns will not match configs. These are not
1255 general regular expressions, see "gn help label_pattern" for details.
1256
1257 - File name: The result will be which targets list the given file in its
1258 "inputs", "sources", "public", "data", or "outputs". Any input that does
1259 not contain wildcards and does not match a target or a config will be
1260 treated as a file.
1261
1262 - Response file: If the input starts with an "@", it will be interpreted as
1263 a path to a file containing a list of labels or file names, one per line.
1264 This allows us to handle long lists of inputs without worrying about
1265 command line limits.
1266```
1267
1268#### **Options**
1269
1270```
1271 --all
1272 When used without --tree, will recurse and display all unique
1273 dependencies of the given targets. For example, if the input is a target,
1274 this will output all targets that depend directly or indirectly on the
1275 input. If the input is a file, this will output all targets that depend
1276 directly or indirectly on that file.
1277
1278 When used with --tree, turns off eliding to show a complete tree.
Brett Wilson796ed472018-07-16 15:11:09 -07001279
1280 --as=(buildfile|label|output)
1281 How to print targets.
1282
1283 buildfile
1284 Prints the build files where the given target was declared as
1285 file names.
1286 label (default)
1287 Prints the label of the target.
1288 output
1289 Prints the first output file for the target relative to the
1290 root build directory.
1291
Robert Sesekd0a6f072020-05-15 11:21:22 -04001292 --default-toolchain
1293 Normally wildcard targets are matched in all toolchains. This
1294 switch makes wildcard labels with no explicit toolchain reference
1295 only match targets in the default toolchain.
1296
1297 Non-wildcard inputs with no explicit toolchain specification will
1298 always match only a target in the default toolchain if one exists.
1299
Brett Wilson796ed472018-07-16 15:11:09 -07001300 -q
1301 Quiet. If nothing matches, don't print any output. Without this option, if
1302 there are no matches there will be an informational message printed which
1303 might interfere with scripts processing the output.
Robert Sesekd0a6f072020-05-15 11:21:22 -04001304
Brett Wilson796ed472018-07-16 15:11:09 -07001305 --testonly=(true|false)
1306 Restrict outputs to targets with the testonly flag set
1307 accordingly. When unspecified, the target's testonly flags are
1308 ignored.
1309
1310 --tree
1311 Outputs a reverse dependency tree from the given target. Duplicates will
1312 be elided. Combine with --all to see a full dependency tree.
1313
1314 Tree output can not be used with the filtering or output flags: --as,
1315 --type, --testonly.
Robert Sesekd0a6f072020-05-15 11:21:22 -04001316
Brett Wilson796ed472018-07-16 15:11:09 -07001317 --type=(action|copy|executable|group|loadable_module|shared_library|
1318 source_set|static_library)
1319 Restrict outputs to targets matching the given type. If
1320 unspecified, no filtering will be performed.
1321```
1322
1323#### **Examples (target input)**
1324
1325```
Keir Mierle45611e32019-11-12 11:18:00 -08001326 gn refs out/Debug //gn:gn
Brett Wilson796ed472018-07-16 15:11:09 -07001327 Find all targets depending on the given exact target name.
1328
Lei Zhang415b3b12024-04-02 09:29:36 -07001329 gn refs out/Debug //base:i18n --as=buildfile | xargs gvim
Brett Wilson796ed472018-07-16 15:11:09 -07001330 Edit all .gn files containing references to //base:i18n
1331
1332 gn refs out/Debug //base --all
1333 List all targets depending directly or indirectly on //base:base.
1334
1335 gn refs out/Debug "//base/*"
1336 List all targets depending directly on any target in //base or
1337 its subdirectories.
1338
1339 gn refs out/Debug "//base:*"
1340 List all targets depending directly on any target in
1341 //base/BUILD.gn.
1342
1343 gn refs out/Debug //base --tree
1344 Print a reverse dependency tree of //base:base
1345```
1346
1347#### **Examples (file input)**
1348
1349```
1350 gn refs out/Debug //base/macros.h
1351 Print target(s) listing //base/macros.h as a source.
1352
1353 gn refs out/Debug //base/macros.h --tree
1354 Display a reverse dependency tree to get to the given file. This
1355 will show how dependencies will reference that file.
1356
1357 gn refs out/Debug //base/macros.h //base/at_exit.h --all
1358 Display all unique targets with some dependency path to a target
1359 containing either of the given files as a source.
1360
1361 gn refs out/Debug //base/macros.h --testonly=true --type=executable
1362 --all --as=output
1363 Display the executable file names of all test executables
1364 potentially affected by a change to the given file.
1365```
1366## Target declarations
1367
[email protected]449f3e42024-08-01 21:43:27 +08001368### **action**: Declare a target that runs a script a single time. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001369
1370```
1371 This target type allows you to run a script a single time to produce one or
1372 more output files. If you want to run a script once for each of a set of
1373 input files, see "gn help action_foreach".
1374```
1375
1376#### **Inputs**
1377
1378```
1379 In an action the "sources" and "inputs" are treated the same: they're both
1380 input dependencies on script execution with no special handling. If you want
1381 to pass the sources to your script, you must do so explicitly by including
1382 them in the "args". Note also that this means there is no special handling of
1383 paths since GN doesn't know which of the args are paths and not. You will
1384 want to use rebase_path() to convert paths to be relative to the
1385 root_build_dir.
1386
1387 You can dynamically write input dependencies (for incremental rebuilds if an
1388 input file changes) by writing a depfile when the script is run (see "gn help
1389 depfile"). This is more flexible than "inputs".
1390
1391 If the command line length is very long, you can use response files to pass
1392 args to your script. See "gn help response_file_contents".
1393
1394 It is recommended you put inputs to your script in the "sources" variable,
1395 and stuff like other Python files required to run your script in the "inputs"
1396 variable.
Julie Hockette2a29402018-07-31 10:11:42 -07001397
Adrian Taylorc0d4f8b2022-03-25 15:05:57 -07001398 Actions can take the configs and public_configs lists, as well as any of the
1399 configs variables (defines, include_dirs, etc.) set directly on the target.
1400 These behave exactly as they would on a binary target and can be accessed
1401 using substitution patterns in the script args (see "gn help args") to
1402 implement custom compiler-like tools.
1403
Brett Wilson796ed472018-07-16 15:11:09 -07001404 The "deps" and "public_deps" for an action will always be
1405 completed before any part of the action is run so it can depend on
1406 the output of previous steps. The "data_deps" will be built if the
1407 action is built, but may not have completed before all steps of the
1408 action are started. This can give additional parallelism in the build
1409 for runtime-only dependencies.
1410```
1411
1412#### **Outputs**
1413
1414```
1415 You should specify files created by your script by specifying them in the
1416 "outputs".
Julie Hockette2a29402018-07-31 10:11:42 -07001417
Brett Wilson796ed472018-07-16 15:11:09 -07001418 The script will be executed with the given arguments with the current
1419 directory being that of the root build directory. If you pass files
1420 to your script, see "gn help rebase_path" for how to convert
1421 file names to be relative to the build directory (file names in the
1422 sources, outputs, and inputs will be all treated as relative to the
1423 current build file and converted as needed automatically).
Brett Wilson1e1ea9d2020-02-04 15:34:05 -08001424
1425 GN sets Ninja's flag 'restat = 1` for all action commands. This means
1426 that Ninja will check the timestamp of the output after the action
1427 completes. If output timestamp is unchanged, the step will be treated
1428 as if it never needed to be rebuilt, potentially eliminating some
1429 downstream steps for incremental builds. Scripts can improve build
1430 performance by taking care not to change the timstamp of the output
1431 file(s) if the contents have not changed.
Brett Wilson796ed472018-07-16 15:11:09 -07001432```
1433
1434#### **File name handling**
Julie Hockette2a29402018-07-31 10:11:42 -07001435
Brett Wilson796ed472018-07-16 15:11:09 -07001436```
1437 All output files must be inside the output directory of the build.
1438 You would generally use |$target_out_dir| or |$target_gen_dir| to
1439 reference the output or generated intermediate file directories,
1440 respectively.
1441```
1442
1443#### **Variables**
1444
1445```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001446 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
1447 cflags_objcc, defines, include_dirs, inputs, ldflags,
1448 lib_dirs, libs, precompiled_header, precompiled_source,
1449 rustenv, rustflags, swiftflags, testonly
1450 Dependent configs: all_dependent_configs, public_configs
1451 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
1452 write_runtime_deps
1453 General: check_includes, configs, data, friend, inputs, metadata,
1454 output_extension, output_name, public, sources, testonly,
1455 visibility
1456 Action variables: args, bridge_header, configs, data, depfile,
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07001457 framework_dirs, inputs, mnemonic, module_deps,
1458 module_name, outputs*, pool, response_file_contents,
1459 script*, sources
Brett Wilson796ed472018-07-16 15:11:09 -07001460 * = required
1461```
1462
1463#### **Example**
1464
1465```
1466 action("run_this_guy_once") {
1467 script = "doprocessing.py"
1468 sources = [ "my_configuration.txt" ]
1469 outputs = [ "$target_gen_dir/insightful_output.txt" ]
1470
1471 # Our script imports this Python file so we want to rebuild if it changes.
1472 inputs = [ "helper_library.py" ]
1473
1474 # Note that we have to manually pass the sources to our script if the
1475 # script needs them as inputs.
1476 args = [ "--out", rebase_path(target_gen_dir, root_build_dir) ] +
1477 rebase_path(sources, root_build_dir)
1478 }
1479```
[email protected]449f3e42024-08-01 21:43:27 +08001480### **action_foreach**: Declare a target that runs a script over a set of files. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001481
1482```
1483 This target type allows you to run a script once-per-file over a set of
1484 sources. If you want to run a script once that takes many files as input, see
1485 "gn help action".
1486```
1487
1488#### **Inputs**
1489
1490```
1491 The script will be run once per file in the "sources" variable. The "outputs"
1492 variable should specify one or more files with a source expansion pattern in
1493 it (see "gn help source_expansion"). The output file(s) for each script
1494 invocation should be unique. Normally you use "{{source_name_part}}" in each
1495 output file.
1496
1497 If your script takes additional data as input, such as a shared configuration
1498 file or a Python module it uses, those files should be listed in the "inputs"
1499 variable. These files are treated as dependencies of each script invocation.
1500
1501 If the command line length is very long, you can use response files to pass
1502 args to your script. See "gn help response_file_contents".
1503
1504 You can dynamically write input dependencies (for incremental rebuilds if an
1505 input file changes) by writing a depfile when the script is run (see "gn help
1506 depfile"). This is more flexible than "inputs".
Julie Hockette2a29402018-07-31 10:11:42 -07001507
Brett Wilson796ed472018-07-16 15:11:09 -07001508 The "deps" and "public_deps" for an action will always be
1509 completed before any part of the action is run so it can depend on
1510 the output of previous steps. The "data_deps" will be built if the
1511 action is built, but may not have completed before all steps of the
1512 action are started. This can give additional parallelism in the build
1513 for runtime-only dependencies.
1514```
1515
1516#### **Outputs**
Julie Hockette2a29402018-07-31 10:11:42 -07001517
Brett Wilson796ed472018-07-16 15:11:09 -07001518```
1519 The script will be executed with the given arguments with the current
1520 directory being that of the root build directory. If you pass files
1521 to your script, see "gn help rebase_path" for how to convert
1522 file names to be relative to the build directory (file names in the
1523 sources, outputs, and inputs will be all treated as relative to the
1524 current build file and converted as needed automatically).
Brett Wilson1e1ea9d2020-02-04 15:34:05 -08001525
1526 GN sets Ninja's flag 'restat = 1` for all action commands. This means
1527 that Ninja will check the timestamp of the output after the action
1528 completes. If output timestamp is unchanged, the step will be treated
1529 as if it never needed to be rebuilt, potentially eliminating some
1530 downstream steps for incremental builds. Scripts can improve build
1531 performance by taking care not to change the timstamp of the output
1532 file(s) if the contents have not changed.
Brett Wilson796ed472018-07-16 15:11:09 -07001533```
1534
1535#### **File name handling**
Julie Hockette2a29402018-07-31 10:11:42 -07001536
Brett Wilson796ed472018-07-16 15:11:09 -07001537```
1538 All output files must be inside the output directory of the build.
1539 You would generally use |$target_out_dir| or |$target_gen_dir| to
1540 reference the output or generated intermediate file directories,
1541 respectively.
1542```
1543
1544#### **Variables**
1545
1546```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001547 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
1548 cflags_objcc, defines, include_dirs, inputs, ldflags,
1549 lib_dirs, libs, precompiled_header, precompiled_source,
1550 rustenv, rustflags, swiftflags, testonly
1551 Dependent configs: all_dependent_configs, public_configs
1552 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
1553 write_runtime_deps
1554 General: check_includes, configs, data, friend, inputs, metadata,
1555 output_extension, output_name, public, sources, testonly,
1556 visibility
1557 Action variables: args, bridge_header, configs, data, depfile,
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07001558 framework_dirs, inputs, mnemonic, module_deps,
1559 module_name, outputs*, pool, response_file_contents,
1560 script*, sources
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001561 * = required
Brett Wilson796ed472018-07-16 15:11:09 -07001562```
1563
1564#### **Example**
1565
1566```
1567 # Runs the script over each IDL file. The IDL script will generate both a .cc
1568 # and a .h file for each input.
1569 action_foreach("my_idl") {
1570 script = "idl_processor.py"
1571 sources = [ "foo.idl", "bar.idl" ]
1572
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07001573 # Causes ninja to output "IDL
1574 # "ACTION
1575 mnemonic = "IDL"
1576
Joe Armstrong73e89072019-05-10 11:23:52 +08001577 # Our script reads this file each time, so we need to list it as a
Brett Wilson796ed472018-07-16 15:11:09 -07001578 # dependency so we can rebuild if it changes.
1579 inputs = [ "my_configuration.txt" ]
1580
1581 # Transformation from source file name to output file names.
1582 outputs = [ "$target_gen_dir/{{source_name_part}}.h",
1583 "$target_gen_dir/{{source_name_part}}.cc" ]
1584
1585 # Note that since "args" is opaque to GN, if you specify paths here, you
1586 # will need to convert it to be relative to the build directory using
1587 # rebase_path().
1588 args = [
1589 "{{source}}",
1590 "-o",
Hector Dearman0d67e272020-12-22 01:37:16 +00001591 rebase_path(target_gen_dir, root_build_dir) +
Brett Wilson796ed472018-07-16 15:11:09 -07001592 "/{{source_name_part}}.h" ]
1593 }
1594```
[email protected]449f3e42024-08-01 21:43:27 +08001595### **bundle_data**: [iOS/macOS] Declare a target without output. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001596
1597```
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01001598 This target type allows one to declare data that is required at runtime. It is
Brett Wilson796ed472018-07-16 15:11:09 -07001599 used to inform "create_bundle" targets of the files to copy into generated
1600 bundle, see "gn help create_bundle" for help.
1601
1602 The target must define a list of files as "sources" and a single "outputs".
1603 If there are multiple files, source expansions must be used to express the
1604 output. The output must reference a file inside of {{bundle_root_dir}}.
1605
1606 This target can be used on all platforms though it is designed only to
1607 generate iOS/macOS bundle. In cross-platform projects, it is advised to put it
1608 behind iOS/macOS conditionals.
1609
Sylvain Defresne06cdcc82024-03-21 13:48:59 +01001610 If any source files in a bundle_data target match `*/*.xcassets/*` then they
1611 will be considered part of an assets catalog, and instead of being copied to
1612 the final bundle the assets catalog itself will be added to the inputs of the
1613 assets catalog compilation step. See "compile_xcassets" tool.
1614
Brett Wilson796ed472018-07-16 15:11:09 -07001615 See "gn help create_bundle" for more information.
1616```
1617
1618#### **Variables**
1619
1620```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001621 Dependent configs: all_dependent_configs, public_configs
1622 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
1623 write_runtime_deps
1624 General: check_includes, configs, data, friend, inputs, metadata,
1625 output_extension, output_name, public, sources, testonly,
1626 visibility
1627 Bundle-specific: sources*, outputs*
Brett Wilson796ed472018-07-16 15:11:09 -07001628 * = required
1629```
1630
1631#### **Examples**
1632
1633```
1634 bundle_data("icudata") {
1635 sources = [ "sources/data/in/icudtl.dat" ]
1636 outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ]
1637 }
1638
1639 bundle_data("base_unittests_bundle_data]") {
1640 sources = [ "test/data" ]
1641 outputs = [
1642 "{{bundle_resources_dir}}/{{source_root_relative_dir}}/" +
1643 "{{source_file_part}}"
1644 ]
1645 }
1646
1647 bundle_data("material_typography_bundle_data") {
1648 sources = [
1649 "src/MaterialTypography.bundle/Roboto-Bold.ttf",
1650 "src/MaterialTypography.bundle/Roboto-Italic.ttf",
1651 "src/MaterialTypography.bundle/Roboto-Regular.ttf",
1652 "src/MaterialTypography.bundle/Roboto-Thin.ttf",
1653 ]
1654 outputs = [
1655 "{{bundle_resources_dir}}/MaterialTypography.bundle/"
1656 "{{source_file_part}}"
1657 ]
1658 }
1659```
[email protected]449f3e42024-08-01 21:43:27 +08001660### **copy**: Declare a target that copies files. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001661
1662#### **File name handling**
1663
1664```
1665 All output files must be inside the output directory of the build. You would
1666 generally use |$target_out_dir| or |$target_gen_dir| to reference the output
1667 or generated intermediate file directories, respectively.
1668
1669 Both "sources" and "outputs" must be specified. Sources can include as many
1670 files as you want, but there can only be one item in the outputs list (plural
1671 is used for the name for consistency with other target types).
1672
1673 If there is more than one source file, your output name should specify a
1674 mapping from each source file to an output file name using source expansion
1675 (see "gn help source_expansion"). The placeholders will look like
1676 "{{source_name_part}}", for example.
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001677
1678 If you want to copy the output of a previous build step, the target that
1679 generates the file to copy must be reachable from the deps or public_deps of
1680 the copy target.
1681```
1682
1683#### **Variables**
1684
1685```
1686 Dependent configs: all_dependent_configs, public_configs
1687 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
1688 write_runtime_deps
1689 General: check_includes, configs, data, friend, inputs, metadata,
1690 output_extension, output_name, public, sources, testonly,
1691 visibility
1692 Copy variables: sources*, outputs*
1693 * = required
Brett Wilson796ed472018-07-16 15:11:09 -07001694```
1695
1696#### **Examples**
1697
1698```
1699 # Write a rule that copies a checked-in DLL to the output directory.
1700 copy("mydll") {
1701 sources = [ "mydll.dll" ]
1702 outputs = [ "$target_out_dir/mydll.dll" ]
1703 }
1704
1705 # Write a rule to copy several files to the target generated files directory.
1706 copy("myfiles") {
1707 sources = [ "data1.dat", "data2.dat", "data3.dat" ]
1708
1709 # Use source expansion to generate output files with the corresponding file
1710 # names in the gen dir. This will just copy each file.
1711 outputs = [ "$target_gen_dir/{{source_file_part}}" ]
1712 }
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001713
1714 # Copy the output of a generated executable.
1715 copy("package_melon") {
1716 # This example uses get_label_info() to compute the output directory of the
1717 # dependency. This allows the copy rule to work regardless of the toolchain.
1718 #
1719 # In some cases (particularly actions defined previously in the same file)
1720 # you can use get_target_outputs() to get the input file which can eliminate
1721 # the assumptions about the output file name of the dependency.
1722
1723 input_dir = get_label_info("//src/tools/melon", "root_out_dir");
1724 sources = [ "$input_dir/melon" ]
1725
1726 outputs = [ "$target_gen_dir/{{source_file_part}}" ]
1727
1728 # Depend on the target to build the file before copying.
1729 deps = [ "//src/tools/melon" ]
1730 }
Brett Wilson796ed472018-07-16 15:11:09 -07001731```
[email protected]449f3e42024-08-01 21:43:27 +08001732### **create_bundle**: [ios/macOS] Build an iOS or macOS bundle. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001733
1734```
1735 This target generates an iOS or macOS bundle (which is a directory with a
1736 well-know structure). This target does not define any sources, instead they
1737 are computed from all "bundle_data" target this one depends on transitively
1738 (the recursion stops at "create_bundle" targets).
1739
Sylvain Defresned46f92f2019-04-03 16:14:29 +02001740 The "bundle_*_dir" are be used for the expansion of {{bundle_*_dir}} rules in
1741 "bundle_data" outputs. The properties are optional but must be defined if any
1742 of the "bundle_data" target use them.
Brett Wilson796ed472018-07-16 15:11:09 -07001743
1744 This target can be used on all platforms though it is designed only to
1745 generate iOS or macOS bundle. In cross-platform projects, it is advised to put
1746 it behind iOS/macOS conditionals.
1747
1748 If a create_bundle is specified as a data_deps for another target, the bundle
1749 is considered a leaf, and its public and private dependencies will not
1750 contribute to any data or data_deps. Required runtime dependencies should be
1751 placed in the bundle. A create_bundle can declare its own explicit data and
1752 data_deps, however.
1753```
1754
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001755#### **Post-processing**
Brett Wilson796ed472018-07-16 15:11:09 -07001756
1757```
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001758 Some bundle needs to be post-processed as part of the build (e.g. on iOS all
1759 application needs to be code signed to run on a device). The post processing
1760 step can be configured via the post_processing_script variable.
Brett Wilson796ed472018-07-16 15:11:09 -07001761
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001762 If set, `post_processing_script` is the path of a script that invoked after
1763 all files have been moved into the bundle. The script must not change any file
1764 in the bundle, but may add new files.
Brett Wilson796ed472018-07-16 15:11:09 -07001765
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001766 If `post_processing_script` is defined, then `post_processing_outputs` must
1767 be defined and non-empty to inform when the script needs to be re-run. The
1768 `post_processing_args` will be passed as is to the script (so path have to be
1769 rebased) and additional inputs may be listed via `post_processing_sources`.
1770```
1771
1772#### **Migration**
1773
1774```
1775 The post-processing step used to be limited to code-signing. The properties
1776 used to be named `code_signing_$name` instead of `post_processing_$name`. The
1777 old names are still accepted as alias to facilitate migration but a warning
1778 will be emitted and the alias eventually be removed.
Brett Wilson796ed472018-07-16 15:11:09 -07001779```
1780
1781#### **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 Defresnef07499a2024-04-04 13:06:37 +02001792 post_processing_args, post_processing_script,
1793 post_processing_sources, post_processing_outputs,
1794 xcode_extra_attributes, xcode_test_application_name,
1795 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"
1870 post_processing_sources = [
Brett Wilson796ed472018-07-16 15:11:09 -07001871 invoker.entitlements_path,
1872 "$target_gen_dir/$app_name",
1873 ]
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001874 post_processing_outputs = [
Brett Wilson796ed472018-07-16 15:11:09 -07001875 "$bundle_root_dir/$app_name",
1876 "$bundle_root_dir/_CodeSignature/CodeResources",
1877 "$bundle_root_dir/embedded.mobileprovision",
1878 "$target_gen_dir/$app_name.xcent",
1879 ]
Sylvain Defresnef07499a2024-04-04 13:06:37 +02001880 post_processing_args = [
1881 "-i=" + ios_post_processing_identity,
Brett Wilson796ed472018-07-16 15:11:09 -07001882 "-b=" + rebase_path(
1883 "$target_gen_dir/$app_name", root_build_dir),
1884 "-e=" + rebase_path(
1885 invoker.entitlements_path, root_build_dir),
1886 "-e=" + rebase_path(
1887 "$target_gen_dir/$app_name.xcent", root_build_dir),
1888 rebase_path(bundle_root_dir, root_build_dir),
1889 ]
1890 } else {
1891 deps += [ ":${app_name}_bundle_executable" ]
1892 }
1893 }
1894 }
1895 }
1896```
[email protected]449f3e42024-08-01 21:43:27 +08001897### **executable**: Declare an executable target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07001898
Julie Hockettce1fa072019-05-07 17:44:37 -07001899#### **Language and compilation**
1900
1901```
1902 The tools and commands used to create this target type will be
1903 determined by the source files in its sources. Targets containing
1904 multiple compiler-incompatible languages are not allowed (e.g. a
1905 target containing both C and C++ sources is acceptable, but a
1906 target containing C and Rust sources is not).
1907```
1908
Brett Wilson796ed472018-07-16 15:11:09 -07001909#### **Variables**
1910
1911```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001912 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
1913 cflags_objcc, defines, include_dirs, inputs, ldflags,
1914 lib_dirs, libs, precompiled_header, precompiled_source,
1915 rustenv, rustflags, swiftflags, testonly
1916 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
1917 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07001918 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08001919 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001920 output_extension, output_name, public, sources, testonly,
Nate Fischer8ed01d32019-01-08 17:32:01 -08001921 visibility
Petr Hosekadd1bb12019-09-11 14:39:38 -07001922 Rust variables: aliased_deps, crate_root, crate_name
Nate Fischer8ed01d32019-01-08 17:32:01 -08001923```
[email protected]449f3e42024-08-01 21:43:27 +08001924### **generated_file**: Declare a generated_file target. [Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08001925
1926```
1927 Writes data value(s) to disk on resolution. This target type mirrors some
1928 functionality of the write_file() function, but also provides the ability to
1929 collect metadata from its dependencies on resolution rather than writing out
Keir Mierle45611e32019-11-12 11:18:00 -08001930 at parse time.
Nate Fischer8ed01d32019-01-08 17:32:01 -08001931
1932 The `outputs` variable is required to be a list with a single element,
1933 specifying the intended location of the output file.
1934
1935 The `output_conversion` variable specified the format to write the
Sylvain Defresne72d5a6e2021-06-15 17:01:32 +02001936 value. See `gn help io_conversion`.
Nate Fischer8ed01d32019-01-08 17:32:01 -08001937
Tomasz Åšniatowski46b572c2021-09-03 21:47:17 +02001938 One of `contents` or `data_keys` must be specified; use of `contents` will
1939 write the contents of that value to file, while use of `data_keys` will
1940 trigger a metadata collection walk based on the dependencies of the target and
1941 the optional values of the `rebase` and `walk_keys` variables. See
Nate Fischer8ed01d32019-01-08 17:32:01 -08001942 `gn help metadata`.
1943
1944 Collected metadata, if specified, will be returned in postorder of
1945 dependencies. See the example for details.
1946```
1947
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001948#### **Variables**
1949
1950```
1951 Dependent configs: all_dependent_configs, public_configs
1952 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
1953 write_runtime_deps
1954 General: check_includes, configs, data, friend, inputs, metadata,
1955 output_extension, output_name, public, sources, testonly,
1956 visibility
1957 Generated file: contents, data_keys, rebase, walk_keys, output_conversion
1958```
1959
Nate Fischer8ed01d32019-01-08 17:32:01 -08001960#### **Example (metadata collection)**
1961
1962```
1963 Given the following targets defined in //base/BUILD.gn, where A depends on B
1964 and B depends on C and D:
1965
1966 group("a") {
1967 metadata = {
1968 doom_melon = [ "enable" ]
1969 my_files = [ "foo.cpp" ]
1970
Keir Mierle45611e32019-11-12 11:18:00 -08001971 # Note: this is functionally equivalent to not defining `my_barrier`
1972 # at all in this target's metadata.
Nate Fischer8ed01d32019-01-08 17:32:01 -08001973 my_barrier = [ "" ]
1974 }
1975
1976 deps = [ ":b" ]
1977 }
1978
Julie Hockettd69a9c32019-01-23 14:36:18 -08001979 group("b") {
Nate Fischer8ed01d32019-01-08 17:32:01 -08001980 metadata = {
1981 my_files = [ "bar.cpp" ]
1982 my_barrier = [ ":c" ]
1983 }
1984
1985 deps = [ ":c", ":d" ]
1986 }
1987
1988 group("c") {
1989 metadata = {
1990 doom_melon = [ "disable" ]
1991 my_files = [ "baz.cpp" ]
1992 }
1993 }
1994
1995 group("d") {
1996 metadata = {
1997 my_files = [ "missing.cpp" ]
1998 }
1999 }
2000
2001 If the following generated_file target is defined:
2002
2003 generated_file("my_files_metadata") {
2004 outputs = [ "$root_build_dir/my_files.json" ]
2005 data_keys = [ "my_files" ]
2006
2007 deps = [ "//base:a" ]
2008 }
2009
2010 The following will be written to "$root_build_dir/my_files.json" (less the
2011 comments):
2012 [
2013 "baz.cpp", // from //base:c via //base:b
2014 "missing.cpp" // from //base:d via //base:b
2015 "bar.cpp", // from //base:b via //base:a
2016 "foo.cpp", // from //base:a
2017 ]
2018
2019 Alternatively, as an example of using walk_keys, if the following
2020 generated_file target is defined:
2021
2022 generated_file("my_files_metadata") {
2023 outputs = [ "$root_build_dir/my_files.json" ]
2024 data_keys = [ "my_files" ]
2025 walk_keys = [ "my_barrier" ]
2026
2027 deps = [ "//base:a" ]
2028 }
2029
2030 The following will be written to "$root_build_dir/my_files.json" (again less
2031 the comments):
2032 [
2033 "baz.cpp", // from //base:c via //base:b
2034 "bar.cpp", // from //base:b via //base:a
2035 "foo.cpp", // from //base:a
2036 ]
2037
2038 If `rebase` is used in the following generated_file target:
2039
2040 generated_file("my_files_metadata") {
2041 outputs = [ "$root_build_dir/my_files.json" ]
2042 data_keys = [ "my_files" ]
2043 walk_keys = [ "my_barrier" ]
2044 rebase = root_build_dir
2045
2046 deps = [ "//base:a" ]
2047 }
2048
2049 The following will be written to "$root_build_dir/my_files.json" (again less
2050 the comments) (assuming root_build_dir = "//out"):
2051 [
2052 "../base/baz.cpp", // from //base:c via //base:b
2053 "../base/bar.cpp", // from //base:b via //base:a
2054 "../base/foo.cpp", // from //base:a
2055 ]
2056```
[email protected]449f3e42024-08-01 21:43:27 +08002057### **group**: Declare a named group of targets. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002058
2059```
2060 This target type allows you to create meta-targets that just collect a set of
2061 dependencies into one named target. Groups can additionally specify configs
2062 that apply to their dependents.
2063```
2064
2065#### **Variables**
2066
2067```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002068 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2069 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002070 Dependent configs: all_dependent_configs, public_configs
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002071 General: check_includes, configs, data, friend, inputs, metadata,
2072 output_extension, output_name, public, sources, testonly,
2073 visibility
Brett Wilson796ed472018-07-16 15:11:09 -07002074```
2075
2076#### **Example**
2077
2078```
2079 group("all") {
2080 deps = [
2081 "//project:runner",
2082 "//project:unit_tests",
2083 ]
2084 }
2085```
[email protected]449f3e42024-08-01 21:43:27 +08002086### **loadable_module**: Declare a loadable module target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002087
2088```
2089 This target type allows you to create an object file that is (and can only
2090 be) loaded and unloaded at runtime.
2091
2092 A loadable module will be specified on the linker line for targets listing
2093 the loadable module in its "deps". If you don't want this (if you don't need
2094 to dynamically load the library at runtime), then you should use a
2095 "shared_library" target type instead.
2096```
2097
Julie Hockettce1fa072019-05-07 17:44:37 -07002098#### **Language and compilation**
2099
2100```
2101 The tools and commands used to create this target type will be
2102 determined by the source files in its sources. Targets containing
2103 multiple compiler-incompatible languages are not allowed (e.g. a
2104 target containing both C and C++ sources is acceptable, but a
2105 target containing C and Rust sources is not).
2106```
2107
Brett Wilson796ed472018-07-16 15:11:09 -07002108#### **Variables**
2109
2110```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002111 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2112 cflags_objcc, defines, include_dirs, inputs, ldflags,
2113 lib_dirs, libs, precompiled_header, precompiled_source,
2114 rustenv, rustflags, swiftflags, testonly
2115 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2116 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002117 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08002118 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002119 output_extension, output_name, public, sources, testonly,
Nate Fischer8ed01d32019-01-08 17:32:01 -08002120 visibility
Petr Hosekadd1bb12019-09-11 14:39:38 -07002121 Rust variables: aliased_deps, crate_root, crate_name, crate_type
Julie Hockettce1fa072019-05-07 17:44:37 -07002122```
[email protected]449f3e42024-08-01 21:43:27 +08002123### **rust_library**: Declare a Rust library target. [Back to Top](#gn-reference)
Julie Hockettce1fa072019-05-07 17:44:37 -07002124
2125```
2126 A Rust library is an archive containing additional rust-c provided metadata.
2127 These are the files produced by the rustc compiler with the `.rlib`
2128 extension, and are the intermediate step for most Rust-based binaries.
2129```
2130
2131#### **Language and compilation**
2132
2133```
2134 The tools and commands used to create this target type will be
2135 determined by the source files in its sources. Targets containing
2136 multiple compiler-incompatible languages are not allowed (e.g. a
2137 target containing both C and C++ sources is acceptable, but a
2138 target containing C and Rust sources is not).
2139```
2140
2141#### **Variables**
2142
2143```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002144 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2145 cflags_objcc, defines, include_dirs, inputs, ldflags,
2146 lib_dirs, libs, precompiled_header, precompiled_source,
2147 rustenv, rustflags, swiftflags, testonly
2148 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2149 write_runtime_deps
Julie Hockettce1fa072019-05-07 17:44:37 -07002150 Dependent configs: all_dependent_configs, public_configs
2151 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002152 output_extension, output_name, public, sources, testonly,
Julie Hockettce1fa072019-05-07 17:44:37 -07002153 visibility
Petr Hosekadd1bb12019-09-11 14:39:38 -07002154 Rust variables: aliased_deps, crate_root, crate_name
Brett Wilson796ed472018-07-16 15:11:09 -07002155```
[email protected]449f3e42024-08-01 21:43:27 +08002156### **rust_proc_macro**: Declare a Rust procedural macro target. [Back to Top](#gn-reference)
Petr Hosekfe36c7c2019-11-26 14:38:08 -08002157
2158```
2159 A Rust procedural macro allows creating syntax extensions as execution of a
2160 function. They are compiled as dynamic libraries and used by the compiler at
2161 runtime.
2162
2163 Their use is the same as of other Rust libraries, but their build has some
2164 additional restrictions in terms of supported flags.
2165```
2166
2167#### **Language and compilation**
2168
2169```
2170 The tools and commands used to create this target type will be
2171 determined by the source files in its sources. Targets containing
2172 multiple compiler-incompatible languages are not allowed (e.g. a
2173 target containing both C and C++ sources is acceptable, but a
2174 target containing C and Rust sources is not).
2175```
2176
2177#### **Variables**
2178
2179```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002180 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2181 cflags_objcc, defines, include_dirs, inputs, ldflags,
2182 lib_dirs, libs, precompiled_header, precompiled_source,
2183 rustenv, rustflags, swiftflags, testonly
2184 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2185 write_runtime_deps
Petr Hosekfe36c7c2019-11-26 14:38:08 -08002186 Dependent configs: all_dependent_configs, public_configs
2187 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002188 output_extension, output_name, public, sources, testonly,
Petr Hosekfe36c7c2019-11-26 14:38:08 -08002189 visibility
2190 Rust variables: aliased_deps, crate_root, crate_name
2191```
[email protected]449f3e42024-08-01 21:43:27 +08002192### **shared_library**: Declare a shared library target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002193
2194```
2195 A shared library will be specified on the linker line for targets listing the
2196 shared library in its "deps". If you don't want this (say you dynamically
2197 load the library at runtime), then you should depend on the shared library
2198 via "data_deps" or, on Darwin platforms, use a "loadable_module" target type
2199 instead.
2200```
2201
Julie Hockettce1fa072019-05-07 17:44:37 -07002202#### **Language and compilation**
2203
2204```
2205 The tools and commands used to create this target type will be
2206 determined by the source files in its sources. Targets containing
2207 multiple compiler-incompatible languages are not allowed (e.g. a
2208 target containing both C and C++ sources is acceptable, but a
2209 target containing C and Rust sources is not).
2210```
2211
Brett Wilson796ed472018-07-16 15:11:09 -07002212#### **Variables**
2213
2214```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002215 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2216 cflags_objcc, defines, include_dirs, inputs, ldflags,
2217 lib_dirs, libs, precompiled_header, precompiled_source,
2218 rustenv, rustflags, swiftflags, testonly
2219 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2220 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002221 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08002222 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002223 output_extension, output_name, public, sources, testonly,
Nate Fischer8ed01d32019-01-08 17:32:01 -08002224 visibility
Petr Hosekadd1bb12019-09-11 14:39:38 -07002225 Rust variables: aliased_deps, crate_root, crate_name, crate_type
Brett Wilson796ed472018-07-16 15:11:09 -07002226```
[email protected]449f3e42024-08-01 21:43:27 +08002227### **source_set**: Declare a source set target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002228
2229```
Robert Sesekd0a6f072020-05-15 11:21:22 -04002230 Only C-language source sets are supported at the moment.
Julie Hockettce1fa072019-05-07 17:44:37 -07002231```
2232
2233#### **C-language source_sets**
2234
2235```
Brett Wilson796ed472018-07-16 15:11:09 -07002236 A source set is a collection of sources that get compiled, but are not linked
2237 to produce any kind of library. Instead, the resulting object files are
2238 implicitly added to the linker line of all targets that depend on the source
2239 set.
2240
2241 In most cases, a source set will behave like a static library, except no
2242 actual library file will be produced. This will make the build go a little
2243 faster by skipping creation of a large static library, while maintaining the
2244 organizational benefits of focused build targets.
2245
2246 The main difference between a source set and a static library is around
2247 handling of exported symbols. Most linkers assume declaring a function
2248 exported means exported from the static library. The linker can then do dead
2249 code elimination to delete code not reachable from exported functions.
2250
2251 A source set will not do this code elimination since there is no link step.
Julie Hockette2a29402018-07-31 10:11:42 -07002252 This allows you to link many source sets into a shared library and have the
Brett Wilson796ed472018-07-16 15:11:09 -07002253 "exported symbol" notation indicate "export from the final shared library and
2254 not from the intermediate targets." There is no way to express this concept
2255 when linking multiple static libraries into a shared library.
2256```
2257
2258#### **Variables**
2259
2260```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002261 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2262 cflags_objcc, defines, include_dirs, inputs, ldflags,
2263 lib_dirs, libs, precompiled_header, precompiled_source,
2264 rustenv, rustflags, swiftflags, testonly
2265 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2266 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002267 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08002268 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002269 output_extension, output_name, public, sources, testonly,
Nate Fischer8ed01d32019-01-08 17:32:01 -08002270 visibility
Brett Wilson796ed472018-07-16 15:11:09 -07002271```
[email protected]449f3e42024-08-01 21:43:27 +08002272### **static_library**: Declare a static library target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002273
2274```
2275 Make a ".a" / ".lib" file.
2276
2277 If you only need the static library for intermediate results in the build,
2278 you should consider a source_set instead since it will skip the (potentially
2279 slow) step of creating the intermediate library file.
2280```
2281
2282#### **Variables**
2283
2284```
2285 complete_static_lib
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002286 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2287 cflags_objcc, defines, include_dirs, inputs, ldflags,
2288 lib_dirs, libs, precompiled_header, precompiled_source,
2289 rustenv, rustflags, swiftflags, testonly
2290 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2291 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002292 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08002293 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002294 output_extension, output_name, public, sources, testonly,
Nate Fischer8ed01d32019-01-08 17:32:01 -08002295 visibility
Petr Hosekadd1bb12019-09-11 14:39:38 -07002296 Rust variables: aliased_deps, crate_root, crate_name
Julie Hockettce1fa072019-05-07 17:44:37 -07002297
2298 The tools and commands used to create this target type will be
2299 determined by the source files in its sources. Targets containing
2300 multiple compiler-incompatible languages are not allowed (e.g. a
2301 target containing both C and C++ sources is acceptable, but a
2302 target containing C and Rust sources is not).
Brett Wilson796ed472018-07-16 15:11:09 -07002303```
[email protected]449f3e42024-08-01 21:43:27 +08002304### **target**: Declare a target with the given programmatic type. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002305
2306```
2307 target(target_type_string, target_name_string) { ... }
2308
2309 The target() function is a way to invoke a built-in target or template with a
2310 type determined at runtime. This is useful for cases where the type of a
2311 target might not be known statically.
2312
2313 Only templates and built-in target functions are supported for the
2314 target_type_string parameter. Arbitrary functions, configs, and toolchains
2315 are not supported.
2316
2317 The call:
2318 target("source_set", "doom_melon") {
2319 Is equivalent to:
2320 source_set("doom_melon") {
2321```
2322
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002323#### **Common target variables**
2324
2325```
2326 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2327 write_runtime_deps
2328 Dependent configs: all_dependent_configs, public_configs
2329 General: check_includes, configs, data, friend, inputs, metadata,
2330 output_extension, output_name, public, sources, testonly,
2331 visibility
2332
2333 Targets will also have variables specific to that type, see "gn help "
2334 for more.
2335```
2336
Brett Wilson796ed472018-07-16 15:11:09 -07002337#### **Example**
2338
2339```
2340 if (foo_build_as_shared) {
2341 my_type = "shared_library"
2342 } else {
2343 my_type = "source_set"
2344 }
2345
2346 target(my_type, "foo") {
2347 ...
2348 }
2349```
2350## Buildfile functions
2351
[email protected]449f3e42024-08-01 21:43:27 +08002352### **assert**: Assert an expression is true at generation time. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002353
2354```
2355 assert( [, ])
2356
2357 If the condition is false, the build will fail with an error. If the
2358 optional second argument is provided, that string will be printed
2359 with the error message.
2360```
2361
2362#### **Examples**
2363
2364```
2365 assert(is_win)
2366 assert(defined(sources), "Sources must be defined");
2367```
[email protected]449f3e42024-08-01 21:43:27 +08002368### **config**: Defines a configuration object. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002369
2370```
2371 Configuration objects can be applied to targets and specify sets of compiler
2372 flags, includes, defines, etc. They provide a way to conveniently group sets
2373 of this configuration information.
2374
2375 A config is referenced by its label just like a target.
2376
2377 The values in a config are additive only. If you want to remove a flag you
2378 need to remove the corresponding config that sets it. The final set of flags,
2379 defines, etc. for a target is generated in this order:
2380
Nico Weber693f9fb2021-10-08 15:33:57 -04002381 1. The values specified directly on the target (rather than using a config).
Brett Wilson796ed472018-07-16 15:11:09 -07002382 2. The configs specified in the target's "configs" list, in order.
2383 3. Public_configs from a breadth-first traversal of the dependency tree in
2384 the order that the targets appear in "deps".
2385 4. All dependent configs from a breadth-first traversal of the dependency
2386 tree in the order that the targets appear in "deps".
2387```
2388
Joe Armstrong39413942019-03-15 10:34:03 +08002389#### **More background**
2390
2391```
2392 Configs solve a problem where the build system needs to have a higher-level
2393 understanding of various compiler settings. For example, some compiler flags
2394 have to appear in a certain order relative to each other, some settings like
2395 defines and flags logically go together, and the build system needs to
2396 de-duplicate flags even though raw command-line parameters can't always be
2397 operated on in that way.
2398
2399 The config gives a name to a group of settings that can then be reasoned
2400 about by GN. GN can know that configs with the same label are the same thing
2401 so can be de-duplicated. It allows related settings to be grouped so they
2402 are added or removed as a unit. And it allows targets to refer to settings
2403 with conceptual names ("no_rtti", "enable_exceptions", etc.) rather than
2404 having to hard-coding every compiler's flags each time they are referred to.
2405```
2406
Brett Wilson796ed472018-07-16 15:11:09 -07002407#### **Variables valid in a config definition**
Joe Armstrong39413942019-03-15 10:34:03 +08002408
Brett Wilson796ed472018-07-16 15:11:09 -07002409```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002410 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2411 cflags_objcc, defines, include_dirs, inputs, ldflags,
2412 lib_dirs, libs, precompiled_header, precompiled_source,
2413 rustenv, rustflags, swiftflags, testonly
Brett Wilson796ed472018-07-16 15:11:09 -07002414 Nested configs: configs
Tomasz Åšniatowski46b572c2021-09-03 21:47:17 +02002415 General: visibility
Brett Wilson796ed472018-07-16 15:11:09 -07002416```
2417
2418#### **Variables on a target used to apply configs**
2419
2420```
2421 all_dependent_configs, configs, public_configs
2422```
2423
2424#### **Example**
2425
2426```
2427 config("myconfig") {
Joe Armstrongf5ad8072019-05-08 08:42:56 +08002428 include_dirs = [ "include/common" ]
Brett Wilson796ed472018-07-16 15:11:09 -07002429 defines = [ "ENABLE_DOOM_MELON" ]
2430 }
2431
2432 executable("mything") {
2433 configs = [ ":myconfig" ]
2434 }
2435```
[email protected]449f3e42024-08-01 21:43:27 +08002436### **declare_args**: Declare build arguments. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002437
2438```
2439 Introduces the given arguments into the current scope. If they are not
2440 specified on the command line or in a toolchain's arguments, the default
2441 values given in the declare_args block will be used. However, these defaults
2442 will not override command-line values.
2443
2444 See also "gn help buildargs" for an overview.
2445
2446 The precise behavior of declare args is:
2447
2448 1. The declare_args() block executes. Any variable defined in the enclosing
2449 scope is available for reading, but any variable defined earlier in
2450 the current scope is not (since the overrides haven't been applied yet).
2451
2452 2. At the end of executing the block, any variables set within that scope
Petr Hosek7617b592019-10-02 09:52:21 -07002453 are saved, with the values specified in the block used as the "default value"
2454 for that argument. Once saved, these variables are available for override
2455 via args.gn.
Brett Wilson796ed472018-07-16 15:11:09 -07002456
2457 3. User-defined overrides are applied. Anything set in "gn args" now
2458 overrides any default values. The resulting set of variables is promoted
2459 to be readable from the following code in the file.
2460
2461 This has some ramifications that may not be obvious:
2462
2463 - You should not perform difficult work inside a declare_args block since
2464 this only sets a default value that may be discarded. In particular,
2465 don't use the result of exec_script() to set the default value. If you
2466 want to have a script-defined default, set some default "undefined" value
2467 like [], "", or -1, and after the declare_args block, call exec_script if
2468 the value is unset by the user.
2469
2470 - Because you cannot read the value of a variable defined in the same
2471 block, if you need to make the default value of one arg depend
2472 on the possibly-overridden value of another, write two separate
2473 declare_args() blocks:
2474
2475 declare_args() {
2476 enable_foo = true
2477 }
2478 declare_args() {
2479 # Bar defaults to same user-overridden state as foo.
2480 enable_bar = enable_foo
2481 }
2482```
2483
2484#### **Example**
2485
2486```
2487 declare_args() {
2488 enable_teleporter = true
2489 enable_doom_melon = false
2490 }
2491
2492 If you want to override the (default disabled) Doom Melon:
2493 gn --args="enable_doom_melon=true enable_teleporter=true"
2494 This also sets the teleporter, but it's already defaulted to on so it will
2495 have no effect.
2496```
[email protected]449f3e42024-08-01 21:43:27 +08002497### **defined**: Returns whether an identifier is defined. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002498
2499```
2500 Returns true if the given argument is defined. This is most useful in
2501 templates to assert that the caller set things up properly.
2502
2503 You can pass an identifier:
2504 defined(foo)
2505 which will return true or false depending on whether foo is defined in the
2506 current scope.
2507
2508 You can also check a named scope:
2509 defined(foo.bar)
2510 which will return true or false depending on whether bar is defined in the
2511 named scope foo. It will throw an error if foo is not defined or is not a
2512 scope.
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07002513
2514 You can also check a named scope using a subscript string expression:
2515 defined(foo[bar + "_name"])
Takuto Ikuta26aa46c2023-05-09 16:28:45 +09002516 which will return true or false depending on whether the subscript
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07002517 expression expands to the name of a member of the scope foo. It will
2518 throw an error if foo is not defined or is not a scope, or if the
2519 expression does not expand to a string, or if it is an empty string.
Brett Wilson796ed472018-07-16 15:11:09 -07002520```
2521
2522#### **Example**
2523
2524```
2525 template("mytemplate") {
2526 # To help users call this template properly...
2527 assert(defined(invoker.sources), "Sources must be defined")
2528
2529 # If we want to accept an optional "values" argument, we don't
2530 # want to dereference something that may not be defined.
2531 if (defined(invoker.values)) {
2532 values = invoker.values
2533 } else {
2534 values = "some default value"
2535 }
2536 }
2537```
[email protected]449f3e42024-08-01 21:43:27 +08002538### **exec_script**: Synchronously run a script and return the output. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002539
2540```
2541 exec_script(filename,
2542 arguments = [],
2543 input_conversion = "",
2544 file_dependencies = [])
2545
2546 Runs the given script, returning the stdout of the script. The build
2547 generation will fail if the script does not exist or returns a nonzero exit
2548 code.
2549
2550 The current directory when executing the script will be the root build
2551 directory. If you are passing file names, you will want to use the
2552 rebase_path() function to make file names relative to this path (see "gn help
2553 rebase_path").
Gary Miguelce7fa362018-09-17 12:48:17 -07002554
2555 The default script interpreter is Python ("python" on POSIX, "python.exe" or
2556 "python.bat" on Windows). This can be configured by the script_executable
2557 variable, see "gn help dotfile".
Brett Wilson796ed472018-07-16 15:11:09 -07002558```
2559
2560#### **Arguments**:
2561
2562```
2563 filename:
Gary Miguelce7fa362018-09-17 12:48:17 -07002564 File name of script to execute. Non-absolute names will be treated as
2565 relative to the current build file.
Brett Wilson796ed472018-07-16 15:11:09 -07002566
2567 arguments:
2568 A list of strings to be passed to the script as arguments. May be
2569 unspecified or the empty list which means no arguments.
2570
2571 input_conversion:
Sylvain Defresne72d5a6e2021-06-15 17:01:32 +02002572 Controls how the file is read and parsed. See `gn help io_conversion`.
Brett Wilson796ed472018-07-16 15:11:09 -07002573
2574 If unspecified, defaults to the empty string which causes the script
2575 result to be discarded. exec script will return None.
2576
2577 dependencies:
2578 (Optional) A list of files that this script reads or otherwise depends
2579 on. These dependencies will be added to the build result such that if any
2580 of them change, the build will be regenerated and the script will be
2581 re-run.
2582
2583 The script itself will be an implicit dependency so you do not need to
2584 list it.
2585```
2586
2587#### **Example**
2588
2589```
2590 all_lines = exec_script(
2591 "myscript.py", [some_input], "list lines",
2592 [ rebase_path("data_file.txt", root_build_dir) ])
2593
2594 # This example just calls the script with no arguments and discards the
2595 # result.
2596 exec_script("//foo/bar/myscript.py")
2597```
[email protected]449f3e42024-08-01 21:43:27 +08002598### **filter_exclude**: Remove values that match a set of patterns. [Back to Top](#gn-reference)
Sylvain Defresneaff489a2020-03-11 18:27:43 +01002599
2600```
2601 filter_exclude(values, exclude_patterns)
2602
2603 The argument values must be a list of strings.
2604
2605 The argument exclude_patterns must be a list of file patterns (see
2606 "gn help file_pattern"). Any elements in values matching at least one
2607 of those patterns will be excluded.
2608```
2609
2610#### **Examples**
2611```
2612 values = [ "foo.cc", "foo.h", "foo.proto" ]
2613 result = filter_exclude(values, [ "*.proto" ])
2614 # result will be [ "foo.cc", "foo.h" ]
2615```
[email protected]449f3e42024-08-01 21:43:27 +08002616### **filter_include**: Remove values that do not match a set of patterns. [Back to Top](#gn-reference)
Sylvain Defresneaff489a2020-03-11 18:27:43 +01002617
2618```
2619 filter_include(values, include_patterns)
2620
2621 The argument values must be a list of strings.
2622
2623 The argument include_patterns must be a list of file patterns (see
2624 "gn help file_pattern"). Only elements from values matching at least
2625 one of the pattern will be included.
2626```
2627
2628#### **Examples**
2629```
2630 values = [ "foo.cc", "foo.h", "foo.proto" ]
2631 result = filter_include(values, [ "*.proto" ])
2632 # result will be [ "foo.proto" ]
2633```
[email protected]449f3e42024-08-01 21:43:27 +08002634### **filter_labels_exclude**: Remove labels that match a set of patterns. [Back to Top](#gn-reference)
Aaron Woode05c0aa2024-02-14 13:40:53 -08002635
2636```
2637 filter_labels_exclude(labels, exclude_patterns)
2638
2639 The argument labels must be a list of strings.
2640
2641 The argument exclude_patterns must be a list of label patterns (see
2642 "gn help label_pattern"). Only elements from labels matching at least
2643 one of the patterns will be excluded.
2644```
2645
2646#### **Examples**
2647```
2648 labels = [ "//foo:baz", "//foo/bar:baz", "//bar:baz" ]
2649 result = filter_labels_exclude(labels, [ "//foo:*" ])
2650 # result will be [ "//foo/bar:baz", "//bar:baz" ]
2651```
[email protected]449f3e42024-08-01 21:43:27 +08002652### **filter_labels_include**: Remove labels that do not match a set of patterns. [Back to Top](#gn-reference)
Aaron Woode05c0aa2024-02-14 13:40:53 -08002653
2654```
2655 filter_labels_include(labels, include_patterns)
2656
2657 The argument labels must be a list of strings.
2658
2659 The argument include_patterns must be a list of label patterns (see
2660 "gn help label_pattern"). Only elements from labels matching at least
2661 one of the patterns will be included.
2662```
2663
2664#### **Examples**
2665```
2666 labels = [ "//foo:baz", "//foo/bar:baz", "//bar:baz" ]
2667 result = filter_labels_include(labels, [ "//foo:*" ])
2668 # result will be [ "//foo:baz" ]
2669```
[email protected]449f3e42024-08-01 21:43:27 +08002670### **foreach**: Iterate over a list. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002671
2672```
2673 foreach(, ) {
2674
2675 }
2676
2677 Executes the loop contents block over each item in the list, assigning the
2678 loop_var to each item in sequence. The will be a copy so assigning
2679 to it will not mutate the list. The loop will iterate over a copy of
2680 so mutating it inside the loop will not affect iteration.
2681
2682 The block does not introduce a new scope, so that variable assignments inside
2683 the loop will be visible once the loop terminates.
2684
2685 The loop variable will temporarily shadow any existing variables with the
2686 same name for the duration of the loop. After the loop terminates the loop
2687 variable will no longer be in scope, and the previous value (if any) will be
2688 restored.
2689```
2690
2691#### **Example**
2692
2693```
2694 mylist = [ "a", "b", "c" ]
2695 foreach(i, mylist) {
2696 print(i)
2697 }
2698
2699 Prints:
2700 a
2701 b
2702 c
2703```
[email protected]449f3e42024-08-01 21:43:27 +08002704### **forward_variables_from**: Copies variables from a different scope. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002705
2706```
2707 forward_variables_from(from_scope, variable_list_or_star,
2708 variable_to_not_forward_list = [])
2709
2710 Copies the given variables from the given scope to the local scope if they
2711 exist. This is normally used in the context of templates to use the values of
2712 variables defined in the template invocation to a template-defined target.
2713
2714 The variables in the given variable_list will be copied if they exist in the
2715 given scope or any enclosing scope. If they do not exist, nothing will happen
2716 and they be left undefined in the current scope.
2717
2718 As a special case, if the variable_list is a string with the value of "*",
2719 all variables from the given scope will be copied. "*" only copies variables
2720 set directly on the from_scope, not enclosing ones. Otherwise it would
2721 duplicate all global variables.
2722
2723 When an explicit list of variables is supplied, if the variable exists in the
2724 current (destination) scope already, an error will be thrown. If "*" is
2725 specified, variables in the current scope will be clobbered (the latter is
2726 important because most targets have an implicit configs list, which means it
2727 wouldn't work at all if it didn't clobber).
2728
Brett Wilson796ed472018-07-16 15:11:09 -07002729 If variables_to_not_forward_list is non-empty, then it must contains a list
2730 of variable names that will not be forwarded. This is mostly useful when
2731 variable_list_or_star has a value of "*".
2732```
2733
2734#### **Examples**
2735
2736```
Andrew Grieve57a964c2018-09-14 10:50:56 -04002737 # forward_variables_from(invoker, ["foo"])
2738 # is equivalent to:
2739 assert(!defined(foo))
2740 if (defined(invoker.foo)) {
2741 foo = invoker.foo
2742 }
2743
Brett Wilson796ed472018-07-16 15:11:09 -07002744 # This is a common action template. It would invoke a script with some given
2745 # parameters, and wants to use the various types of deps and the visibility
2746 # from the invoker if it's defined. It also injects an additional dependency
2747 # to all targets.
2748 template("my_test") {
2749 action(target_name) {
2750 forward_variables_from(invoker, [ "data_deps", "deps",
Julie Hockette2a29402018-07-31 10:11:42 -07002751 "public_deps", "visibility"])
Brett Wilson796ed472018-07-16 15:11:09 -07002752 # Add our test code to the dependencies.
2753 # "deps" may or may not be defined at this point.
2754 if (defined(deps)) {
2755 deps += [ "//tools/doom_melon" ]
2756 } else {
2757 deps = [ "//tools/doom_melon" ]
2758 }
2759 }
2760 }
2761
Julie Hockette2a29402018-07-31 10:11:42 -07002762 # This is a template around a target whose type depends on a global variable.
2763 # It forwards all values from the invoker.
Brett Wilson796ed472018-07-16 15:11:09 -07002764 template("my_wrapper") {
2765 target(my_wrapper_target_type, target_name) {
2766 forward_variables_from(invoker, "*")
2767 }
2768 }
2769
2770 # A template that wraps another. It adds behavior based on one
2771 # variable, and forwards all others to the nested target.
2772 template("my_ios_test_app") {
2773 ios_test_app(target_name) {
2774 forward_variables_from(invoker, "*", ["test_bundle_name"])
2775 if (!defined(extra_substitutions)) {
2776 extra_substitutions = []
2777 }
2778 extra_substitutions += [ "BUNDLE_ID_TEST_NAME=$test_bundle_name" ]
2779 }
2780 }
2781```
[email protected]449f3e42024-08-01 21:43:27 +08002782### **get_label_info**: Get an attribute from a target's label. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002783
2784```
2785 get_label_info(target_label, what)
2786
2787 Given the label of a target, returns some attribute of that target. The
2788 target need not have been previously defined in the same file, since none of
2789 the attributes depend on the actual target definition, only the label itself.
2790
2791 See also "gn help get_target_outputs".
2792```
2793
2794#### **Possible values for the "what" parameter**
2795
2796```
2797 "name"
2798 The short name of the target. This will match the value of the
2799 "target_name" variable inside that target's declaration. For the label
2800 "//foo/bar:baz" this will return "baz".
2801
2802 "dir"
2803 The directory containing the target's definition, with no slash at the
2804 end. For the label "//foo/bar:baz" this will return "//foo/bar".
2805
2806 "target_gen_dir"
2807 The generated file directory for the target. This will match the value of
2808 the "target_gen_dir" variable when inside that target's declaration.
2809
2810 "root_gen_dir"
2811 The root of the generated file tree for the target. This will match the
2812 value of the "root_gen_dir" variable when inside that target's
2813 declaration.
2814
2815 "target_out_dir
2816 The output directory for the target. This will match the value of the
2817 "target_out_dir" variable when inside that target's declaration.
2818
2819 "root_out_dir"
2820 The root of the output file tree for the target. This will match the
2821 value of the "root_out_dir" variable when inside that target's
2822 declaration.
2823
2824 "label_no_toolchain"
2825 The fully qualified version of this label, not including the toolchain.
2826 For the input ":bar" it might return "//foo:bar".
2827
2828 "label_with_toolchain"
2829 The fully qualified version of this label, including the toolchain. For
2830 the input ":bar" it might return "//foo:bar(//toolchain:x64)".
2831
2832 "toolchain"
2833 The label of the toolchain. This will match the value of the
2834 "current_toolchain" variable when inside that target's declaration.
2835```
2836
2837#### **Examples**
2838
2839```
2840 get_label_info(":foo", "name")
2841 # Returns string "foo".
2842
2843 get_label_info("//foo/bar:baz", "target_gen_dir")
2844 # Returns string "//out/Debug/gen/foo/bar".
2845```
[email protected]449f3e42024-08-01 21:43:27 +08002846### **get_path_info**: Extract parts of a file or directory name. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002847
2848```
2849 get_path_info(input, what)
2850
2851 The first argument is either a string representing a file or directory name,
2852 or a list of such strings. If the input is a list the return value will be a
2853 list containing the result of applying the rule to each item in the input.
2854```
2855
2856#### **Possible values for the "what" parameter**
2857
2858```
2859 "file"
2860 The substring after the last slash in the path, including the name and
2861 extension. If the input ends in a slash, the empty string will be
2862 returned.
2863 "foo/bar.txt" => "bar.txt"
2864 "bar.txt" => "bar.txt"
2865 "foo/" => ""
2866 "" => ""
2867
2868 "name"
2869 The substring of the file name not including the extension.
2870 "foo/bar.txt" => "bar"
2871 "foo/bar" => "bar"
2872 "foo/" => ""
2873
2874 "extension"
2875 The substring following the last period following the last slash, or the
2876 empty string if not found. The period is not included.
2877 "foo/bar.txt" => "txt"
2878 "foo/bar" => ""
2879
2880 "dir"
2881 The directory portion of the name, not including the slash.
2882 "foo/bar.txt" => "foo"
2883 "//foo/bar" => "//foo"
2884 "foo" => "."
2885
2886 The result will never end in a slash, so if the resulting is empty, the
2887 system ("/") or source ("//") roots, a "." will be appended such that it
2888 is always legal to append a slash and a filename and get a valid path.
2889
2890 "out_dir"
2891 The output file directory corresponding to the path of the given file,
2892 not including a trailing slash.
2893 "//foo/bar/baz.txt" => "//out/Default/obj/foo/bar"
2894
2895 "gen_dir"
2896 The generated file directory corresponding to the path of the given file,
2897 not including a trailing slash.
2898 "//foo/bar/baz.txt" => "//out/Default/gen/foo/bar"
2899
2900 "abspath"
2901 The full absolute path name to the file or directory. It will be resolved
2902 relative to the current directory, and then the source- absolute version
2903 will be returned. If the input is system- absolute, the same input will
2904 be returned.
2905 "foo/bar.txt" => "//mydir/foo/bar.txt"
2906 "foo/" => "//mydir/foo/"
2907 "//foo/bar" => "//foo/bar" (already absolute)
2908 "/usr/include" => "/usr/include" (already absolute)
2909
2910 If you want to make the path relative to another directory, or to be
2911 system-absolute, see rebase_path().
2912```
2913
2914#### **Examples**
2915```
2916 sources = [ "foo.cc", "foo.h" ]
2917 result = get_path_info(source, "abspath")
2918 # result will be [ "//mydir/foo.cc", "//mydir/foo.h" ]
2919
2920 result = get_path_info("//foo/bar/baz.cc", "dir")
2921 # result will be "//foo/bar"
2922
2923 # Extract the source-absolute directory name,
Joe Armstrong39413942019-03-15 10:34:03 +08002924 result = get_path_info(get_path_info(path, "dir"), "abspath")
Brett Wilson796ed472018-07-16 15:11:09 -07002925```
[email protected]449f3e42024-08-01 21:43:27 +08002926### **get_target_outputs**: [file list] Get the list of outputs from a target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002927
2928```
2929 get_target_outputs(target_label)
2930
2931 Returns a list of output files for the named target. The named target must
2932 have been previously defined in the current file before this function is
2933 called (it can't reference targets in other files because there isn't a
2934 defined execution order, and it obviously can't reference targets that are
2935 defined after the function call).
2936
Julie Hockettce1fa072019-05-07 17:44:37 -07002937 Only copy, generated_file, and action targets are supported. The outputs from
2938 binary targets will depend on the toolchain definition which won't
2939 necessarily have been loaded by the time a given line of code has run, and
2940 source sets and groups have no useful output file.
Brett Wilson796ed472018-07-16 15:11:09 -07002941```
2942
2943#### **Return value**
2944
2945```
2946 The names in the resulting list will be absolute file paths (normally like
2947 "//out/Debug/bar.exe", depending on the build directory).
2948
Julie Hockettce1fa072019-05-07 17:44:37 -07002949 action, copy, and generated_file targets: this will just return the files
2950 specified in the "outputs" variable of the target.
Brett Wilson796ed472018-07-16 15:11:09 -07002951
2952 action_foreach targets: this will return the result of applying the output
2953 template to the sources (see "gn help source_expansion"). This will be the
2954 same result (though with guaranteed absolute file paths), as
2955 process_file_template will return for those inputs (see "gn help
2956 process_file_template").
2957
Brett Wilson796ed472018-07-16 15:11:09 -07002958 source sets and groups: this will return a list containing the path of the
RJ Ascani843b5002020-11-04 14:49:23 -08002959 "stamp" file that Ninja will produce once all outputs are generated. This
Brett Wilson796ed472018-07-16 15:11:09 -07002960 probably isn't very useful.
2961```
2962
2963#### **Example**
2964
2965```
2966 # Say this action generates a bunch of C source files.
2967 action_foreach("my_action") {
2968 sources = [ ... ]
2969 outputs = [ ... ]
2970 }
2971
2972 # Compile the resulting source files into a source set.
2973 source_set("my_lib") {
2974 sources = get_target_outputs(":my_action")
2975 }
2976```
[email protected]449f3e42024-08-01 21:43:27 +08002977### **getenv**: Get an environment variable. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002978
2979```
2980 value = getenv(env_var_name)
2981
2982 Returns the value of the given environment variable. If the value is not
2983 found, it will try to look up the variable with the "opposite" case (based on
2984 the case of the first letter of the variable), but is otherwise
2985 case-sensitive.
2986
2987 If the environment variable is not found, the empty string will be returned.
2988 Note: it might be nice to extend this if we had the concept of "none" in the
2989 language to indicate lookup failure.
2990```
2991
2992#### **Example**
2993
2994```
2995 home_dir = getenv("HOME")
2996```
[email protected]449f3e42024-08-01 21:43:27 +08002997### **import**: Import a file into the current scope. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002998
2999```
3000 The import command loads the rules and variables resulting from executing the
3001 given file into the current scope.
3002
3003 By convention, imported files are named with a .gni extension.
3004
3005 An import is different than a C++ "include". The imported file is executed in
3006 a standalone environment from the caller of the import command. The results
3007 of this execution are cached for other files that import the same .gni file.
3008
3009 Note that you can not import a BUILD.gn file that's otherwise used in the
3010 build. Files must either be imported or implicitly loaded as a result of deps
3011 rules, but not both.
3012
3013 The imported file's scope will be merged with the scope at the point import
3014 was called. If there is a conflict (both the current scope and the imported
3015 file define some variable or rule with the same name but different value), a
3016 runtime error will be thrown. Therefore, it's good practice to minimize the
3017 stuff that an imported file defines.
3018
3019 Variables and templates beginning with an underscore '_' are considered
3020 private and will not be imported. Imported files can use such variables for
3021 internal computation without affecting other files.
3022```
3023
3024#### **Examples**
3025
3026```
3027 import("//build/rules/idl_compilation_rule.gni")
3028
3029 # Looks in the current directory.
3030 import("my_vars.gni")
3031```
[email protected]449f3e42024-08-01 21:43:27 +08003032### **label_matches**: Returns true if the label matches any of a set of patterns. [Back to Top](#gn-reference)
Aaron Woode05c0aa2024-02-14 13:40:53 -08003033
3034```
3035 label_matches(target_label, patterns)
3036
3037 The argument patterns must be a list of label patterns (see
3038 "gn help label_pattern"). If the target_label matches any of the patterns,
3039 the function returns the value true.
3040```
3041
3042#### **Examples**
3043```
3044 result = label_matches("//baz:bar", [ "//foo/bar/*", "//baz:*" ])
3045 # result will be true
3046```
[email protected]449f3e42024-08-01 21:43:27 +08003047### **not_needed**: Mark variables from scope as not needed. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003048
3049```
3050 not_needed(variable_list_or_star, variable_to_ignore_list = [])
3051 not_needed(from_scope, variable_list_or_star,
3052 variable_to_ignore_list = [])
3053
3054 Mark the variables in the current or given scope as not needed, which means
3055 you will not get an error about unused variables for these. The
3056 variable_to_ignore_list allows excluding variables from "all matches" if
3057 variable_list_or_star is "*".
3058```
3059
3060#### **Example**
3061
3062```
3063 not_needed("*", [ "config" ])
3064 not_needed([ "data_deps", "deps" ])
3065 not_needed(invoker, "*", [ "config" ])
3066 not_needed(invoker, [ "data_deps", "deps" ])
3067```
[email protected]449f3e42024-08-01 21:43:27 +08003068### **pool**: Defines a pool object. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003069
3070```
3071 Pool objects can be applied to a tool to limit the parallelism of the
3072 build. This object has a single property "depth" corresponding to
3073 the number of tasks that may run simultaneously.
3074
3075 As the file containing the pool definition may be executed in the
3076 context of more than one toolchain it is recommended to specify an
3077 explicit toolchain when defining and referencing a pool.
3078
Julie Hockette2a29402018-07-31 10:11:42 -07003079 A pool named "console" defined in the root build file represents Ninja's
3080 console pool. Targets using this pool will have access to the console's
3081 stdin and stdout, and output will not be buffered. This special pool must
3082 have a depth of 1. Pools not defined in the root must not be named "console".
3083 The console pool can only be defined for the default toolchain.
3084 Refer to the Ninja documentation on the console pool for more info.
3085
Brett Wilson796ed472018-07-16 15:11:09 -07003086 A pool is referenced by its label just like a target.
3087```
3088
3089#### **Variables**
3090
3091```
3092 depth*
3093 * = required
3094```
3095
3096#### **Example**
3097
3098```
3099 if (current_toolchain == default_toolchain) {
3100 pool("link_pool") {
3101 depth = 1
3102 }
3103 }
3104
3105 toolchain("toolchain") {
3106 tool("link") {
3107 command = "..."
Petr Hosekadd1bb12019-09-11 14:39:38 -07003108 pool = ":link_pool($default_toolchain)"
Brett Wilson796ed472018-07-16 15:11:09 -07003109 }
3110 }
3111```
[email protected]449f3e42024-08-01 21:43:27 +08003112### **print**: Prints to the console. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003113
3114```
3115 Prints all arguments to the console separated by spaces. A newline is
3116 automatically appended to the end.
3117
3118 This function is intended for debugging. Note that build files are run in
3119 parallel so you may get interleaved prints. A buildfile may also be executed
3120 more than once in parallel in the context of different toolchains so the
3121 prints from one file may be duplicated or
3122 interleaved with itself.
3123```
3124
3125#### **Examples**
3126
3127```
3128 print("Hello world")
3129
3130 print(sources, deps)
3131```
[email protected]449f3e42024-08-01 21:43:27 +08003132### **print_stack_trace**: Prints a stack trace. [Back to Top](#gn-reference)
Aaron Wood24062bb2022-04-25 20:37:48 -07003133
3134```
3135 Prints the current file location, and all template invocations that led up to
3136 this location, to the console.
3137```
3138
3139#### **Examples**
3140
3141```
3142 template("foo"){
3143 print_stack_trace()
3144 }
3145 template("bar"){
3146 foo(target_name + ".foo") {
3147 baz = invoker.baz
3148 }
3149 }
3150 bar("lala") {
3151 baz = 42
3152 }
3153
3154 will print out the following:
3155
3156 print_stack_trace() initiated at //build.gn:2
3157 bar("lala") //BUILD.gn:9
3158 foo("lala.foo") //BUILD.gn:5
3159 print_stack_trace() //BUILD.gn:2
3160```
[email protected]449f3e42024-08-01 21:43:27 +08003161### **process_file_template**: Do template expansion over a list of files. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003162
3163```
3164 process_file_template(source_list, template)
3165
3166 process_file_template applies a template list to a source file list,
3167 returning the result of applying each template to each source. This is
3168 typically used for computing output file names from input files.
3169
3170 In most cases, get_target_outputs() will give the same result with shorter,
3171 more maintainable code. This function should only be used when that function
3172 can't be used (like there's no target or the target is defined in another
3173 build file).
3174```
3175
3176#### **Arguments**
3177
3178```
3179 The source_list is a list of file names.
3180
3181 The template can be a string or a list. If it is a list, multiple output
3182 strings are generated for each input.
3183
3184 The template should contain source expansions to which each name in the
3185 source list is applied. See "gn help source_expansion".
3186```
3187
3188#### **Example**
3189
3190```
3191 sources = [
3192 "foo.idl",
3193 "bar.idl",
3194 ]
3195 myoutputs = process_file_template(
3196 sources,
3197 [ "$target_gen_dir/{{source_name_part}}.cc",
3198 "$target_gen_dir/{{source_name_part}}.h" ])
3199
3200 The result in this case will be:
3201 [ "//out/Debug/foo.cc"
3202 "//out/Debug/foo.h"
3203 "//out/Debug/bar.cc"
3204 "//out/Debug/bar.h" ]
3205```
[email protected]449f3e42024-08-01 21:43:27 +08003206### **read_file**: Read a file into a variable. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003207
3208```
3209 read_file(filename, input_conversion)
3210
3211 Whitespace will be trimmed from the end of the file. Throws an error if the
3212 file can not be opened.
3213```
3214
3215#### **Arguments**
3216
3217```
3218 filename
3219 Filename to read, relative to the build file.
3220
3221 input_conversion
Sylvain Defresne72d5a6e2021-06-15 17:01:32 +02003222 Controls how the file is read and parsed. See `gn help io_conversion`.
Brett Wilson796ed472018-07-16 15:11:09 -07003223```
3224
3225#### **Example**
3226
3227```
3228 lines = read_file("foo.txt", "list lines")
3229```
[email protected]449f3e42024-08-01 21:43:27 +08003230### **rebase_path**: Rebase a file or directory to another location. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003231
3232```
3233 converted = rebase_path(input,
3234 new_base = "",
3235 current_base = ".")
3236
3237 Takes a string argument representing a file name, or a list of such strings
3238 and converts it/them to be relative to a different base directory.
3239
3240 When invoking the compiler or scripts, GN will automatically convert sources
3241 and include directories to be relative to the build directory. However, if
3242 you're passing files directly in the "args" array or doing other manual
3243 manipulations where GN doesn't know something is a file name, you will need
3244 to convert paths to be relative to what your tool is expecting.
3245
3246 The common case is to use this to convert paths relative to the current
3247 directory to be relative to the build directory (which will be the current
3248 directory when executing scripts).
3249
3250 If you want to convert a file path to be source-absolute (that is, beginning
3251 with a double slash like "//foo/bar"), you should use the get_path_info()
3252 function. This function won't work because it will always make relative
3253 paths, and it needs to support making paths relative to the source root, so
Robert Sesekd0a6f072020-05-15 11:21:22 -04003254 it can't also generate source-absolute paths without more special-cases.
Brett Wilson796ed472018-07-16 15:11:09 -07003255```
3256
3257#### **Arguments**
3258
3259```
3260 input
Robert Sesekd0a6f072020-05-15 11:21:22 -04003261 A string or list of strings representing file or directory names. These
Brett Wilson796ed472018-07-16 15:11:09 -07003262 can be relative paths ("foo/bar.txt"), system absolute paths
3263 ("/foo/bar.txt"), or source absolute paths ("//foo/bar.txt").
3264
3265 new_base
3266 The directory to convert the paths to be relative to. This can be an
3267 absolute path or a relative path (which will be treated as being relative
3268 to the current BUILD-file's directory).
3269
3270 As a special case, if new_base is the empty string (the default), all
3271 paths will be converted to system-absolute native style paths with system
3272 path separators. This is useful for invoking external programs.
3273
3274 current_base
3275 Directory representing the base for relative paths in the input. If this
3276 is not an absolute path, it will be treated as being relative to the
3277 current build file. Use "." (the default) to convert paths from the
3278 current BUILD-file's directory.
3279```
3280
3281#### **Return value**
3282
3283```
3284 The return value will be the same type as the input value (either a string or
3285 a list of strings). All relative and source-absolute file names will be
3286 converted to be relative to the requested output System-absolute paths will
3287 be unchanged.
3288
3289 Whether an output path will end in a slash will match whether the
3290 corresponding input path ends in a slash. It will return "." or "./"
3291 (depending on whether the input ends in a slash) to avoid returning empty
3292 strings. This means if you want a root path ("//" or "/") not ending in a
3293 slash, you can add a dot ("//.").
3294```
3295
3296#### **Example**
3297
3298```
3299 # Convert a file in the current directory to be relative to the build
3300 # directory (the current dir when executing compilers and scripts).
3301 foo = rebase_path("myfile.txt", root_build_dir)
3302 # might produce "../../project/myfile.txt".
3303
3304 # Convert a file to be system absolute:
3305 foo = rebase_path("myfile.txt")
3306 # Might produce "D:\\source\\project\\myfile.txt" on Windows or
3307 # "/home/you/source/project/myfile.txt" on Linux.
3308
3309 # Typical usage for converting to the build directory for a script.
3310 action("myscript") {
3311 # Don't convert sources, GN will automatically convert these to be relative
3312 # to the build directory when it constructs the command line for your
3313 # script.
3314 sources = [ "foo.txt", "bar.txt" ]
3315
3316 # Extra file args passed manually need to be explicitly converted
3317 # to be relative to the build directory:
3318 args = [
3319 "--data",
3320 rebase_path("//mything/data/input.dat", root_build_dir),
3321 "--rel",
3322 rebase_path("relative_path.txt", root_build_dir)
3323 ] + rebase_path(sources, root_build_dir)
3324 }
3325```
[email protected]449f3e42024-08-01 21:43:27 +08003326### **set_default_toolchain**: Sets the default toolchain name. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003327
3328```
3329 set_default_toolchain(toolchain_label)
3330
3331 The given label should identify a toolchain definition (see "gn help
3332 toolchain"). This toolchain will be used for all targets unless otherwise
3333 specified.
3334
3335 This function is only valid to call during the processing of the build
3336 configuration file. Since the build configuration file is processed
3337 separately for each toolchain, this function will be a no-op when called
3338 under any non-default toolchains.
3339
3340 For example, the default toolchain should be appropriate for the current
3341 environment. If the current environment is 32-bit and somebody references a
3342 target with a 64-bit toolchain, we wouldn't want processing of the build
3343 config file for the 64-bit toolchain to reset the default toolchain to
3344 64-bit, we want to keep it 32-bits.
3345```
3346
3347#### **Argument**
3348
3349```
3350 toolchain_label
3351 Toolchain name.
3352```
3353
3354#### **Example**
3355
3356```
3357 # Set default toolchain only has an effect when run in the context of the
3358 # default toolchain. Pick the right one according to the current CPU
3359 # architecture.
3360 if (target_cpu == "x64") {
3361 set_default_toolchain("//toolchains:64")
3362 } else if (target_cpu == "x86") {
3363 set_default_toolchain("//toolchains:32")
3364 }
3365```
[email protected]449f3e42024-08-01 21:43:27 +08003366### **set_defaults**: Set default values for a target type. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003367
3368```
3369 set_defaults() { }
3370
3371 Sets the default values for a given target type. Whenever target_type_name is
3372 seen in the future, the values specified in set_default's block will be
3373 copied into the current scope.
3374
3375 When the target type is used, the variable copying is very strict. If a
3376 variable with that name is already in scope, the build will fail with an
3377 error.
3378
3379 set_defaults can be used for built-in target types ("executable",
3380 "shared_library", etc.) and custom ones defined via the "template" command.
3381 It can be called more than once and the most recent call in any scope will
3382 apply, but there is no way to refer to the previous defaults and modify them
3383 (each call to set_defaults must supply a complete list of all defaults it
3384 wants). If you want to share defaults, store them in a separate variable.
3385```
3386
3387#### **Example**
3388
3389```
3390 set_defaults("static_library") {
3391 configs = [ "//tools/mything:settings" ]
3392 }
3393
Nico Webere49cb722018-08-28 13:10:29 -04003394 static_library("mylib") {
Brett Wilson796ed472018-07-16 15:11:09 -07003395 # The configs will be auto-populated as above. You can remove it if
3396 # you don't want the default for a particular default:
3397 configs -= [ "//tools/mything:settings" ]
3398 }
3399```
[email protected]449f3e42024-08-01 21:43:27 +08003400### **split_list**: Splits a list into N different sub-lists. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003401
3402```
3403 result = split_list(input, n)
3404
3405 Given a list and a number N, splits the list into N sub-lists of
3406 approximately equal size. The return value is a list of the sub-lists. The
3407 result will always be a list of size N. If N is greater than the number of
3408 elements in the input, it will be padded with empty lists.
3409
3410 The expected use is to divide source files into smaller uniform chunks.
3411```
3412
3413#### **Example**
3414
3415```
3416 The code:
3417 mylist = [1, 2, 3, 4, 5, 6]
3418 print(split_list(mylist, 3))
3419
3420 Will print:
3421 [[1, 2], [3, 4], [5, 6]
3422```
[email protected]449f3e42024-08-01 21:43:27 +08003423### **string_join**: Concatenates a list of strings with a separator. [Back to Top](#gn-reference)
Keir Mierle6ae63302019-11-08 23:02:18 -08003424
3425```
3426 result = string_join(separator, strings)
3427
3428 Concatenate a list of strings with intervening occurrences of separator.
3429```
3430
3431#### **Examples**
3432
3433```
3434 string_join("", ["a", "b", "c"]) --> "abc"
3435 string_join("|", ["a", "b", "c"]) --> "a|b|c"
3436 string_join(", ", ["a", "b", "c"]) --> "a, b, c"
3437 string_join("s", ["", ""]) --> "s"
3438```
[email protected]449f3e42024-08-01 21:43:27 +08003439### **string_replace**: Replaces substring in the given string. [Back to Top](#gn-reference)
Petr Hosekc0744ed2018-08-04 16:13:59 -07003440
3441```
3442 result = string_replace(str, old, new[, max])
3443
3444 Returns a copy of the string str in which the occurrences of old have been
3445 replaced with new, optionally restricting the number of replacements. The
3446 replacement is performed sequentially, so if new contains old, it won't be
3447 replaced.
3448```
3449
3450#### **Example**
3451
3452```
3453 The code:
3454 mystr = "Hello, world!"
3455 print(string_replace(mystr, "world", "GN"))
3456
3457 Will print:
3458 Hello, GN!
3459```
[email protected]449f3e42024-08-01 21:43:27 +08003460### **string_split**: Split string into a list of strings. [Back to Top](#gn-reference)
Keir Mierle6ae63302019-11-08 23:02:18 -08003461
3462```
3463 result = string_split(str[, sep])
3464
3465 Split string into all substrings separated by separator and returns a list
3466 of the substrings between those separators.
3467
3468 If the separator argument is omitted, the split is by any whitespace, and
3469 any leading/trailing whitespace is ignored; similar to Python's str.split().
3470```
3471
3472#### **Examples without a separator (split on whitespace)**:
3473
3474```
3475 string_split("") --> []
3476 string_split("a") --> ["a"]
3477 string_split(" aa bb") --> ["aa", "bb"]
3478```
3479
3480#### **Examples with a separator (split on separators)**:
3481
3482```
3483 string_split("", "|") --> [""]
3484 string_split(" a b ", " ") --> ["", "", "a", "b", "", ""]
3485 string_split("aa+-bb+-c", "+-") --> ["aa", "bb", "c"]
3486```
[email protected]449f3e42024-08-01 21:43:27 +08003487### **template**: Define a template rule. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003488
3489```
3490 A template defines a custom name that acts like a function. It provides a way
3491 to add to the built-in target types.
3492
3493 The template() function is used to declare a template. To invoke the
3494 template, just use the name of the template like any other target type.
3495
3496 Often you will want to declare your template in a special file that other
3497 files will import (see "gn help import") so your template rule can be shared
3498 across build files.
3499```
3500
3501#### **Variables and templates**:
3502
3503```
3504 When you call template() it creates a closure around all variables currently
3505 in scope with the code in the template block. When the template is invoked,
3506 the closure will be executed.
3507
3508 When the template is invoked, the code in the caller is executed and passed
3509 to the template code as an implicit "invoker" variable. The template uses
3510 this to read state out of the invoking code.
3511
3512 One thing explicitly excluded from the closure is the "current directory"
3513 against which relative file names are resolved. The current directory will be
3514 that of the invoking code, since typically that code specifies the file
3515 names. This means all files internal to the template should use absolute
3516 names.
3517
3518 A template will typically forward some or all variables from the invoking
3519 scope to a target that it defines. Often, such variables might be optional.
3520 Use the pattern:
3521
3522 if (defined(invoker.deps)) {
3523 deps = invoker.deps
3524 }
3525
3526 The function forward_variables_from() provides a shortcut to forward one or
3527 more or possibly all variables in this manner:
3528
3529 forward_variables_from(invoker, ["deps", "public_deps"])
3530```
3531
3532#### **Target naming**
3533
3534```
3535 Your template should almost always define a built-in target with the name the
3536 template invoker specified. For example, if you have an IDL template and
3537 somebody does:
3538 idl("foo") {...
3539 you will normally want this to expand to something defining a source_set or
3540 static_library named "foo" (among other things you may need). This way, when
3541 another target specifies a dependency on "foo", the static_library or
3542 source_set will be linked.
3543
3544 It is also important that any other targets your template expands to have
3545 unique names, or you will get collisions.
3546
3547 Access the invoking name in your template via the implicit "target_name"
3548 variable. This should also be the basis for how other targets that a template
3549 expands to ensure uniqueness.
3550
3551 A typical example would be a template that defines an action to generate some
3552 source files, and a source_set to compile that source. Your template would
3553 name the source_set "target_name" because that's what you want external
3554 targets to depend on to link your code. And you would name the action
3555 something like "${target_name}_action" to make it unique. The source set
3556 would have a dependency on the action to make it run.
3557```
3558
3559#### **Overriding builtin targets**
3560
3561```
3562 You can use template to redefine a built-in target in which case your template
3563 takes a precedence over the built-in one. All uses of the target from within
3564 the template definition will refer to the built-in target which makes it
3565 possible to extend the behavior of the built-in target:
3566
3567 template("shared_library") {
3568 shared_library(shlib) {
Julie Hockette2a29402018-07-31 10:11:42 -07003569 forward_variables_from(invoker, "*")
Brett Wilson796ed472018-07-16 15:11:09 -07003570 ...
3571 }
3572 }
3573```
3574
3575#### **Example of defining a template**
3576
3577```
3578 template("my_idl") {
3579 # Be nice and help callers debug problems by checking that the variables
3580 # the template requires are defined. This gives a nice message rather than
3581 # giving the user an error about an undefined variable in the file defining
3582 # the template
3583 #
3584 # You can also use defined() to give default values to variables
3585 # unspecified by the invoker.
3586 assert(defined(invoker.sources),
3587 "Need sources in $target_name listing the idl files.")
3588
3589 # Name of the intermediate target that does the code gen. This must
3590 # incorporate the target name so it's unique across template
3591 # instantiations.
3592 code_gen_target_name = target_name + "_code_gen"
3593
3594 # Intermediate target to convert IDL to C source. Note that the name is
3595 # based on the name the invoker of the template specified. This way, each
3596 # time the template is invoked we get a unique intermediate action name
3597 # (since all target names are in the global scope).
3598 action_foreach(code_gen_target_name) {
3599 # Access the scope defined by the invoker via the implicit "invoker"
3600 # variable.
3601 sources = invoker.sources
3602
3603 # Note that we need an absolute path for our script file name. The
3604 # current directory when executing this code will be that of the invoker
3605 # (this is why we can use the "sources" directly above without having to
3606 # rebase all of the paths). But if we need to reference a script relative
3607 # to the template file, we'll need to use an absolute path instead.
3608 script = "//tools/idl/idl_code_generator.py"
3609
3610 # Tell GN how to expand output names given the sources.
3611 # See "gn help source_expansion" for more.
3612 outputs = [ "$target_gen_dir/{{source_name_part}}.cc",
3613 "$target_gen_dir/{{source_name_part}}.h" ]
3614 }
3615
3616 # Name the source set the same as the template invocation so instancing
3617 # this template produces something that other targets can link to in their
3618 # deps.
3619 source_set(target_name) {
3620 # Generates the list of sources, we get these from the action_foreach
3621 # above.
3622 sources = get_target_outputs(":$code_gen_target_name")
3623
3624 # This target depends on the files produced by the above code gen target.
3625 deps = [ ":$code_gen_target_name" ]
3626 }
3627 }
3628```
3629
3630#### **Example of invoking the resulting template**
3631
3632```
3633 # This calls the template code above, defining target_name to be
3634 # "foo_idl_files" and "invoker" to be the set of stuff defined in the curly
3635 # brackets.
3636 my_idl("foo_idl_files") {
3637 # Goes into the template as "invoker.sources".
3638 sources = [ "foo.idl", "bar.idl" ]
3639 }
3640
3641 # Here is a target that depends on our template.
3642 executable("my_exe") {
3643 # Depend on the name we gave the template call above. Internally, this will
3644 # produce a dependency from executable to the source_set inside the
3645 # template (since it has this name), which will in turn depend on the code
3646 # gen action.
3647 deps = [ ":foo_idl_files" ]
3648 }
3649```
[email protected]449f3e42024-08-01 21:43:27 +08003650### **tool**: Specify arguments to a toolchain tool. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003651
3652#### **Usage**
3653
3654```
3655 tool() {
3656
3657 }
3658```
3659
3660#### **Tool types**
3661
3662```
3663 Compiler tools:
3664 "cc": C compiler
3665 "cxx": C++ compiler
Sylvain Defresne89e64252020-08-07 13:01:06 +02003666 "cxx_module": C++ compiler used for Clang .modulemap files
Brett Wilson796ed472018-07-16 15:11:09 -07003667 "objc": Objective C compiler
3668 "objcxx": Objective C++ compiler
3669 "rc": Resource compiler (Windows .rc files)
3670 "asm": Assembler
Sylvain Defresne89e64252020-08-07 13:01:06 +02003671 "swift": Swift compiler driver
Brett Wilson796ed472018-07-16 15:11:09 -07003672
3673 Linker tools:
3674 "alink": Linker for static libraries (archives)
3675 "solink": Linker for shared libraries
3676 "link": Linker for executables
3677
3678 Other tools:
3679 "stamp": Tool for creating stamp files
3680 "copy": Tool to copy files.
3681 "action": Defaults for actions
3682
3683 Platform specific tools:
3684 "copy_bundle_data": [iOS, macOS] Tool to copy files in a bundle.
3685 "compile_xcassets": [iOS, macOS] Tool to compile asset catalogs.
Julie Hockettce1fa072019-05-07 17:44:37 -07003686
3687 Rust tools:
Petr Hosek7617b592019-10-02 09:52:21 -07003688 "rust_bin": Tool for compiling Rust binaries
3689 "rust_cdylib": Tool for compiling C-compatible dynamic libraries.
3690 "rust_dylib": Tool for compiling Rust dynamic libraries.
3691 "rust_macro": Tool for compiling Rust procedural macros.
3692 "rust_rlib": Tool for compiling Rust libraries.
3693 "rust_staticlib": Tool for compiling Rust static libraries.
Brett Wilson796ed472018-07-16 15:11:09 -07003694```
3695
3696#### **Tool variables**
3697
3698```
3699 command [string with substitutions]
3700 Valid for: all tools except "action" (required)
3701
3702 The command to run.
3703
Joe Armstrong23d22bc2019-06-28 15:31:03 +08003704 command_launcher [string]
3705 Valid for: all tools except "action" (optional)
3706
3707 The prefix with which to launch the command (e.g. the path to a Goma or
3708 CCache compiler launcher).
3709
3710 Note that this prefix will not be included in the compilation database or
3711 IDE files generated from the build.
3712
Brett Wilson796ed472018-07-16 15:11:09 -07003713 default_output_dir [string with substitutions]
3714 Valid for: linker tools
3715
3716 Default directory name for the output file relative to the
3717 root_build_dir. It can contain other substitution patterns. This will
3718 be the default value for the {{output_dir}} expansion (discussed below)
3719 but will be overridden by the "output_dir" variable in a target, if one
3720 is specified.
3721
3722 GN doesn't do anything with this string other than pass it along,
3723 potentially with target-specific overrides. It is the tool's job to use
3724 the expansion so that the files will be in the right place.
3725
3726 default_output_extension [string]
3727 Valid for: linker tools
3728
3729 Extension for the main output of a linkable tool. It includes the
3730 leading dot. This will be the default value for the
3731 {{output_extension}} expansion (discussed below) but will be overridden
3732 by by the "output extension" variable in a target, if one is specified.
3733 Empty string means no extension.
3734
3735 GN doesn't actually do anything with this extension other than pass it
3736 along, potentially with target-specific overrides. One would typically
3737 use the {{output_extension}} value in the "outputs" to read this value.
3738
3739 Example: default_output_extension = ".exe"
3740
3741 depfile [string with substitutions]
3742 Valid for: compiler tools (optional)
3743
3744 If the tool can write ".d" files, this specifies the name of the
3745 resulting file. These files are used to list header file dependencies
3746 (or other implicit input dependencies) that are discovered at build
3747 time. See also "depsformat".
3748
3749 Example: depfile = "{{output}}.d"
3750
3751 depsformat [string]
3752 Valid for: compiler tools (when depfile is specified)
3753
3754 Format for the deps outputs. This is either "gcc" or "msvc". See the
3755 ninja documentation for "deps" for more information.
3756
3757 Example: depsformat = "gcc"
3758
3759 description [string with substitutions, optional]
3760 Valid for: all tools
3761
3762 What to print when the command is run.
3763
3764 Example: description = "Compiling {{source}}"
3765
Julie Hockettce1fa072019-05-07 17:44:37 -07003766 exe_output_extension [string, optional, rust tools only]
3767 rlib_output_extension [string, optional, rust tools only]
3768 dylib_output_extension [string, optional, rust tools only]
3769 cdylib_output_extension [string, optional, rust tools only]
Petr Hosekfe36c7c2019-11-26 14:38:08 -08003770 rust_proc_macro_output_extension [string, optional, rust tools only]
Julie Hockettce1fa072019-05-07 17:44:37 -07003771 Valid for: Rust tools
3772
3773 These specify the default tool output for each of the crate types.
3774 The default is empty for executables, shared, and static libraries and
3775 ".rlib" for rlibs. Note that the Rust compiler complains with an error
3776 if external crates do not take the form `lib.rlib` or
3777 `lib.`, where `` is `.so`,
3778 `.dylib`, or `.dll` as appropriate for the platform.
3779
Brett Wilson796ed472018-07-16 15:11:09 -07003780 lib_switch [string, optional, link tools only]
3781 lib_dir_switch [string, optional, link tools only]
3782 Valid for: Linker tools except "alink"
3783
3784 These strings will be prepended to the libraries and library search
Sylvain Defresnea09ec162020-01-16 12:36:40 +01003785 directories, respectively, because linkers differ on how to specify
3786 them.
3787
Brett Wilson796ed472018-07-16 15:11:09 -07003788 If you specified:
3789 lib_switch = "-l"
3790 lib_dir_switch = "-L"
Sylvain Defresnea09ec162020-01-16 12:36:40 +01003791 then the "{{libs}}" expansion for
3792 [ "freetype", "expat" ]
3793 would be
3794 "-lfreetype -lexpat".
3795
3796 framework_switch [string, optional, link tools only]
Robert Sesekd0a6f072020-05-15 11:21:22 -04003797 weak_framework_switch [string, optional, link tools only]
Sylvain Defresnea09ec162020-01-16 12:36:40 +01003798 framework_dir_switch [string, optional, link tools only]
3799 Valid for: Linker tools
3800
3801 These strings will be prepended to the frameworks and framework search
3802 path directories, respectively, because linkers differ on how to specify
3803 them.
3804
3805 If you specified:
3806 framework_switch = "-framework "
Robert Sesekd0a6f072020-05-15 11:21:22 -04003807 weak_framework_switch = "-weak_framework "
Sylvain Defresnea09ec162020-01-16 12:36:40 +01003808 framework_dir_switch = "-F"
Robert Sesekd0a6f072020-05-15 11:21:22 -04003809 and:
3810 framework_dirs = [ "$root_out_dir" ]
3811 frameworks = [ "UIKit.framework", "Foo.framework" ]
3812 weak_frameworks = [ "MediaPlayer.framework" ]
3813 would be:
3814 "-F. -framework UIKit -framework Foo -weak_framework MediaPlayer"
Brett Wilson796ed472018-07-16 15:11:09 -07003815
Sylvain Defresne89e64252020-08-07 13:01:06 +02003816 swiftmodule_switch [string, optional, link tools only]
3817 Valid for: Linker tools except "alink"
3818
3819 The string will be prependend to the path to the .swiftmodule files
3820 that are embedded in the linker output.
3821
3822 If you specified:
3823 swiftmodule_swift = "-Wl,-add_ast_path,"
3824 then the "{{swiftmodules}}" expansion for
3825 [ "obj/foo/Foo.swiftmodule" ]
3826 would be
3827 "-Wl,-add_ast_path,obj/foo/Foo.swiftmodule"
3828
danakj4fb095d2024-05-30 11:40:51 -04003829 rust_swiftmodule_switch [string, optional, link tools only]
3830 Valid for: Linker tools except "alink"
3831
3832 Like swiftmodule_switch, but for targets built/linked with the Rust
3833 compiler. The string will be prependend to the path to the
3834 .swiftmodule files that are embedded in the linker output.
3835
3836 If you specified:
3837 rust_swiftmodule_swift = "-Clink-arg=-Wl,-add_ast_path,"
3838 then the "{{swiftmodules}}" expansion for
3839 [ "obj/foo/Foo.swiftmodule" ]
3840 would be
3841 "-Clink-arg=-Wl,-add_ast_path,obj/foo/Foo.swiftmodule"
3842
Brett Wilson796ed472018-07-16 15:11:09 -07003843 outputs [list of strings with substitutions]
3844 Valid for: Linker and compiler tools (required)
3845
3846 An array of names for the output files the tool produces. These are
3847 relative to the build output directory. There must always be at least
3848 one output file. There can be more than one output (a linker might
3849 produce a library and an import library, for example).
3850
3851 This array just declares to GN what files the tool will produce. It is
3852 your responsibility to specify the tool command that actually produces
3853 these files.
3854
3855 If you specify more than one output for shared library links, you
3856 should consider setting link_output, depend_output, and
3857 runtime_outputs.
3858
3859 Example for a compiler tool that produces .obj files:
3860 outputs = [
3861 "{{source_out_dir}}/{{source_name_part}}.obj"
3862 ]
3863
3864 Example for a linker tool that produces a .dll and a .lib. The use of
3865 {{target_output_name}}, {{output_extension}} and {{output_dir}} allows
3866 the target to override these values.
3867 outputs = [
Nico Weberad9eab22020-11-15 22:20:28 -05003868 "{{output_dir}}/{{target_output_name}}{{output_extension}}",
Brett Wilson796ed472018-07-16 15:11:09 -07003869 "{{output_dir}}/{{target_output_name}}.lib",
3870 ]
3871
Sylvain Defresne89e64252020-08-07 13:01:06 +02003872 partial_outputs [list of strings with substitutions]
3873 Valid for: "swift" only
3874
3875 An array of names for the partial outputs the tool produces. These
3876 are relative to the build output directory. The expansion will be
3877 evaluated for each file listed in the "sources" of the target.
3878
3879 This is used to deal with whole module optimization, allowing to
3880 list one object file per source file when whole module optimization
3881 is disabled.
3882
Brett Wilson796ed472018-07-16 15:11:09 -07003883 pool [label, optional]
3884 Valid for: all tools (optional)
3885
3886 Label of the pool to use for the tool. Pools are used to limit the
3887 number of tasks that can execute concurrently during the build.
3888
3889 See also "gn help pool".
3890
3891 link_output [string with substitutions]
3892 depend_output [string with substitutions]
Dirk Pranke05eed8f2024-08-06 16:21:07 +00003893 Valid for: "solink" only (optional)
Brett Wilson796ed472018-07-16 15:11:09 -07003894
Dirk Pranke05eed8f2024-08-06 16:21:07 +00003895 These two files specify which of the outputs from the solink tool
3896 should be used for linking and dependency tracking. These should match
3897 entries in the "outputs". If unspecified, the first item in the
3898 "outputs" array will be used for all. See "Separate linking and
3899 dependencies for shared libraries" below for more.
Brett Wilson796ed472018-07-16 15:11:09 -07003900
3901 On Windows, where the tools produce a .dll shared library and a .lib
3902 import library, you will want the first two to be the import library
3903 and the third one to be the .dll file. On Linux, if you're not doing
3904 the separate linking/dependency optimization, all of these should be
3905 the .so output.
3906
3907 output_prefix [string]
3908 Valid for: Linker tools (optional)
3909
3910 Prefix to use for the output name. Defaults to empty. This prefix will
3911 be prepended to the name of the target (or the output_name if one is
3912 manually specified for it) if the prefix is not already there. The
3913 result will show up in the {{output_name}} substitution pattern.
3914
3915 Individual targets can opt-out of the output prefix by setting:
3916 output_prefix_override = true
3917 (see "gn help output_prefix_override").
3918
3919 This is typically used to prepend "lib" to libraries on
3920 Posix systems:
3921 output_prefix = "lib"
3922
3923 precompiled_header_type [string]
3924 Valid for: "cc", "cxx", "objc", "objcxx"
3925
3926 Type of precompiled headers. If undefined or the empty string,
3927 precompiled headers will not be used for this tool. Otherwise use "gcc"
3928 or "msvc".
3929
3930 For precompiled headers to be used for a given target, the target (or a
3931 config applied to it) must also specify a "precompiled_header" and, for
3932 "msvc"-style headers, a "precompiled_source" value. If the type is
3933 "gcc", then both "precompiled_header" and "precompiled_source" must
3934 resolve to the same file, despite the different formats required for
3935 each."
3936
3937 See "gn help precompiled_header" for more.
3938
3939 restat [boolean]
3940 Valid for: all tools (optional, defaults to false)
3941
3942 Requests that Ninja check the file timestamp after this tool has run to
3943 determine if anything changed. Set this if your tool has the ability to
3944 skip writing output if the output file has not changed.
3945
3946 Normally, Ninja will assume that when a tool runs the output be new and
3947 downstream dependents must be rebuild. When this is set to trye, Ninja
3948 can skip rebuilding downstream dependents for input changes that don't
3949 actually affect the output.
3950
3951 Example:
3952 restat = true
3953
3954 rspfile [string with substitutions]
3955 Valid for: all tools except "action" (optional)
3956
3957 Name of the response file. If empty, no response file will be
3958 used. See "rspfile_content".
3959
3960 rspfile_content [string with substitutions]
3961 Valid for: all tools except "action" (required when "rspfile" is used)
3962
3963 The contents to be written to the response file. This may include all
3964 or part of the command to send to the tool which allows you to get
3965 around OS command-line length limits.
3966
3967 This example adds the inputs and libraries to a response file, but
3968 passes the linker flags directly on the command line:
3969 tool("link") {
3970 command = "link -o {{output}} {{ldflags}} @{{output}}.rsp"
3971 rspfile = "{{output}}.rsp"
Adrian Taylorac6cc952020-04-26 20:49:18 -07003972 rspfile_content = "{{inputs}} {{solibs}} {{libs}} {{rlibs}}"
Brett Wilson796ed472018-07-16 15:11:09 -07003973 }
3974
3975 runtime_outputs [string list with substitutions]
3976 Valid for: linker tools
3977
3978 If specified, this list is the subset of the outputs that should be
3979 added to runtime deps (see "gn help runtime_deps"). By default (if
3980 runtime_outputs is empty or unspecified), it will be the link_output.
Adrian Taylor4aa9bdf2021-11-15 19:00:06 -08003981
3982 rust_sysroot
3983 Valid for: Rust tools
3984
3985 A path relative to root_out_dir. This is not used in the build
3986 process, but may be used when generating metadata for rust-analyzer.
3987 (See --export-rust-project). It enables such metadata to include
3988 information about the Rust standard library.
Adrian Taylore3978de2023-05-26 12:07:53 +01003989
3990 dynamic_link_switch
3991 Valid for: Rust tools which link
3992
3993 A switch to be optionally inserted into linker command lines
3994 to indicate that subsequent items may be dynamically linked.
3995 For ld-like linkers, -Clink-arg=-Bdynamic may be a good choice.
3996 This switch is inserted by gn into rustc command lines before
3997 listing any non-Rust dependencies. This may be necessary because
3998 sometimes rustc puts the linker into a mode where it would otherwise
3999 link against static libraries by default. This flag will be
4000 inserted into the {{rustdeps}} variable at the appropriate place;
4001 {{ldflags}} can't be used for the same purpose because the flags
4002 may not be inserted at the desired place in the command line.
Brett Wilson796ed472018-07-16 15:11:09 -07004003```
4004
4005#### **Expansions for tool variables**
4006
4007```
4008 All paths are relative to the root build directory, which is the current
4009 directory for running all tools. These expansions are available to all tools:
4010
4011 {{label}}
4012 The label of the current target. This is typically used in the
4013 "description" field for link tools. The toolchain will be omitted from
4014 the label for targets in the default toolchain, and will be included
4015 for targets in other toolchains.
4016
4017 {{label_name}}
4018 The short name of the label of the target. This is the part after the
4019 colon. For "//foo/bar:baz" this will be "baz". Unlike
4020 {{target_output_name}}, this is not affected by the "output_prefix" in
4021 the tool or the "output_name" set on the target.
4022
Scott Graham501b49a2020-08-05 13:03:37 -07004023 {{label_no_toolchain}}
4024 The label of the current target, never including the toolchain
4025 (otherwise, this is identical to {{label}}). This is used as the module
4026 name when using .modulemap files.
4027
Brett Wilson796ed472018-07-16 15:11:09 -07004028 {{output}}
4029 The relative path and name of the output(s) of the current build step.
4030 If there is more than one output, this will expand to a list of all of
4031 them. Example: "out/base/my_file.o"
4032
4033 {{target_gen_dir}}
4034 {{target_out_dir}}
4035 The directory of the generated file and output directories,
4036 respectively, for the current target. There is no trailing slash. See
4037 also {{output_dir}} for linker tools. Example: "out/base/test"
4038
4039 {{target_output_name}}
4040 The short name of the current target with no path information, or the
4041 value of the "output_name" variable if one is specified in the target.
4042 This will include the "output_prefix" if any. See also {{label_name}}.
4043
4044 Example: "libfoo" for the target named "foo" and an output prefix for
4045 the linker tool of "lib".
4046
4047 Compiler tools have the notion of a single input and a single output, along
4048 with a set of compiler-specific flags. The following expansions are
4049 available:
4050
4051 {{asmflags}}
4052 {{cflags}}
4053 {{cflags_c}}
4054 {{cflags_cc}}
4055 {{cflags_objc}}
4056 {{cflags_objcc}}
4057 {{defines}}
4058 {{include_dirs}}
4059 Strings correspond that to the processed flags/defines/include
4060 directories specified for the target.
4061 Example: "--enable-foo --enable-bar"
4062
4063 Defines will be prefixed by "-D" and include directories will be
4064 prefixed by "-I" (these work with Posix tools as well as Microsoft
4065 ones).
4066
Scott Graham484245b2020-08-11 10:58:50 -07004067 {{module_deps}}
4068 {{module_deps_no_self}}
4069 Strings that correspond to the flags necessary to depend upon the Clang
4070 modules referenced by the current target. The "_no_self" version doesn't
4071 include the module for the current target, and can be used to compile
4072 the pcm itself.
4073
Brett Wilson796ed472018-07-16 15:11:09 -07004074 {{source}}
4075 The relative path and name of the current input file.
4076 Example: "../../base/my_file.cc"
4077
4078 {{source_file_part}}
4079 The file part of the source including the extension (with no directory
4080 information).
4081 Example: "foo.cc"
4082
4083 {{source_name_part}}
4084 The filename part of the source file with no directory or extension.
4085 Example: "foo"
4086
4087 {{source_gen_dir}}
4088 {{source_out_dir}}
4089 The directory in the generated file and output directories,
4090 respectively, for the current input file. If the source file is in the
4091 same directory as the target is declared in, they will will be the same
4092 as the "target" versions above. Example: "gen/base/test"
4093
Julie Hockette2a29402018-07-31 10:11:42 -07004094 Linker tools have multiple inputs and (potentially) multiple outputs. The
Brett Wilson796ed472018-07-16 15:11:09 -07004095 static library tool ("alink") is not considered a linker tool. The following
4096 expansions are available:
4097
4098 {{inputs}}
4099 {{inputs_newline}}
4100 Expands to the inputs to the link step. This will be a list of object
4101 files and static libraries.
4102 Example: "obj/foo.o obj/bar.o obj/somelibrary.a"
4103
4104 The "_newline" version will separate the input files with newlines
4105 instead of spaces. This is useful in response files: some linkers can
4106 take a "-filelist" flag which expects newline separated files, and some
4107 Microsoft tools have a fixed-sized buffer for parsing each line of a
4108 response file.
4109
4110 {{ldflags}}
4111 Expands to the processed set of ldflags and library search paths
4112 specified for the target.
4113 Example: "-m64 -fPIC -pthread -L/usr/local/mylib"
4114
4115 {{libs}}
4116 Expands to the list of system libraries to link to. Each will be
4117 prefixed by the "lib_switch".
4118
Brett Wilson796ed472018-07-16 15:11:09 -07004119 Example: "-lfoo -lbar"
4120
4121 {{output_dir}}
4122 The value of the "output_dir" variable in the target, or the the value
4123 of the "default_output_dir" value in the tool if the target does not
4124 override the output directory. This will be relative to the
4125 root_build_dir and will not end in a slash. Will be "." for output to
4126 the root_build_dir.
4127
4128 This is subtly different than {{target_out_dir}} which is defined by GN
4129 based on the target's path and not overridable. {{output_dir}} is for
4130 the final output, {{target_out_dir}} is generally for object files and
4131 other outputs.
4132
4133 Usually {{output_dir}} would be defined in terms of either
4134 {{target_out_dir}} or {{root_out_dir}}
4135
4136 {{output_extension}}
4137 The value of the "output_extension" variable in the target, or the
4138 value of the "default_output_extension" value in the tool if the target
4139 does not specify an output extension.
4140 Example: ".so"
4141
4142 {{solibs}}
4143 Extra libraries from shared library dependencies not specified in the
4144 {{inputs}}. This is the list of link_output files from shared libraries
Dirk Pranke05eed8f2024-08-06 16:21:07 +00004145 (if the solink tool specifies a "link_output" variable separate from
4146 the "depend_output").
Brett Wilson796ed472018-07-16 15:11:09 -07004147
4148 These should generally be treated the same as libs by your tool.
4149
4150 Example: "libfoo.so libbar.so"
4151
Adrian Taylorac6cc952020-04-26 20:49:18 -07004152 {{rlibs}}
4153 Any Rust .rlibs which need to be linked into a final C++ target.
4154 These should be treated as {{inputs}} except that sometimes
4155 they might have different linker directives applied.
4156
4157 Example: "obj/foo/libfoo.rlib"
4158
Sylvain Defresnea09ec162020-01-16 12:36:40 +01004159 {{frameworks}}
4160 Shared libraries packaged as framework bundle. This is principally
4161 used on Apple's platforms (macOS and iOS). All name must be ending
4162 with ".framework" suffix; the suffix will be stripped when expanding
Robert Sesekd0a6f072020-05-15 11:21:22 -04004163 {{frameworks}} and each item will be preceded by "-framework" or
4164 "-weak_framework".
Sylvain Defresnea09ec162020-01-16 12:36:40 +01004165
Sylvain Defresne89e64252020-08-07 13:01:06 +02004166 {{swiftmodules}}
4167 Swift .swiftmodule files that needs to be embedded into the binary.
4168 This is necessary to correctly link with object generated by the
4169 Swift compiler (the .swiftmodule file cannot be embedded in object
4170 files directly). Those will be prefixed with "swiftmodule_switch"
4171 value.
4172
Brett Wilson796ed472018-07-16 15:11:09 -07004173 The static library ("alink") tool allows {{arflags}} plus the common tool
4174 substitutions.
4175
4176 The copy tool allows the common compiler/linker substitutions, plus
4177 {{source}} which is the source of the copy. The stamp tool allows only the
4178 common tool substitutions.
4179
4180 The copy_bundle_data and compile_xcassets tools only allows the common tool
4181 substitutions. Both tools are required to create iOS/macOS bundles and need
4182 only be defined on those platforms.
4183
4184 The copy_bundle_data tool will be called with one source and needs to copy
4185 (optionally optimizing the data representation) to its output. It may be
4186 called with a directory as input and it needs to be recursively copied.
4187
4188 The compile_xcassets tool will be called with one or more source (each an
4189 asset catalog) that needs to be compiled to a single output. The following
4190 substitutions are available:
4191
4192 {{inputs}}
4193 Expands to the list of .xcassets to use as input to compile the asset
4194 catalog.
4195
4196 {{bundle_product_type}}
4197 Expands to the product_type of the bundle that will contain the
4198 compiled asset catalog. Usually corresponds to the product_type
4199 property of the corresponding create_bundle target.
4200
4201 {{bundle_partial_info_plist}}
4202 Expands to the path to the partial Info.plist generated by the
4203 assets catalog compiler. Usually based on the target_name of
4204 the create_bundle target.
Julie Hockettce1fa072019-05-07 17:44:37 -07004205
Harley Li0a9affb2020-06-03 10:38:42 -04004206 {{xcasset_compiler_flags}}
4207 Expands to the list of flags specified in corresponding
4208 create_bundle target.
4209
Sylvain Defresne06cdcc82024-03-21 13:48:59 +01004210 The inputs for compile_xcassets tool will be found from the bundle_data
4211 dependencies by looking for any file matching "*/*.xcassets/*" pattern.
4212 The "$assets.xcassets" directory will be added as input to the tool.
4213
Sylvain Defresne89e64252020-08-07 13:01:06 +02004214 The Swift tool has multiple input and outputs. It must have exactly one
4215 output of .swiftmodule type, but can have one or more object file outputs,
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01004216 in addition to other type of outputs. The following expansions are available:
Sylvain Defresne89e64252020-08-07 13:01:06 +02004217
4218 {{module_name}}
4219 Expands to the string representing the module name of target under
4220 compilation (see "module_name" variable).
4221
4222 {{module_dirs}}
4223 Expands to the list of -I for the target Swift module search
4224 path computed from target dependencies.
4225
4226 {{swiftflags}}
4227 Expands to the list of strings representing Swift compiler flags.
4228
Julie Hockettce1fa072019-05-07 17:44:37 -07004229 Rust tools have the notion of a single input and a single output, along
4230 with a set of compiler-specific flags. The following expansions are
4231 available:
4232
4233 {{crate_name}}
4234 Expands to the string representing the crate name of target under
4235 compilation.
4236
4237 {{crate_type}}
4238 Expands to the string representing the type of crate for the target
4239 under compilation.
4240
4241 {{externs}}
4242 Expands to the list of --extern flags needed to include addition Rust
4243 libraries in this target. Includes any specified renamed dependencies.
4244
Julie Hockettce1fa072019-05-07 17:44:37 -07004245 {{rustdeps}}
4246 Expands to the list of -Ldependency= strings needed to compile
4247 this target.
4248
4249 {{rustenv}}
4250 Expands to the list of environment variables.
4251
4252 {{rustflags}}
4253 Expands to the list of strings representing Rust compiler flags.
Brett Wilson796ed472018-07-16 15:11:09 -07004254```
4255
4256#### **Separate linking and dependencies for shared libraries**
4257
4258```
4259 Shared libraries are special in that not all changes to them require that
4260 dependent targets be re-linked. If the shared library is changed but no
4261 imports or exports are different, dependent code needn't be relinked, which
4262 can speed up the build.
4263
4264 If your link step can output a list of exports from a shared library and
4265 writes the file only if the new one is different, the timestamp of this file
4266 can be used for triggering re-links, while the actual shared library would be
4267 used for linking.
4268
4269 You will need to specify
4270 restat = true
4271 in the linker tool to make this work, so Ninja will detect if the timestamp
4272 of the dependency file has changed after linking (otherwise it will always
4273 assume that running a command updates the output):
4274
4275 tool("solink") {
4276 command = "..."
4277 outputs = [
4278 "{{output_dir}}/{{target_output_name}}{{output_extension}}",
Nico Weberad9eab22020-11-15 22:20:28 -05004279 "{{output_dir}}/{{target_output_name}}{{output_extension}}.TOC",
Brett Wilson796ed472018-07-16 15:11:09 -07004280 ]
4281 link_output =
4282 "{{output_dir}}/{{target_output_name}}{{output_extension}}"
4283 depend_output =
Nico Weberad9eab22020-11-15 22:20:28 -05004284 "{{output_dir}}/{{target_output_name}}{{output_extension}}.TOC"
Brett Wilson796ed472018-07-16 15:11:09 -07004285 restat = true
4286 }
4287```
4288
4289#### **Example**
4290
4291```
4292 toolchain("my_toolchain") {
4293 # Put these at the top to apply to all tools below.
4294 lib_switch = "-l"
4295 lib_dir_switch = "-L"
4296
4297 tool("cc") {
4298 command = "gcc {{source}} -o {{output}}"
4299 outputs = [ "{{source_out_dir}}/{{source_name_part}}.o" ]
4300 description = "GCC {{source}}"
4301 }
4302 tool("cxx") {
4303 command = "g++ {{source}} -o {{output}}"
4304 outputs = [ "{{source_out_dir}}/{{source_name_part}}.o" ]
4305 description = "G++ {{source}}"
4306 }
4307 };
4308```
[email protected]449f3e42024-08-01 21:43:27 +08004309### **toolchain**: Defines a toolchain. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004310
4311```
4312 A toolchain is a set of commands and build flags used to compile the source
4313 code. The toolchain() function defines these commands.
4314```
4315
4316#### **Toolchain overview**
4317
4318```
4319 You can have more than one toolchain in use at once in a build and a target
4320 can exist simultaneously in multiple toolchains. A build file is executed
4321 once for each toolchain it is referenced in so the GN code can vary all
4322 parameters of each target (or which targets exist) on a per-toolchain basis.
4323
4324 When you have a simple build with only one toolchain, the build config file
4325 is loaded only once at the beginning of the build. It must call
4326 set_default_toolchain() (see "gn help set_default_toolchain") to tell GN the
4327 label of the toolchain definition to use. The "toolchain_args" section of the
4328 toolchain definition is ignored.
4329
4330 When a target has a dependency on a target using different toolchain (see "gn
4331 help labels" for how to specify this), GN will start a build using that
4332 secondary toolchain to resolve the target. GN will load the build config file
4333 with the build arguments overridden as specified in the toolchain_args.
4334 Because the default toolchain is already known, calls to
4335 set_default_toolchain() are ignored.
4336
4337 To load a file in an alternate toolchain, GN does the following:
4338
4339 1. Loads the file with the toolchain definition in it (as determined by the
4340 toolchain label).
4341 2. Re-runs the master build configuration file, applying the arguments
4342 specified by the toolchain_args section of the toolchain definition.
4343 3. Loads the destination build file in the context of the configuration file
4344 in the previous step.
4345
4346 The toolchain configuration is two-way. In the default toolchain (i.e. the
4347 main build target) the configuration flows from the build config file to the
4348 toolchain. The build config file looks at the state of the build (OS type,
4349 CPU architecture, etc.) and decides which toolchain to use (via
4350 set_default_toolchain()). In secondary toolchains, the configuration flows
4351 from the toolchain to the build config file: the "toolchain_args" in the
4352 toolchain definition specifies the arguments to re-invoke the build.
4353```
4354
4355#### **Functions and variables**
4356
4357```
4358 tool()
Julie Hockette2a29402018-07-31 10:11:42 -07004359 The tool() function call specifies the commands to run for a given step. See
4360 "gn help tool".
Brett Wilson796ed472018-07-16 15:11:09 -07004361
Julie Hockette2a29402018-07-31 10:11:42 -07004362 toolchain_args [scope]
Brett Wilson796ed472018-07-16 15:11:09 -07004363 Overrides for build arguments to pass to the toolchain when invoking it.
4364 This is a variable of type "scope" where the variable names correspond to
4365 variables in declare_args() blocks.
4366
4367 When you specify a target using an alternate toolchain, the master build
4368 configuration file is re-interpreted in the context of that toolchain.
4369 toolchain_args allows you to control the arguments passed into this
4370 alternate invocation of the build.
4371
4372 Any default system arguments or arguments passed in via "gn args" will also
4373 be passed to the alternate invocation unless explicitly overridden by
4374 toolchain_args.
4375
4376 The toolchain_args will be ignored when the toolchain being defined is the
4377 default. In this case, it's expected you want the default argument values.
4378
4379 See also "gn help buildargs" for an overview of these arguments.
4380
Julie Hockette2a29402018-07-31 10:11:42 -07004381 propagates_configs [boolean, default=false]
4382 Determines whether public_configs and all_dependent_configs in this
4383 toolchain propagate to targets in other toolchains.
4384
4385 When false (the default), this toolchain will not propagate any configs to
4386 targets in other toolchains that depend on it targets inside this
4387 toolchain. This matches the most common usage of toolchains where they
4388 represent different architectures or compilers and the settings that apply
4389 to one won't necessarily apply to others.
4390
4391 When true, configs (public and all-dependent) will cross the boundary out
4392 of this toolchain as if the toolchain boundary wasn't there. This only
4393 affects one direction of dependencies: a toolchain can't control whether
4394 it accepts such configs, only whether it pushes them. The build is
4395 responsible for ensuring that any external targets depending on targets in
4396 this toolchain are compatible with the compiler flags, etc. that may be
4397 propagated.
4398
4399 deps [string list]
Brett Wilson796ed472018-07-16 15:11:09 -07004400 Dependencies of this toolchain. These dependencies will be resolved before
4401 any target in the toolchain is compiled. To avoid circular dependencies
4402 these must be targets defined in another toolchain.
4403
4404 This is expressed as a list of targets, and generally these targets will
4405 always specify a toolchain:
4406 deps = [ "//foo/bar:baz(//build/toolchain:bootstrap)" ]
4407
4408 This concept is somewhat inefficient to express in Ninja (it requires a lot
4409 of duplicate of rules) so should only be used when absolutely necessary.
4410```
4411
4412#### **Example of defining a toolchain**
4413
4414```
4415 toolchain("32") {
4416 tool("cc") {
4417 command = "gcc {{source}}"
4418 ...
4419 }
4420
4421 toolchain_args = {
4422 use_doom_melon = true # Doom melon always required for 32-bit builds.
4423 current_cpu = "x86"
4424 }
4425 }
4426
4427 toolchain("64") {
4428 tool("cc") {
4429 command = "gcc {{source}}"
4430 ...
4431 }
4432
4433 toolchain_args = {
4434 # use_doom_melon is not overridden here, it will take the default.
4435 current_cpu = "x64"
4436 }
4437 }
4438```
4439
4440#### **Example of cross-toolchain dependencies**
4441
4442```
4443 If a 64-bit target wants to depend on a 32-bit binary, it would specify a
4444 dependency using data_deps (data deps are like deps that are only needed at
4445 runtime and aren't linked, since you can't link a 32-bit and a 64-bit
4446 library).
4447
4448 executable("my_program") {
4449 ...
4450 if (target_cpu == "x64") {
4451 # The 64-bit build needs this 32-bit helper.
4452 data_deps = [ ":helper(//toolchains:32)" ]
4453 }
4454 }
4455
4456 if (target_cpu == "x86") {
4457 # Our helper library is only compiled in 32-bits.
4458 shared_library("helper") {
4459 ...
4460 }
4461 }
4462```
[email protected]449f3e42024-08-01 21:43:27 +08004463### **write_file**: Write a file to disk. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004464
4465```
Julie Hockett09171292018-07-31 14:35:10 -07004466 write_file(filename, data, output_conversion = "")
Brett Wilson796ed472018-07-16 15:11:09 -07004467
4468 If data is a list, the list will be written one-item-per-line with no quoting
4469 or brackets.
4470
4471 If the file exists and the contents are identical to that being written, the
4472 file will not be updated. This will prevent unnecessary rebuilds of targets
4473 that depend on this file.
4474
4475 One use for write_file is to write a list of inputs to an script that might
4476 be too long for the command line. However, it is preferable to use response
4477 files for this purpose. See "gn help response_file_contents".
Brett Wilson796ed472018-07-16 15:11:09 -07004478```
4479
4480#### **Arguments**
4481
4482```
4483 filename
4484 Filename to write. This must be within the output directory.
4485
4486 data
4487 The list or string to write.
Julie Hockett09171292018-07-31 14:35:10 -07004488
4489 output_conversion
Sylvain Defresne72d5a6e2021-06-15 17:01:32 +02004490 Controls how the output is written. See `gn help io_conversion`.
Brett Wilson796ed472018-07-16 15:11:09 -07004491```
4492## Built-in predefined variables
4493
[email protected]449f3e42024-08-01 21:43:27 +08004494### **current_cpu**: The processor architecture of the current toolchain. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004495
4496```
4497 The build configuration usually sets this value based on the value of
4498 "host_cpu" (see "gn help host_cpu") and then threads this through the
4499 toolchain definitions to ensure that it always reflects the appropriate
4500 value.
4501
Julie Hockette2a29402018-07-31 10:11:42 -07004502 This value is not used internally by GN for any purpose. It is set to the
Brett Wilson796ed472018-07-16 15:11:09 -07004503 empty string ("") by default but is declared so that it can be overridden on
4504 the command line if so desired.
4505
4506 See "gn help target_cpu" for a list of common values returned.
4507```
[email protected]449f3e42024-08-01 21:43:27 +08004508### **current_os**: The operating system of the current toolchain. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004509
4510```
4511 The build configuration usually sets this value based on the value of
4512 "target_os" (see "gn help target_os"), and then threads this through the
4513 toolchain definitions to ensure that it always reflects the appropriate
4514 value.
4515
Julie Hockette2a29402018-07-31 10:11:42 -07004516 This value is not used internally by GN for any purpose. It is set to the
Brett Wilson796ed472018-07-16 15:11:09 -07004517 empty string ("") by default but is declared so that it can be overridden on
4518 the command line if so desired.
4519
4520 See "gn help target_os" for a list of common values returned.
4521```
[email protected]449f3e42024-08-01 21:43:27 +08004522### **current_toolchain**: Label of the current toolchain. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004523
4524```
4525 A fully-qualified label representing the current toolchain. You can use this
4526 to make toolchain-related decisions in the build. See also
4527 "default_toolchain".
4528```
4529
4530#### **Example**
4531
4532```
4533 if (current_toolchain == "//build:64_bit_toolchain") {
4534 executable("output_thats_64_bit_only") {
4535 ...
4536```
[email protected]449f3e42024-08-01 21:43:27 +08004537### **default_toolchain**: [string] Label of the default toolchain. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004538
4539```
4540 A fully-qualified label representing the default toolchain, which may not
4541 necessarily be the current one (see "current_toolchain").
4542```
[email protected]449f3e42024-08-01 21:43:27 +08004543### **gn_version**: [number] The version of gn. [Back to Top](#gn-reference)
James Robinson61377e32020-02-13 15:20:07 -08004544
4545```
4546 Corresponds to the number printed by `gn --version`.
4547```
4548
4549#### **Example**
4550
4551```
4552 assert(gn_version >= 1700, "need GN version 1700 for the frobulate feature")
4553```
[email protected]449f3e42024-08-01 21:43:27 +08004554### **host_cpu**: The processor architecture that GN is running on. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004555
4556```
4557 This is value is exposed so that cross-compile toolchains can access the host
4558 architecture when needed.
4559
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01004560 The value should generally be considered read-only, but it can be overridden
Brett Wilson796ed472018-07-16 15:11:09 -07004561 in order to handle unusual cases where there might be multiple plausible
4562 values for the host architecture (e.g., if you can do either 32-bit or 64-bit
4563 builds). The value is not used internally by GN for any purpose.
4564```
4565
4566#### **Some possible values**
4567
4568```
4569 - "x64"
4570 - "x86"
4571```
[email protected]449f3e42024-08-01 21:43:27 +08004572### **host_os**: [string] The operating system that GN is running on. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004573
4574```
4575 This value is exposed so that cross-compiles can access the host build
4576 system's settings.
4577
4578 This value should generally be treated as read-only. It, however, is not used
4579 internally by GN for any purpose.
4580```
4581
4582#### **Some possible values**
4583
4584```
4585 - "linux"
4586 - "mac"
4587 - "win"
4588```
[email protected]449f3e42024-08-01 21:43:27 +08004589### **invoker**: [string] The invoking scope inside a template. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004590
4591```
4592 Inside a template invocation, this variable refers to the scope of the
4593 invoker of the template. Outside of template invocations, this variable is
4594 undefined.
4595
4596 All of the variables defined inside the template invocation are accessible as
4597 members of the "invoker" scope. This is the way that templates read values
4598 set by the callers.
4599
4600 This is often used with "defined" to see if a value is set on the invoking
4601 scope.
4602
4603 See "gn help template" for more examples.
4604```
4605
4606#### **Example**
4607
4608```
4609 template("my_template") {
4610 print(invoker.sources) # Prints [ "a.cc", "b.cc" ]
4611 print(defined(invoker.foo)) # Prints false.
4612 print(defined(invoker.bar)) # Prints true.
4613 }
4614
4615 my_template("doom_melon") {
4616 sources = [ "a.cc", "b.cc" ]
4617 bar = 123
4618 }
4619```
[email protected]449f3e42024-08-01 21:43:27 +08004620### **python_path**: Absolute path of Python. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004621
4622```
4623 Normally used in toolchain definitions if running some command requires
4624 Python. You will normally not need this when invoking scripts since GN
4625 automatically finds it for you.
4626```
[email protected]449f3e42024-08-01 21:43:27 +08004627### **root_build_dir**: [string] Directory where build commands are run. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004628
4629```
4630 This is the root build output directory which will be the current directory
4631 when executing all compilers and scripts.
4632
4633 Most often this is used with rebase_path (see "gn help rebase_path") to
4634 convert arguments to be relative to a script's current directory.
4635```
[email protected]449f3e42024-08-01 21:43:27 +08004636### **root_gen_dir**: Directory for the toolchain's generated files. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004637
4638```
4639 Absolute path to the root of the generated output directory tree for the
4640 current toolchain. An example would be "//out/Debug/gen" for the default
4641 toolchain, or "//out/Debug/arm/gen" for the "arm" toolchain.
4642
4643 This is primarily useful for setting up include paths for generated files. If
4644 you are passing this to a script, you will want to pass it through
4645 rebase_path() (see "gn help rebase_path") to convert it to be relative to the
4646 build directory.
4647
4648 See also "target_gen_dir" which is usually a better location for generated
4649 files. It will be inside the root generated dir.
4650```
[email protected]449f3e42024-08-01 21:43:27 +08004651### **root_out_dir**: [string] Root directory for toolchain output files. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004652
4653```
4654 Absolute path to the root of the output directory tree for the current
4655 toolchain. It will not have a trailing slash.
4656
4657 For the default toolchain this will be the same as the root_build_dir. An
4658 example would be "//out/Debug" for the default toolchain, or
4659 "//out/Debug/arm" for the "arm" toolchain.
4660
4661 This is primarily useful for setting up script calls. If you are passing this
4662 to a script, you will want to pass it through rebase_path() (see "gn help
4663 rebase_path") to convert it to be relative to the build directory.
4664
4665 See also "target_out_dir" which is usually a better location for output
4666 files. It will be inside the root output dir.
4667```
4668
4669#### **Example**
4670
4671```
4672 action("myscript") {
4673 # Pass the output dir to the script.
4674 args = [ "-o", rebase_path(root_out_dir, root_build_dir) ]
4675 }
4676```
[email protected]449f3e42024-08-01 21:43:27 +08004677### **target_cpu**: The desired cpu architecture for the build. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004678
4679```
4680 This value should be used to indicate the desired architecture for the
4681 primary objects of the build. It will match the cpu architecture of the
4682 default toolchain, but not necessarily the current toolchain.
4683
4684 In many cases, this is the same as "host_cpu", but in the case of
4685 cross-compiles, this can be set to something different. This value is
4686 different from "current_cpu" in that it does not change based on the current
4687 toolchain. When writing rules, "current_cpu" should be used rather than
4688 "target_cpu" most of the time.
4689
4690 This value is not used internally by GN for any purpose, so it may be set to
4691 whatever value is needed for the build. GN defaults this value to the empty
4692 string ("") and the configuration files should set it to an appropriate value
4693 (e.g., setting it to the value of "host_cpu") if it is not overridden on the
4694 command line or in the args.gn file.
4695```
4696
4697#### **Possible values**
4698
4699```
4700 - "x86"
4701 - "x64"
4702 - "arm"
4703 - "arm64"
4704 - "mipsel"
Tyler Mandry4a648092022-02-15 19:47:09 +00004705 - "mips64el"
4706 - "s390x"
4707 - "ppc64"
4708 - "riscv32"
4709 - "riscv64"
4710 - "e2k"
4711 - "loong64"
Brett Wilson796ed472018-07-16 15:11:09 -07004712```
[email protected]449f3e42024-08-01 21:43:27 +08004713### **target_gen_dir**: Directory for a target's generated files. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004714
4715```
4716 Absolute path to the target's generated file directory. This will be the
4717 "root_gen_dir" followed by the relative path to the current build file. If
4718 your file is in "//tools/doom_melon" then target_gen_dir would be
4719 "//out/Debug/gen/tools/doom_melon". It will not have a trailing slash.
4720
4721 This is primarily useful for setting up include paths for generated files. If
4722 you are passing this to a script, you will want to pass it through
4723 rebase_path() (see "gn help rebase_path") to convert it to be relative to the
4724 build directory.
4725
4726 See also "gn help root_gen_dir".
4727```
4728
4729#### **Example**
4730
4731```
4732 action("myscript") {
4733 # Pass the generated output dir to the script.
Nico Weberad9eab22020-11-15 22:20:28 -05004734 args = [ "-o", rebase_path(target_gen_dir, root_build_dir) ]
Brett Wilson796ed472018-07-16 15:11:09 -07004735 }
4736```
[email protected]449f3e42024-08-01 21:43:27 +08004737### **target_name**: [string] The name of the current target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004738
4739```
4740 Inside a target or template invocation, this variable refers to the name
4741 given to the target or template invocation. Outside of these, this variable
4742 is undefined.
4743
4744 This is most often used in template definitions to name targets defined in
4745 the template based on the name of the invocation. This is necessary both to
4746 ensure generated targets have unique names and to generate a target with the
4747 exact name of the invocation that other targets can depend on.
4748
4749 Be aware that this value will always reflect the innermost scope. So when
4750 defining a target inside a template, target_name will refer to the target
4751 rather than the template invocation. To get the name of the template
4752 invocation in this case, you should save target_name to a temporary variable
4753 outside of any target definitions.
4754
4755 See "gn help template" for more examples.
4756```
4757
4758#### **Example**
4759
4760```
4761 executable("doom_melon") {
4762 print(target_name) # Prints "doom_melon".
4763 }
4764
4765 template("my_template") {
4766 print(target_name) # Prints "space_ray" when invoked below.
4767
4768 executable(target_name + "_impl") {
4769 print(target_name) # Prints "space_ray_impl".
4770 }
4771 }
4772
4773 my_template("space_ray") {
4774 }
4775```
[email protected]449f3e42024-08-01 21:43:27 +08004776### **target_os**: The desired operating system for the build. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004777
4778```
4779 This value should be used to indicate the desired operating system for the
4780 primary object(s) of the build. It will match the OS of the default
4781 toolchain.
4782
4783 In many cases, this is the same as "host_os", but in the case of
4784 cross-compiles, it may be different. This variable differs from "current_os"
4785 in that it can be referenced from inside any toolchain and will always return
4786 the initial value.
4787
4788 This should be set to the most specific value possible. So, "android" or
4789 "chromeos" should be used instead of "linux" where applicable, even though
4790 Android and ChromeOS are both Linux variants. This can mean that one needs to
4791 write
4792
4793 if (target_os == "android" || target_os == "linux") {
4794 # ...
4795 }
4796
4797 and so forth.
4798
4799 This value is not used internally by GN for any purpose, so it may be set to
4800 whatever value is needed for the build. GN defaults this value to the empty
4801 string ("") and the configuration files should set it to an appropriate value
4802 (e.g., setting it to the value of "host_os") if it is not set via the command
4803 line or in the args.gn file.
4804```
4805
4806#### **Possible values**
4807
4808```
4809 - "android"
4810 - "chromeos"
4811 - "ios"
4812 - "linux"
4813 - "nacl"
4814 - "mac"
4815 - "win"
4816```
[email protected]449f3e42024-08-01 21:43:27 +08004817### **target_out_dir**: [string] Directory for target output files. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004818
4819```
4820 Absolute path to the target's generated file directory. If your current
4821 target is in "//tools/doom_melon" then this value might be
4822 "//out/Debug/obj/tools/doom_melon". It will not have a trailing slash.
4823
4824 This is primarily useful for setting up arguments for calling scripts. If you
4825 are passing this to a script, you will want to pass it through rebase_path()
4826 (see "gn help rebase_path") to convert it to be relative to the build
4827 directory.
4828
4829 See also "gn help root_out_dir".
4830```
4831
4832#### **Example**
4833
4834```
4835 action("myscript") {
4836 # Pass the output dir to the script.
Nico Weberad9eab22020-11-15 22:20:28 -05004837 args = [ "-o", rebase_path(target_out_dir, root_build_dir) ]
Brett Wilson796ed472018-07-16 15:11:09 -07004838 }
4839```
4840## Variables you set in targets
4841
[email protected]449f3e42024-08-01 21:43:27 +08004842### **aliased_deps**: [scope] Set of crate-dependency pairs. [Back to Top](#gn-reference)
Julie Hockettce1fa072019-05-07 17:44:37 -07004843
4844```
4845 Valid for `rust_library` targets and `executable`, `static_library`, and
4846 `shared_library` targets that contain Rust sources.
4847
4848 A scope, each key indicating the renamed crate and the corresponding value
4849 specifying the label of the dependency producing the relevant binary.
4850
4851 All dependencies listed in this field *must* be listed as deps of the target.
4852
4853 executable("foo") {
4854 sources = [ "main.rs" ]
4855 deps = [ "//bar" ]
4856 }
4857
4858 This target would compile the `foo` crate with the following `extern` flag:
4859 `rustc ...command... --extern bar=/obj/bar`
4860
4861 executable("foo") {
4862 sources = [ "main.rs" ]
4863 deps = [ ":bar" ]
4864 aliased_deps = {
4865 bar_renamed = ":bar"
4866 }
4867 }
4868
4869 With the addition of `aliased_deps`, above target would instead compile with:
4870 `rustc ...command... --extern bar_renamed=/obj/bar`
4871```
[email protected]449f3e42024-08-01 21:43:27 +08004872### **all_dependent_configs**: Configs to be forced on dependents. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004873
4874```
4875 A list of config labels.
4876
4877 All targets depending on this one, and recursively, all targets depending on
4878 those, will have the configs listed in this variable added to them. These
4879 configs will also apply to the current target.
4880
4881 This addition happens in a second phase once a target and all of its
4882 dependencies have been resolved. Therefore, a target will not see these
4883 force-added configs in their "configs" variable while the script is running,
4884 and they can not be removed. As a result, this capability should generally
4885 only be used to add defines and include directories necessary to compile a
4886 target's headers.
4887
4888 See also "public_configs".
4889```
4890
4891#### **Ordering of flags and values**
4892
4893```
4894 1. Those set on the current target (not in a config).
4895 2. Those set on the "configs" on the target in order that the
4896 configs appear in the list.
4897 3. Those set on the "all_dependent_configs" on the target in order
4898 that the configs appear in the list.
4899 4. Those set on the "public_configs" on the target in order that
4900 those configs appear in the list.
4901 5. all_dependent_configs pulled from dependencies, in the order of
4902 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01004903 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07004904 6. public_configs pulled from dependencies, in the order of the
4905 "deps" list. If a dependency is public, they will be applied
4906 recursively.
4907```
[email protected]449f3e42024-08-01 21:43:27 +08004908### **allow_circular_includes_from**: Permit includes from deps. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004909
4910```
4911 A list of target labels. Must be a subset of the target's "deps". These
4912 targets will be permitted to include headers from the current target despite
4913 the dependency going in the opposite direction.
4914
4915 When you use this, both targets must be included in a final binary for it to
4916 link. To keep linker errors from happening, it is good practice to have all
4917 external dependencies depend only on one of the two targets, and to set the
4918 visibility on the other to enforce this. Thus the targets will always be
4919 linked together in any output.
4920```
4921
4922#### **Details**
4923
4924```
4925 Normally, for a file in target A to include a file from target B, A must list
4926 B as a dependency. This invariant is enforced by the "gn check" command (and
4927 the --check flag to "gn gen" -- see "gn help check").
4928
4929 Sometimes, two targets might be the same unit for linking purposes (two
4930 source sets or static libraries that would always be linked together in a
4931 final executable or shared library) and they each include headers from the
4932 other: you want A to be able to include B's headers, and B to include A's
4933 headers. This is not an ideal situation but is sometimes unavoidable.
4934
4935 This list, if specified, lists which of the dependencies of the current
4936 target can include header files from the current target. That is, if A
4937 depends on B, B can only include headers from A if it is in A's
4938 allow_circular_includes_from list. Normally includes must follow the
4939 direction of dependencies, this flag allows them to go in the opposite
4940 direction.
4941```
4942
4943#### **Danger**
4944
4945```
4946 In the above example, A's headers are likely to include headers from A's
4947 dependencies. Those dependencies may have public_configs that apply flags,
4948 defines, and include paths that make those headers work properly.
4949
4950 With allow_circular_includes_from, B can include A's headers, and
4951 transitively from A's dependencies, without having the dependencies that
4952 would bring in the public_configs those headers need. The result may be
4953 errors or inconsistent builds.
4954
4955 So when you use allow_circular_includes_from, make sure that any compiler
4956 settings, flags, and include directories are the same between both targets
4957 (consider putting such things in a shared config they can both reference).
4958 Make sure the dependencies are also the same (you might consider a group to
4959 collect such dependencies they both depend on).
4960```
4961
4962#### **Example**
4963
4964```
4965 source_set("a") {
4966 deps = [ ":b", ":a_b_shared_deps" ]
4967 allow_circular_includes_from = [ ":b" ]
4968 ...
4969 }
4970
4971 source_set("b") {
4972 deps = [ ":a_b_shared_deps" ]
4973 # Sources here can include headers from a despite lack of deps.
4974 ...
4975 }
4976
4977 group("a_b_shared_deps") {
4978 public_deps = [ ":c" ]
4979 }
4980```
[email protected]449f3e42024-08-01 21:43:27 +08004981### **arflags**: Arguments passed to static_library archiver. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004982
4983```
4984 A list of flags passed to the archive/lib command that creates static
4985 libraries.
4986
4987 arflags are NOT pushed to dependents, so applying arflags to source sets or
4988 any other target type will be a no-op. As with ldflags, you could put the
4989 arflags in a config and set that as a public or "all dependent" config, but
4990 that will likely not be what you want. If you have a chain of static
4991 libraries dependent on each other, this can cause the flags to propagate up
4992 to other static libraries. Due to the nature of how arflags are typically
4993 used, you will normally want to apply them directly on static_library targets
4994 themselves.
4995```
4996
4997#### **Ordering of flags and values**
4998
4999```
5000 1. Those set on the current target (not in a config).
5001 2. Those set on the "configs" on the target in order that the
5002 configs appear in the list.
5003 3. Those set on the "all_dependent_configs" on the target in order
5004 that the configs appear in the list.
5005 4. Those set on the "public_configs" on the target in order that
5006 those configs appear in the list.
5007 5. all_dependent_configs pulled from dependencies, in the order of
5008 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005009 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005010 6. public_configs pulled from dependencies, in the order of the
5011 "deps" list. If a dependency is public, they will be applied
5012 recursively.
5013```
[email protected]449f3e42024-08-01 21:43:27 +08005014### **args**: (target variable) Arguments passed to an action. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005015
5016```
5017 For action and action_foreach targets, args is the list of arguments to pass
5018 to the script. Typically you would use source expansion (see "gn help
5019 source_expansion") to insert the source file names.
5020
Adrian Taylorc0d4f8b2022-03-25 15:05:57 -07005021 Args can also expand the substitution patterns corresponding to config
5022 variables in the same way that compiler tools (see "gn help tool") do. These
5023 allow actions that run compiler or compiler-like tools to access the results
5024 of propagating configs through the build graph. For example:
5025
5026 args = [ "{{defines}}", "{{include_dirs}}", "{{rustenv}}", "--input-file",
5027 "{{source}}" ]
5028
Brett Wilson796ed472018-07-16 15:11:09 -07005029 See also "gn help action" and "gn help action_foreach".
5030```
[email protected]449f3e42024-08-01 21:43:27 +08005031### **asmflags**: Flags passed to the assembler. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005032
5033```
5034 A list of strings.
5035
5036 "asmflags" are passed to any invocation of a tool that takes an .asm or .S
5037 file as input.
5038```
5039
5040#### **Ordering of flags and values**
5041
5042```
5043 1. Those set on the current target (not in a config).
5044 2. Those set on the "configs" on the target in order that the
5045 configs appear in the list.
5046 3. Those set on the "all_dependent_configs" on the target in order
5047 that the configs appear in the list.
5048 4. Those set on the "public_configs" on the target in order that
5049 those configs appear in the list.
5050 5. all_dependent_configs pulled from dependencies, in the order of
5051 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005052 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005053 6. public_configs pulled from dependencies, in the order of the
5054 "deps" list. If a dependency is public, they will be applied
5055 recursively.
5056```
[email protected]449f3e42024-08-01 21:43:27 +08005057### **assert_no_deps**: Ensure no deps on these targets. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005058
5059```
5060 A list of label patterns.
5061
5062 This list is a list of patterns that must not match any of the transitive
5063 dependencies of the target. These include all public, private, and data
5064 dependencies, and cross shared library boundaries. This allows you to express
5065 that undesirable code isn't accidentally added to downstream dependencies in
5066 a way that might otherwise be difficult to notice.
5067
5068 Checking does not cross executable boundaries. If a target depends on an
5069 executable, it's assumed that the executable is a tool that is producing part
5070 of the build rather than something that is linked and distributed. This
5071 allows assert_no_deps to express what is distributed in the final target
5072 rather than depend on the internal build steps (which may include
5073 non-distributable code).
5074
5075 See "gn help label_pattern" for the format of the entries in the list. These
5076 patterns allow blacklisting individual targets or whole directory
5077 hierarchies.
5078
5079 Sometimes it is desirable to enforce that many targets have no dependencies
5080 on a target or set of targets. One efficient way to express this is to create
5081 a group with the assert_no_deps rule on it, and make that group depend on all
5082 targets you want to apply that assertion to.
5083```
5084
5085#### **Example**
5086
5087```
5088 executable("doom_melon") {
5089 deps = [ "//foo:bar" ]
5090 ...
5091 assert_no_deps = [
5092 "//evil/*", # Don't link any code from the evil directory.
5093 "//foo:test_support", # This target is also disallowed.
5094 ]
5095 }
5096```
[email protected]449f3e42024-08-01 21:43:27 +08005097### **bridge_header**: [string] Path to C/Objective-C compatibility header. [Back to Top](#gn-reference)
Sylvain Defresne89e64252020-08-07 13:01:06 +02005098
5099```
5100 Valid for binary targets that contain Swift sources.
5101
5102 Path to an header that includes C/Objective-C functions and types that
5103 needs to be made available to the Swift module.
5104```
[email protected]449f3e42024-08-01 21:43:27 +08005105### **bundle_contents_dir**: Expansion of {{bundle_contents_dir}} in [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005106```
5107 create_bundle.
5108
5109 A string corresponding to a path in $root_build_dir.
5110
5111 This string is used by the "create_bundle" target to expand the
5112 {{bundle_contents_dir}} of the "bundle_data" target it depends on. This must
5113 correspond to a path under "bundle_root_dir".
5114
5115 See "gn help bundle_root_dir" for examples.
5116```
[email protected]449f3e42024-08-01 21:43:27 +08005117### **bundle_deps_filter**: [label list] A list of labels that are filtered out. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005118
5119```
5120 A list of target labels.
5121
5122 This list contains target label patterns that should be filtered out when
5123 creating the bundle. Any target matching one of those label will be removed
5124 from the dependencies of the create_bundle target.
5125
5126 This is mostly useful when creating application extension bundle as the
5127 application extension has access to runtime resources from the application
5128 bundle and thus do not require a second copy.
5129
5130 See "gn help create_bundle" for more information.
5131```
5132
5133#### **Example**
5134
5135```
5136 create_bundle("today_extension") {
5137 deps = [
5138 "//base"
5139 ]
5140 bundle_root_dir = "$root_out_dir/today_extension.appex"
5141 bundle_deps_filter = [
5142 # The extension uses //base but does not use any function calling into
5143 # third_party/icu and thus does not need the icudtl.dat file.
5144 "//third_party/icu:icudata",
5145 ]
5146 }
5147```
[email protected]449f3e42024-08-01 21:43:27 +08005148### **bundle_executable_dir** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005149
Joe Armstrongb199e542019-03-21 09:40:08 +08005150```
Sylvain Defresned46f92f2019-04-03 16:14:29 +02005151 bundle_executable_dir: Expansion of {{bundle_executable_dir}} in
5152 create_bundle.
5153
Brett Wilson796ed472018-07-16 15:11:09 -07005154 A string corresponding to a path in $root_build_dir.
5155
5156 This string is used by the "create_bundle" target to expand the
5157 {{bundle_executable_dir}} of the "bundle_data" target it depends on. This
5158 must correspond to a path under "bundle_root_dir".
5159
5160 See "gn help bundle_root_dir" for examples.
5161```
[email protected]449f3e42024-08-01 21:43:27 +08005162### **bundle_resources_dir** [Back to Top](#gn-reference)
Joe Armstrongb199e542019-03-21 09:40:08 +08005163
Brett Wilson796ed472018-07-16 15:11:09 -07005164```
Sylvain Defresned46f92f2019-04-03 16:14:29 +02005165 bundle_resources_dir: Expansion of {{bundle_resources_dir}} in
5166 create_bundle.
Brett Wilson796ed472018-07-16 15:11:09 -07005167
5168 A string corresponding to a path in $root_build_dir.
5169
5170 This string is used by the "create_bundle" target to expand the
5171 {{bundle_resources_dir}} of the "bundle_data" target it depends on. This must
5172 correspond to a path under "bundle_root_dir".
5173
5174 See "gn help bundle_root_dir" for examples.
5175```
[email protected]449f3e42024-08-01 21:43:27 +08005176### **bundle_root_dir**: Expansion of {{bundle_root_dir}} in create_bundle. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005177
5178```
5179 A string corresponding to a path in root_build_dir.
5180
5181 This string is used by the "create_bundle" target to expand the
5182 {{bundle_root_dir}} of the "bundle_data" target it depends on. This must
5183 correspond to a path under root_build_dir.
5184```
5185
5186#### **Example**
5187
5188```
5189 bundle_data("info_plist") {
5190 sources = [ "Info.plist" ]
5191 outputs = [ "{{bundle_contents_dir}}/Info.plist" ]
5192 }
5193
5194 create_bundle("doom_melon.app") {
5195 deps = [ ":info_plist" ]
5196 bundle_root_dir = "${root_build_dir}/doom_melon.app"
5197 bundle_contents_dir = "${bundle_root_dir}/Contents"
5198 bundle_resources_dir = "${bundle_contents_dir}/Resources"
5199 bundle_executable_dir = "${bundle_contents_dir}/MacOS"
Brett Wilson796ed472018-07-16 15:11:09 -07005200 }
5201```
[email protected]449f3e42024-08-01 21:43:27 +08005202### **cflags***: Flags passed to the C compiler. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005203
5204```
5205 A list of strings.
5206
5207 "cflags" are passed to all invocations of the C, C++, Objective C, and
5208 Objective C++ compilers.
5209
5210 To target one of these variants individually, use "cflags_c", "cflags_cc",
5211 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5212 versions of cflags* will be appended on the compiler command line after
5213 "cflags".
5214
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005215 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5216 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005217```
5218
5219#### **Ordering of flags and values**
5220
5221```
5222 1. Those set on the current target (not in a config).
5223 2. Those set on the "configs" on the target in order that the
5224 configs appear in the list.
5225 3. Those set on the "all_dependent_configs" on the target in order
5226 that the configs appear in the list.
5227 4. Those set on the "public_configs" on the target in order that
5228 those configs appear in the list.
5229 5. all_dependent_configs pulled from dependencies, in the order of
5230 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005231 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005232 6. public_configs pulled from dependencies, in the order of the
5233 "deps" list. If a dependency is public, they will be applied
5234 recursively.
5235```
[email protected]449f3e42024-08-01 21:43:27 +08005236### **cflags***: Flags passed to the C compiler. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005237
5238```
5239 A list of strings.
5240
5241 "cflags" are passed to all invocations of the C, C++, Objective C, and
5242 Objective C++ compilers.
5243
5244 To target one of these variants individually, use "cflags_c", "cflags_cc",
5245 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5246 versions of cflags* will be appended on the compiler command line after
5247 "cflags".
5248
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005249 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5250 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005251```
5252
5253#### **Ordering of flags and values**
5254
5255```
5256 1. Those set on the current target (not in a config).
5257 2. Those set on the "configs" on the target in order that the
5258 configs appear in the list.
5259 3. Those set on the "all_dependent_configs" on the target in order
5260 that the configs appear in the list.
5261 4. Those set on the "public_configs" on the target in order that
5262 those configs appear in the list.
5263 5. all_dependent_configs pulled from dependencies, in the order of
5264 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005265 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005266 6. public_configs pulled from dependencies, in the order of the
5267 "deps" list. If a dependency is public, they will be applied
5268 recursively.
5269```
[email protected]449f3e42024-08-01 21:43:27 +08005270### **cflags***: Flags passed to the C compiler. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005271
5272```
5273 A list of strings.
5274
5275 "cflags" are passed to all invocations of the C, C++, Objective C, and
5276 Objective C++ compilers.
5277
5278 To target one of these variants individually, use "cflags_c", "cflags_cc",
5279 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5280 versions of cflags* will be appended on the compiler command line after
5281 "cflags".
5282
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005283 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5284 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005285```
5286
5287#### **Ordering of flags and values**
5288
5289```
5290 1. Those set on the current target (not in a config).
5291 2. Those set on the "configs" on the target in order that the
5292 configs appear in the list.
5293 3. Those set on the "all_dependent_configs" on the target in order
5294 that the configs appear in the list.
5295 4. Those set on the "public_configs" on the target in order that
5296 those configs appear in the list.
5297 5. all_dependent_configs pulled from dependencies, in the order of
5298 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005299 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005300 6. public_configs pulled from dependencies, in the order of the
5301 "deps" list. If a dependency is public, they will be applied
5302 recursively.
5303```
[email protected]449f3e42024-08-01 21:43:27 +08005304### **cflags***: Flags passed to the C compiler. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005305
5306```
5307 A list of strings.
5308
5309 "cflags" are passed to all invocations of the C, C++, Objective C, and
5310 Objective C++ compilers.
5311
5312 To target one of these variants individually, use "cflags_c", "cflags_cc",
5313 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5314 versions of cflags* will be appended on the compiler command line after
5315 "cflags".
5316
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005317 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5318 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005319```
5320
5321#### **Ordering of flags and values**
5322
5323```
5324 1. Those set on the current target (not in a config).
5325 2. Those set on the "configs" on the target in order that the
5326 configs appear in the list.
5327 3. Those set on the "all_dependent_configs" on the target in order
5328 that the configs appear in the list.
5329 4. Those set on the "public_configs" on the target in order that
5330 those configs appear in the list.
5331 5. all_dependent_configs pulled from dependencies, in the order of
5332 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005333 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005334 6. public_configs pulled from dependencies, in the order of the
5335 "deps" list. If a dependency is public, they will be applied
5336 recursively.
5337```
[email protected]449f3e42024-08-01 21:43:27 +08005338### **cflags***: Flags passed to the C compiler. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005339
5340```
5341 A list of strings.
5342
5343 "cflags" are passed to all invocations of the C, C++, Objective C, and
5344 Objective C++ compilers.
5345
5346 To target one of these variants individually, use "cflags_c", "cflags_cc",
5347 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5348 versions of cflags* will be appended on the compiler command line after
5349 "cflags".
5350
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005351 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5352 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005353```
5354
5355#### **Ordering of flags and values**
5356
5357```
5358 1. Those set on the current target (not in a config).
5359 2. Those set on the "configs" on the target in order that the
5360 configs appear in the list.
5361 3. Those set on the "all_dependent_configs" on the target in order
5362 that the configs appear in the list.
5363 4. Those set on the "public_configs" on the target in order that
5364 those configs appear in the list.
5365 5. all_dependent_configs pulled from dependencies, in the order of
5366 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005367 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005368 6. public_configs pulled from dependencies, in the order of the
5369 "deps" list. If a dependency is public, they will be applied
5370 recursively.
5371```
[email protected]449f3e42024-08-01 21:43:27 +08005372### **check_includes**: [boolean] Controls whether a target's files are checked. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005373
5374```
5375 When true (the default), the "gn check" command (as well as "gn gen" with the
5376 --check flag) will check this target's sources and headers for proper
5377 dependencies.
5378
5379 When false, the files in this target will be skipped by default. This does
5380 not affect other targets that depend on the current target, it just skips
5381 checking the includes of the current target's files.
5382
5383 If there are a few conditionally included headers that trip up checking, you
5384 can exclude headers individually by annotating them with "nogncheck" (see "gn
5385 help nogncheck").
5386
5387 The topic "gn help check" has general information on how checking works and
5388 advice on how to pass a check in problematic cases.
5389```
5390
5391#### **Example**
5392
5393```
5394 source_set("busted_includes") {
5395 # This target's includes are messed up, exclude it from checking.
5396 check_includes = false
5397 ...
5398 }
5399```
[email protected]449f3e42024-08-01 21:43:27 +08005400### **code_signing_args**: [string list] [deprecated] Args for the post-processing script. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005401
5402```
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005403 For create_bundle targets, post_processing_args is the list of arguments to
5404 pass to the post-processing script. Typically you would use source expansion
5405 (see "gn help source_expansion") to insert the source file names.
Brett Wilson796ed472018-07-16 15:11:09 -07005406
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005407 Deprecated: this is an old name for the "post_processing_args" property of
5408 the "create_bundle" target. It is still supported to avoid breaking existing
5409 build rules, but a warning will be emitted when it is used.
5410
5411 See also "gn help create_bundle" and "gn help post_processing_args".
Brett Wilson796ed472018-07-16 15:11:09 -07005412```
[email protected]449f3e42024-08-01 21:43:27 +08005413### **code_signing_outputs**: [file list] [deprecated] Outputs of the post-processing step. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005414
5415```
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005416 Outputs from the post-processing step of a create_bundle target. Must refer to
Brett Wilson796ed472018-07-16 15:11:09 -07005417 files in the build directory.
5418
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005419 Deprecated: this is an old name for the "post_processing_outputs" property of
5420 the "create_bundle" target. It is still supported to avoid breaking existing
5421 build rules, but a warning will be emitted when it is used.
5422
5423 See also "gn help create_bundle" and "gn help post_processing_args".
Brett Wilson796ed472018-07-16 15:11:09 -07005424```
[email protected]449f3e42024-08-01 21:43:27 +08005425### **code_signing_script**: [file name] [deprecated] Script for the post-processing step." [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005426
5427```
5428 An absolute or buildfile-relative file name of a Python script to run for a
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005429 create_bundle target to perform the post-processing step.
Brett Wilson796ed472018-07-16 15:11:09 -07005430
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005431 Deprecated: this is an old name for the "post_processing_script" property of
5432 the "create_bundle" target. It is still supported to avoid breaking existing
5433 build rules, but a warning will be emitted when it is used.
5434
5435 See also "gn help create_bundle" and "gn help post_processing_args".
Brett Wilson796ed472018-07-16 15:11:09 -07005436```
[email protected]449f3e42024-08-01 21:43:27 +08005437### **code_signing_sources**: [file list] [deprecated] Sources for the post-processing step. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005438
5439```
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005440 A list of files used as input for the post-processing step of a create_bundle
Brett Wilson796ed472018-07-16 15:11:09 -07005441 target. Non-absolute paths will be resolved relative to the current build
5442 file.
5443
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005444 Deprecated: this is an old name for the "post_processing_sources" property of
5445 the "create_bundle" target. It is still supported to avoid breaking existing
5446 build rules, but a warning will be emitted when it is used.
5447
5448 See also "gn help create_bundle" and "gn help post_processing_args".
Brett Wilson796ed472018-07-16 15:11:09 -07005449```
[email protected]449f3e42024-08-01 21:43:27 +08005450### **complete_static_lib**: [boolean] Links all deps into a static library. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005451
5452```
5453 A static library normally doesn't include code from dependencies, but instead
5454 forwards the static libraries and source sets in its deps up the dependency
5455 chain until a linkable target (an executable or shared library) is reached.
5456 The final linkable target only links each static library once, even if it
5457 appears more than once in its dependency graph.
5458
5459 In some cases the static library might be the final desired output. For
5460 example, you may be producing a static library for distribution to third
5461 parties. In this case, the static library should include code for all
5462 dependencies in one complete package. However, complete static libraries
5463 themselves are never linked into other complete static libraries. All
5464 complete static libraries are for distribution and linking them in would
5465 cause code duplication in this case. If the static library is not for
5466 distribution, it should not be complete.
5467
5468 GN treats non-complete static libraries as source sets when they are linked
5469 into complete static libraries. This is done because some tools like AR do
5470 not handle dependent static libraries properly. This makes it easier to write
5471 "alink" rules.
5472
5473 In rare cases it makes sense to list a header in more than one target if it
5474 could be considered conceptually a member of both. libraries.
5475```
5476
5477#### **Example**
5478
5479```
5480 static_library("foo") {
5481 complete_static_lib = true
5482 deps = [ "bar" ]
5483 }
5484```
[email protected]449f3e42024-08-01 21:43:27 +08005485### **configs**: Configs applying to this target or config. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005486
5487```
5488 A list of config labels.
5489```
5490
5491#### **Configs on a target**
5492
5493```
5494 When used on a target, the include_dirs, defines, etc. in each config are
5495 appended in the order they appear to the compile command for each file in the
5496 target. They will appear after the include_dirs, defines, etc. that the
5497 target sets directly.
5498
5499 Since configs apply after the values set on a target, directly setting a
5500 compiler flag will prepend it to the command line. If you want to append a
5501 flag instead, you can put that flag in a one-off config and append that
5502 config to the target's configs list.
5503
5504 The build configuration script will generally set up the default configs
5505 applying to a given target type (see "set_defaults"). When a target is being
5506 defined, it can add to or remove from this list.
5507```
5508
5509#### **Configs on a config**
5510
5511```
5512 It is possible to create composite configs by specifying configs on a config.
5513 One might do this to forward values, or to factor out blocks of settings from
5514 very large configs into more manageable named chunks.
5515
5516 In this case, the composite config is expanded to be the concatenation of its
5517 own values, and in order, the values from its sub-configs *before* anything
5518 else happens. This has some ramifications:
5519
5520 - A target has no visibility into a config's sub-configs. Target code only
5521 sees the name of the composite config. It can't remove sub-configs or opt
5522 in to only parts of it. The composite config may not even be defined
5523 before the target is.
5524
5525 - You can get duplication of values if a config is listed twice, say, on a
5526 target and in a sub-config that also applies. In other cases, the configs
5527 applying to a target are de-duped. It's expected that if a config is
5528 listed as a sub-config that it is only used in that context. (Note that
5529 it's possible to fix this and de-dupe, but it's not normally relevant and
5530 complicates the implementation.)
5531```
5532
5533#### **Ordering of flags and values**
5534
5535```
5536 1. Those set on the current target (not in a config).
5537 2. Those set on the "configs" on the target in order that the
5538 configs appear in the list.
5539 3. Those set on the "all_dependent_configs" on the target in order
5540 that the configs appear in the list.
5541 4. Those set on the "public_configs" on the target in order that
5542 those configs appear in the list.
5543 5. all_dependent_configs pulled from dependencies, in the order of
5544 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005545 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005546 6. public_configs pulled from dependencies, in the order of the
5547 "deps" list. If a dependency is public, they will be applied
5548 recursively.
5549```
5550
5551#### **Example**
5552
5553```
5554 # Configs on a target.
5555 source_set("foo") {
5556 # Don't use the default RTTI config that BUILDCONFIG applied to us.
5557 configs -= [ "//build:no_rtti" ]
5558
5559 # Add some of our own settings.
5560 configs += [ ":mysettings" ]
5561 }
5562
5563 # Create a default_optimization config that forwards to one of a set of more
5564 # specialized configs depending on build flags. This pattern is useful
5565 # because it allows a target to opt in to either a default set, or a more
5566 # specific set, while avoid duplicating the settings in two places.
5567 config("super_optimization") {
5568 cflags = [ ... ]
5569 }
5570 config("default_optimization") {
5571 if (optimize_everything) {
5572 configs = [ ":super_optimization" ]
5573 } else {
5574 configs = [ ":no_optimization" ]
5575 }
5576 }
5577```
[email protected]449f3e42024-08-01 21:43:27 +08005578### **contents**: Contents to write to file. [Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08005579
5580```
5581 The contents of the file for a generated_file target.
5582 See "gn help generated_file".
5583```
[email protected]449f3e42024-08-01 21:43:27 +08005584### **crate_name**: [string] The name for the compiled crate. [Back to Top](#gn-reference)
Julie Hockettce1fa072019-05-07 17:44:37 -07005585
5586```
5587 Valid for `rust_library` targets and `executable`, `static_library`,
5588 `shared_library`, and `source_set` targets that contain Rust sources.
5589
5590 If crate_name is not set, then this rule will use the target name.
5591```
[email protected]449f3e42024-08-01 21:43:27 +08005592### **crate_root**: [string] The root source file for a binary or library. [Back to Top](#gn-reference)
Julie Hockettce1fa072019-05-07 17:44:37 -07005593
5594```
5595 Valid for `rust_library` targets and `executable`, `static_library`,
5596 `shared_library`, and `source_set` targets that contain Rust sources.
5597
5598 This file is usually the `main.rs` or `lib.rs` for binaries and libraries,
5599 respectively.
5600
5601 If crate_root is not set, then this rule will look for a lib.rs file (or
5602 main.rs for executable) or a single file in sources, if sources contains
5603 only one file.
5604```
[email protected]449f3e42024-08-01 21:43:27 +08005605### **crate_type**: [string] The type of linkage to use on a shared_library. [Back to Top](#gn-reference)
Julie Hockettce1fa072019-05-07 17:44:37 -07005606
5607```
5608 Valid for `rust_library` targets and `executable`, `static_library`,
5609 `shared_library`, and `source_set` targets that contain Rust sources.
5610
5611 Options for this field are "cdylib", "staticlib", "proc-macro", and "dylib".
5612 This field sets the `crate-type` attribute for the `rustc` tool on static
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005613 libraries, as well as the appropriate output extension in the
Julie Hockettce1fa072019-05-07 17:44:37 -07005614 `rust_output_extension` attribute. Since outputs must be explicit, the `lib`
5615 crate type (where the Rust compiler produces what it thinks is the
5616 appropriate library type) is not supported.
5617
5618 It should be noted that the "dylib" crate type in Rust is unstable in the set
5619 of symbols it exposes, and most usages today are potentially wrong and will
5620 be broken in the future.
5621
5622 Static libraries, rust libraries, and executables have this field set
5623 automatically.
5624```
[email protected]449f3e42024-08-01 21:43:27 +08005625### **data**: Runtime data file dependencies. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005626
5627```
5628 Lists files or directories required to run the given target. These are
5629 typically data files or directories of data files. The paths are interpreted
5630 as being relative to the current build file. Since these are runtime
5631 dependencies, they do not affect which targets are built or when. To declare
5632 input files to a script, use "inputs".
5633
5634 Appearing in the "data" section does not imply any special handling such as
5635 copying them to the output directory. This is just used for declaring runtime
5636 dependencies. Runtime dependencies can be queried using the "runtime_deps"
5637 category of "gn desc" or written during build generation via
5638 "--runtime-deps-list-file".
5639
5640 GN doesn't require data files to exist at build-time. So actions that produce
5641 files that are in turn runtime dependencies can list those generated files
5642 both in the "outputs" list as well as the "data" list.
5643
5644 By convention, directories are listed with a trailing slash:
5645 data = [ "test/data/" ]
5646 However, no verification is done on these so GN doesn't enforce this. The
5647 paths are just rebased and passed along when requested.
5648
5649 Note: On iOS and macOS, create_bundle targets will not be recursed into when
5650 gathering data. See "gn help create_bundle" for details.
5651
5652 See "gn help runtime_deps" for how these are used.
5653```
[email protected]449f3e42024-08-01 21:43:27 +08005654### **data_deps**: Non-linked dependencies. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005655
5656```
5657 A list of target labels.
5658
5659 Specifies dependencies of a target that are not actually linked into the
5660 current target. Such dependencies will be built and will be available at
5661 runtime.
5662
5663 This is normally used for things like plugins or helper programs that a
5664 target needs at runtime.
5665
5666 Note: On iOS and macOS, create_bundle targets will not be recursed into when
5667 gathering data_deps. See "gn help create_bundle" for details.
5668
5669 See also "gn help deps" and "gn help data".
5670```
5671
5672#### **Example**
5673
5674```
5675 executable("foo") {
5676 deps = [ "//base" ]
5677 data_deps = [ "//plugins:my_runtime_plugin" ]
5678 }
5679```
[email protected]449f3e42024-08-01 21:43:27 +08005680### **data_keys**: Keys from which to collect metadata. [Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08005681
5682```
5683 These keys are used to identify metadata to collect. If a walked target
5684 defines this key in its metadata, its value will be appended to the resulting
5685 collection.
5686
5687 See "gn help generated_file".
5688```
[email protected]449f3e42024-08-01 21:43:27 +08005689### **defines**: C preprocessor defines. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005690
5691```
5692 A list of strings
5693
5694 These strings will be passed to the C/C++ compiler as #defines. The strings
5695 may or may not include an "=" to assign a value.
5696```
5697
5698#### **Ordering of flags and values**
5699
5700```
5701 1. Those set on the current target (not in a config).
5702 2. Those set on the "configs" on the target in order that the
5703 configs appear in the list.
5704 3. Those set on the "all_dependent_configs" on the target in order
5705 that the configs appear in the list.
5706 4. Those set on the "public_configs" on the target in order that
5707 those configs appear in the list.
5708 5. all_dependent_configs pulled from dependencies, in the order of
5709 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005710 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005711 6. public_configs pulled from dependencies, in the order of the
5712 "deps" list. If a dependency is public, they will be applied
5713 recursively.
5714```
5715
5716#### **Example**
5717
5718```
5719 defines = [ "AWESOME_FEATURE", "LOG_LEVEL=3" ]
5720```
[email protected]449f3e42024-08-01 21:43:27 +08005721### **depfile**: [string] File name for input dependencies for actions. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005722
5723```
5724 If nonempty, this string specifies that the current action or action_foreach
5725 target will generate the given ".d" file containing the dependencies of the
5726 input. Empty or unset means that the script doesn't generate the files.
5727
5728 A depfile should be used only when a target depends on files that are not
5729 already specified by a target's inputs and sources. Likewise, depfiles should
5730 specify only those dependencies not already included in sources or inputs.
5731
5732 The .d file should go in the target output directory. If you have more than
5733 one source file that the script is being run over, you can use the output
5734 file expansions described in "gn help action_foreach" to name the .d file
Nico Weberad9eab22020-11-15 22:20:28 -05005735 according to the input.
Brett Wilson796ed472018-07-16 15:11:09 -07005736
5737 The format is that of a Makefile and all paths must be relative to the root
5738 build directory. Only one output may be listed and it must match the first
5739 output of the action.
5740
5741 Although depfiles are created by an action, they should not be listed in the
5742 action's "outputs" unless another target will use the file as an input.
5743```
5744
5745#### **Example**
5746
5747```
5748 action_foreach("myscript_target") {
5749 script = "myscript.py"
5750 sources = [ ... ]
5751
5752 # Locate the depfile in the output directory named like the
5753 # inputs but with a ".d" appended.
Hector Dearman84c84312023-01-29 11:50:02 +00005754 depfile = "$target_gen_dir/{{source_name_part}}.d"
Brett Wilson796ed472018-07-16 15:11:09 -07005755
5756 # Say our script uses "-o " to indicate the depfile.
Hector Dearman84c84312023-01-29 11:50:02 +00005757 args = [ "{{source}}", "-o", rebase_path(depfile, root_build_dir)]
Brett Wilson796ed472018-07-16 15:11:09 -07005758 }
5759```
[email protected]449f3e42024-08-01 21:43:27 +08005760### **deps**: Private linked dependencies. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005761
5762```
5763 A list of target labels.
5764
5765 Specifies private dependencies of a target. Private dependencies are
5766 propagated up the dependency tree and linked to dependent targets, but do not
5767 grant the ability to include headers from the dependency. Public configs are
5768 not forwarded.
5769```
5770
5771#### **Details of dependency propagation**
5772
5773```
5774 Source sets, shared libraries, and non-complete static libraries will be
5775 propagated up the dependency tree across groups, non-complete static
5776 libraries and source sets.
5777
5778 Executables, shared libraries, and complete static libraries will link all
5779 propagated targets and stop propagation. Actions and copy steps also stop
5780 propagation, allowing them to take a library as an input but not force
5781 dependents to link to it.
5782
5783 Propagation of all_dependent_configs and public_configs happens independently
5784 of target type. all_dependent_configs are always propagated across all types
5785 of targets, and public_configs are always propagated across public deps of
5786 all types of targets.
5787
danakj2a92efd2023-07-06 14:16:38 -04005788 For Rust targets, deps ensures that Rust code can refer to the dependency
5789 target. If the dependency is a C/C++ target, the path to that target will
5790 be made available to Rust for `#[link]` directives.
5791
Brett Wilson796ed472018-07-16 15:11:09 -07005792 Data dependencies are propagated differently. See "gn help data_deps" and
5793 "gn help runtime_deps".
5794
5795 See also "public_deps".
5796```
[email protected]449f3e42024-08-01 21:43:27 +08005797### **externs**: [scope] Set of Rust crate-dependency pairs. [Back to Top](#gn-reference)
Petr Hoseka1413862020-01-03 12:54:33 -08005798
5799```
5800 A list, each value being a scope indicating a pair of crate name and the path
5801 to the Rust library.
5802
5803 These libraries will be passed as `--extern crate_name=path` to compiler
5804 invocation containing the current target.
5805```
5806
5807#### **Examples**
5808
5809```
5810 executable("foo") {
5811 sources = [ "main.rs" ]
5812 externs = [{
5813 crate_name = "bar",
5814 path = "path/to/bar.rlib"
5815 }]
5816 }
5817
5818 This target would compile the `foo` crate with the following `extern` flag:
5819 `--extern bar=path/to/bar.rlib`.
5820```
[email protected]449f3e42024-08-01 21:43:27 +08005821### **framework_dirs**: [directory list] Additional framework search directories. [Back to Top](#gn-reference)
Sylvain Defresnea09ec162020-01-16 12:36:40 +01005822
5823```
5824 A list of source directories.
5825
5826 The directories in this list will be added to the framework search path for
5827 the files in the affected target.
5828```
5829
5830#### **Ordering of flags and values**
5831
5832```
5833 1. Those set on the current target (not in a config).
5834 2. Those set on the "configs" on the target in order that the
5835 configs appear in the list.
5836 3. Those set on the "all_dependent_configs" on the target in order
5837 that the configs appear in the list.
5838 4. Those set on the "public_configs" on the target in order that
5839 those configs appear in the list.
5840 5. all_dependent_configs pulled from dependencies, in the order of
5841 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005842 more than once, only the first occurrence will be used.
Sylvain Defresnea09ec162020-01-16 12:36:40 +01005843 6. public_configs pulled from dependencies, in the order of the
5844 "deps" list. If a dependency is public, they will be applied
5845 recursively.
5846```
5847
5848#### **Example**
5849
5850```
5851 framework_dirs = [ "src/include", "//third_party/foo" ]
5852```
[email protected]449f3e42024-08-01 21:43:27 +08005853### **frameworks**: [name list] Name of frameworks that must be linked. [Back to Top](#gn-reference)
Sylvain Defresnea09ec162020-01-16 12:36:40 +01005854
5855```
5856 A list of framework names.
5857
5858 The frameworks named in that list will be linked with any dynamic link
5859 type target.
5860```
5861
5862#### **Ordering of flags and values**
5863
5864```
5865 1. Those set on the current target (not in a config).
5866 2. Those set on the "configs" on the target in order that the
5867 configs appear in the list.
5868 3. Those set on the "all_dependent_configs" on the target in order
5869 that the configs appear in the list.
5870 4. Those set on the "public_configs" on the target in order that
5871 those configs appear in the list.
5872 5. all_dependent_configs pulled from dependencies, in the order of
5873 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005874 more than once, only the first occurrence will be used.
Sylvain Defresnea09ec162020-01-16 12:36:40 +01005875 6. public_configs pulled from dependencies, in the order of the
5876 "deps" list. If a dependency is public, they will be applied
5877 recursively.
5878```
5879
5880#### **Example**
5881
5882```
5883 frameworks = [ "Foundation.framework", "Foo.framework" ]
5884```
[email protected]449f3e42024-08-01 21:43:27 +08005885### **friend**: Allow targets to include private headers. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005886
5887```
5888 A list of label patterns (see "gn help label_pattern") that allow dependent
5889 targets to include private headers. Applies to all binary targets.
5890
5891 Normally if a target lists headers in the "public" list (see "gn help
5892 public"), other headers are implicitly marked as private. Private headers
5893 can not be included by other targets, even with a public dependency path.
5894 The "gn check" function performs this validation.
5895
5896 A friend declaration allows one or more targets to include private headers.
5897 This is useful for things like unit tests that are closely associated with a
5898 target and require internal knowledge without opening up all headers to be
5899 included by all dependents.
5900
5901 A friend target does not allow that target to include headers when no
5902 dependency exists. A public dependency path must still exist between two
5903 targets to include any headers from a destination target. The friend
5904 annotation merely allows the use of headers that would otherwise be
5905 prohibited because they are private.
5906
5907 The friend annotation is matched only against the target containing the file
5908 with the include directive. Friend annotations are not propagated across
5909 public or private dependencies. Friend annotations do not affect visibility.
5910```
5911
5912#### **Example**
5913
5914```
5915 static_library("lib") {
5916 # This target can include our private headers.
5917 friend = [ ":unit_tests" ]
5918
5919 public = [
5920 "public_api.h", # Normal public API for dependent targets.
5921 ]
5922
5923 # Private API and sources.
5924 sources = [
5925 "a_source_file.cc",
5926
5927 # Normal targets that depend on this one won't be able to include this
5928 # because this target defines a list of "public" headers. Without the
5929 # "public" list, all headers are implicitly public.
5930 "private_api.h",
5931 ]
5932 }
5933
5934 executable("unit_tests") {
5935 sources = [
5936 # This can include "private_api.h" from the :lib target because it
5937 # depends on that target and because of the friend annotation.
5938 "my_test.cc",
5939 ]
5940
5941 deps = [
5942 ":lib", # Required for the include to be allowed.
5943 ]
5944 }
5945```
[email protected]449f3e42024-08-01 21:43:27 +08005946### **gen_deps**: Declares targets that should generate when this one does. [Back to Top](#gn-reference)
Tyler Mandry4a648092022-02-15 19:47:09 +00005947
5948```
5949 A list of target labels.
5950
5951 Not all GN targets that get evaluated are actually turned into ninja targets
5952 (see "gn help execution"). If this target is generated, then any targets in
Ricardo Ribalda85bd0a62023-11-11 16:30:19 +00005953 the "gen_deps" list will also be generated, regardless of the usual criteria.
Tyler Mandry4a648092022-02-15 19:47:09 +00005954
5955 Since "gen_deps" are not build time dependencies, there can be cycles between
5956 "deps" and "gen_deps" or within "gen_deps" itself.
5957```
[email protected]449f3e42024-08-01 21:43:27 +08005958### **include_dirs**: Additional include directories. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005959
5960```
5961 A list of source directories.
5962
5963 The directories in this list will be added to the include path for the files
5964 in the affected target.
5965```
5966
5967#### **Ordering of flags and values**
5968
5969```
5970 1. Those set on the current target (not in a config).
5971 2. Those set on the "configs" on the target in order that the
5972 configs appear in the list.
5973 3. Those set on the "all_dependent_configs" on the target in order
5974 that the configs appear in the list.
5975 4. Those set on the "public_configs" on the target in order that
5976 those configs appear in the list.
5977 5. all_dependent_configs pulled from dependencies, in the order of
5978 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005979 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005980 6. public_configs pulled from dependencies, in the order of the
5981 "deps" list. If a dependency is public, they will be applied
5982 recursively.
5983```
5984
5985#### **Example**
5986
5987```
5988 include_dirs = [ "src/include", "//third_party/foo" ]
5989```
[email protected]449f3e42024-08-01 21:43:27 +08005990### **inputs**: Additional compile-time dependencies. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005991
5992```
5993 Inputs are compile-time dependencies of the current target. This means that
5994 all inputs must be available before compiling any of the sources or executing
5995 any actions.
5996
5997 Inputs are typically only used for action and action_foreach targets.
5998```
5999
6000#### **Inputs for actions**
6001
6002```
6003 For action and action_foreach targets, inputs should be the inputs to script
6004 that don't vary. These should be all .py files that the script uses via
6005 imports (the main script itself will be an implicit dependency of the action
6006 so need not be listed).
6007
6008 For action targets, inputs and sources are treated the same, but from a style
6009 perspective, it's recommended to follow the same rule as action_foreach and
6010 put helper files in the inputs, and the data used by the script (if any) in
6011 sources.
6012
6013 Note that another way to declare input dependencies from an action is to have
6014 the action write a depfile (see "gn help depfile"). This allows the script to
6015 dynamically write input dependencies, that might not be known until actually
6016 executing the script. This is more efficient than doing processing while
6017 running GN to determine the inputs, and is easier to keep in-sync than
6018 hardcoding the list.
6019```
6020
6021#### **Script input gotchas**
6022
6023```
6024 It may be tempting to write a script that enumerates all files in a directory
6025 as inputs. Don't do this! Even if you specify all the files in the inputs or
6026 sources in the GN target (or worse, enumerate the files in an exec_script
6027 call when running GN, which will be slow), the dependencies will be broken.
6028
6029 The problem happens if a file is ever removed because the inputs are not
6030 listed on the command line to the script. Because the script hasn't changed
6031 and all inputs are up to date, the script will not re-run and you will get a
6032 stale build. Instead, either list all inputs on the command line to the
6033 script, or if there are many, create a separate list file that the script
6034 reads. As long as this file is listed in the inputs, the build will detect
6035 when it has changed in any way and the action will re-run.
6036```
6037
6038#### **Inputs for binary targets**
6039
6040```
Julie Hockette2a29402018-07-31 10:11:42 -07006041 Any input dependencies will be resolved before compiling any sources or
6042 linking the target. Normally, all actions that a target depends on will be run
6043 before any files in a target are compiled. So if you depend on generated
6044 headers, you do not typically need to list them in the inputs section.
Brett Wilson796ed472018-07-16 15:11:09 -07006045
6046 Inputs for binary targets will be treated as implicit dependencies, meaning
6047 that changes in any of the inputs will force all sources in the target to be
6048 recompiled. If an input only applies to a subset of source files, you may
6049 want to split those into a separate target to avoid unnecessary recompiles.
6050```
6051
6052#### **Example**
6053
6054```
6055 action("myscript") {
6056 script = "domything.py"
6057 inputs = [ "input.data" ]
6058 }
6059```
[email protected]449f3e42024-08-01 21:43:27 +08006060### **ldflags**: Flags passed to the linker. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006061
6062```
6063 A list of strings.
6064
6065 These flags are passed on the command-line to the linker and generally
6066 specify various linking options. Most targets will not need these and will
6067 use "libs" and "lib_dirs" instead.
6068
6069 ldflags are NOT pushed to dependents, so applying ldflags to source sets or
6070 static libraries will be a no-op. If you want to apply ldflags to dependent
6071 targets, put them in a config and set it in the all_dependent_configs or
6072 public_configs.
6073```
6074
6075#### **Ordering of flags and values**
6076
6077```
6078 1. Those set on the current target (not in a config).
6079 2. Those set on the "configs" on the target in order that the
6080 configs appear in the list.
6081 3. Those set on the "all_dependent_configs" on the target in order
6082 that the configs appear in the list.
6083 4. Those set on the "public_configs" on the target in order that
6084 those configs appear in the list.
6085 5. all_dependent_configs pulled from dependencies, in the order of
6086 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006087 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07006088 6. public_configs pulled from dependencies, in the order of the
6089 "deps" list. If a dependency is public, they will be applied
6090 recursively.
6091```
[email protected]449f3e42024-08-01 21:43:27 +08006092### **lib_dirs**: Additional library directories. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006093
6094```
6095 A list of directories.
6096
6097 Specifies additional directories passed to the linker for searching for the
6098 required libraries. If an item is not an absolute path, it will be treated as
6099 being relative to the current build file.
6100
6101 libs and lib_dirs work differently than other flags in two respects.
Joe Armstrong23d22bc2019-06-28 15:31:03 +08006102 First, they are inherited across static library boundaries until a
Brett Wilson796ed472018-07-16 15:11:09 -07006103 shared library or executable target is reached. Second, they are
6104 uniquified so each one is only passed once (the first instance of it
6105 will be the one used).
6106```
6107
6108#### **Ordering of flags and values**
6109
6110```
6111 1. Those set on the current target (not in a config).
6112 2. Those set on the "configs" on the target in order that the
6113 configs appear in the list.
6114 3. Those set on the "all_dependent_configs" on the target in order
6115 that the configs appear in the list.
6116 4. Those set on the "public_configs" on the target in order that
6117 those configs appear in the list.
6118 5. all_dependent_configs pulled from dependencies, in the order of
6119 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006120 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07006121 6. public_configs pulled from dependencies, in the order of the
6122 "deps" list. If a dependency is public, they will be applied
6123 recursively.
6124
6125 For "libs" and "lib_dirs" only, the values propagated from
6126 dependencies (as described above) are applied last assuming they
6127 are not already in the list.
6128```
6129
6130#### **Example**
6131
6132```
6133 lib_dirs = [ "/usr/lib/foo", "lib/doom_melon" ]
6134```
[email protected]449f3e42024-08-01 21:43:27 +08006135### **libs**: Additional libraries to link. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006136
6137```
6138 A list of library names or library paths.
6139
6140 These libraries will be linked into the final binary (executable or shared
6141 library) containing the current target.
6142
6143 libs and lib_dirs work differently than other flags in two respects.
Joe Armstrong23d22bc2019-06-28 15:31:03 +08006144 First, they are inherited across static library boundaries until a
Brett Wilson796ed472018-07-16 15:11:09 -07006145 shared library or executable target is reached. Second, they are
6146 uniquified so each one is only passed once (the first instance of it
6147 will be the one used).
6148```
6149
6150#### **Types of libs**
6151
6152```
6153 There are several different things that can be expressed in libs:
6154
6155 File paths
6156 Values containing '/' will be treated as references to files in the
6157 checkout. They will be rebased to be relative to the build directory and
6158 specified in the "libs" for linker tools. This facility should be used
6159 for libraries that are checked in to the version control. For libraries
6160 that are generated by the build, use normal GN deps to link them.
6161
6162 System libraries
6163 Values not containing '/' will be treated as system library names. These
6164 will be passed unmodified to the linker and prefixed with the
6165 "lib_switch" attribute of the linker tool. Generally you would set the
6166 "lib_dirs" so the given library is found. Your BUILD.gn file should not
6167 specify the switch (like "-l"): this will be encoded in the "lib_switch"
6168 of the tool.
Brett Wilson796ed472018-07-16 15:11:09 -07006169```
6170
6171#### **Ordering of flags and values**
6172
6173```
6174 1. Those set on the current target (not in a config).
6175 2. Those set on the "configs" on the target in order that the
6176 configs appear in the list.
6177 3. Those set on the "all_dependent_configs" on the target in order
6178 that the configs appear in the list.
6179 4. Those set on the "public_configs" on the target in order that
6180 those configs appear in the list.
6181 5. all_dependent_configs pulled from dependencies, in the order of
6182 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006183 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07006184 6. public_configs pulled from dependencies, in the order of the
6185 "deps" list. If a dependency is public, they will be applied
6186 recursively.
6187
6188 For "libs" and "lib_dirs" only, the values propagated from
6189 dependencies (as described above) are applied last assuming they
6190 are not already in the list.
6191```
6192
6193#### **Examples**
6194
6195```
6196 On Windows:
6197 libs = [ "ctl3d.lib" ]
6198
6199 On Linux:
6200 libs = [ "ld" ]
6201```
[email protected]449f3e42024-08-01 21:43:27 +08006202### **metadata**: Metadata of this target. [Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08006203
6204```
6205 Metadata is a collection of keys and values relating to a particular target.
Julie Hockettd69a9c32019-01-23 14:36:18 -08006206 Values must be lists, allowing for sane and predictable collection behavior.
6207 Generally, these keys will include three types of lists: lists of ordinary
6208 strings, lists of filenames intended to be rebased according to their
6209 particular source directory, and lists of target labels intended to be used
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006210 as barriers to the walk. Verification of these categories occurs at walk time,
Julie Hockettd69a9c32019-01-23 14:36:18 -08006211 not creation time (since it is not clear until the walk which values are
6212 intended for which purpose).
6213```
Nate Fischer8ed01d32019-01-08 17:32:01 -08006214
Julie Hockettd69a9c32019-01-23 14:36:18 -08006215#### **Example**
Nate Fischer8ed01d32019-01-08 17:32:01 -08006216
Julie Hockettd69a9c32019-01-23 14:36:18 -08006217```
Nate Fischer8ed01d32019-01-08 17:32:01 -08006218 group("doom_melon") {
6219 metadata = {
6220 # These keys are not built in to GN but are interpreted when consuming
6221 # metadata.
6222 my_barrier = []
6223 my_files = [ "a.txt", "b.txt" ]
6224 }
6225 }
6226```
[email protected]449f3e42024-08-01 21:43:27 +08006227### **mnemonic**: [string] Prefix displayed when ninja runs this action. [Back to Top](#gn-reference)
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07006228
6229```
6230 Tools in GN can set their ninja "description" which is displayed when
6231 building a target. These are commonly set with the format "CXX $output"
6232 or "LINK $label". By default, all GN actions will have the description
6233 "ACTION $label". Setting a mnemonic will override the "ACTION" prefix
6234 with another string, but the label will still be unconditionally displayed.
6235
6236 Whitespace is not allowed within a mnemonic.
6237```
[email protected]449f3e42024-08-01 21:43:27 +08006238### **module_name**: [string] The name for the compiled module. [Back to Top](#gn-reference)
Sylvain Defresne89e64252020-08-07 13:01:06 +02006239
6240```
6241 Valid for binary targets that contain Swift sources.
6242
6243 If module_name is not set, then this rule will use the target name.
6244```
[email protected]449f3e42024-08-01 21:43:27 +08006245### **output_conversion**: Data format for generated_file targets. [Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08006246
6247```
6248 Controls how the "contents" of a generated_file target is formatted.
Sylvain Defresne72d5a6e2021-06-15 17:01:32 +02006249 See `gn help io_conversion`.
Nate Fischer8ed01d32019-01-08 17:32:01 -08006250```
[email protected]449f3e42024-08-01 21:43:27 +08006251### **output_dir**: [directory] Directory to put output file in. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006252
6253```
6254 For library and executable targets, overrides the directory for the final
6255 output. This must be in the root_build_dir or a child thereof.
6256
6257 This should generally be in the root_out_dir or a subdirectory thereof (the
6258 root_out_dir will be the same as the root_build_dir for the default
6259 toolchain, and will be a subdirectory for other toolchains). Not putting the
6260 output in a subdirectory of root_out_dir can result in collisions between
6261 different toolchains, so you will need to take steps to ensure that your
6262 target is only present in one toolchain.
6263
6264 Normally the toolchain specifies the output directory for libraries and
6265 executables (see "gn help tool"). You will have to consult that for the
6266 default location. The default location will be used if output_dir is
6267 undefined or empty.
6268```
6269
6270#### **Example**
6271
6272```
6273 shared_library("doom_melon") {
6274 output_dir = "$root_out_dir/plugin_libs"
6275 ...
6276 }
6277```
[email protected]449f3e42024-08-01 21:43:27 +08006278### **output_extension**: Value to use for the output's file extension. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006279
6280```
6281 Normally the file extension for a target is based on the target type and the
6282 operating system, but in rare cases you will need to override the name (for
6283 example to use "libfreetype.so.6" instead of libfreetype.so on Linux).
6284
6285 This value should not include a leading dot. If undefined, the default
6286 specified on the tool will be used. If set to the empty string, no output
6287 extension will be used.
6288
6289 The output_extension will be used to set the "{{output_extension}}" expansion
6290 which the linker tool will generally use to specify the output file name. See
6291 "gn help tool".
6292```
6293
6294#### **Example**
6295
6296```
6297 shared_library("freetype") {
6298 if (is_linux) {
6299 # Call the output "libfreetype.so.6"
6300 output_extension = "so.6"
6301 }
6302 ...
6303 }
6304
6305 # On Windows, generate a "mysettings.cpl" control panel applet. Control panel
6306 # applets are actually special shared libraries.
6307 if (is_win) {
6308 shared_library("mysettings") {
6309 output_extension = "cpl"
6310 ...
6311 }
6312 }
6313```
[email protected]449f3e42024-08-01 21:43:27 +08006314### **output_name**: Define a name for the output file other than the default. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006315
6316```
6317 Normally the output name of a target will be based on the target name, so the
6318 target "//foo/bar:bar_unittests" will generate an output file such as
6319 "bar_unittests.exe" (using Windows as an example).
6320
6321 Sometimes you will want an alternate name to avoid collisions or if the
6322 internal name isn't appropriate for public distribution.
6323
6324 The output name should have no extension or prefixes, these will be added
6325 using the default system rules. For example, on Linux an output name of "foo"
6326 will produce a shared library "libfoo.so". There is no way to override the
6327 output prefix of a linker tool on a per- target basis. If you need more
6328 flexibility, create a copy target to produce the file you want.
6329
6330 This variable is valid for all binary output target types.
6331```
6332
6333#### **Example**
6334
6335```
6336 static_library("doom_melon") {
6337 output_name = "fluffy_bunny"
6338 }
6339```
[email protected]449f3e42024-08-01 21:43:27 +08006340### **output_prefix_override**: Don't use prefix for output name. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006341
6342```
6343 A boolean that overrides the output prefix for a target. Defaults to false.
6344
6345 Some systems use prefixes for the names of the final target output file. The
6346 normal example is "libfoo.so" on Linux for a target named "foo".
6347
6348 The output prefix for a given target type is specified on the linker tool
6349 (see "gn help tool"). Sometimes this prefix is undesired.
6350
6351 See also "gn help output_extension".
6352```
6353
6354#### **Example**
6355
6356```
6357 shared_library("doom_melon") {
6358 # Normally this will produce "libdoom_melon.so" on Linux. Setting this flag
6359 # will produce "doom_melon.so".
6360 output_prefix_override = true
6361 ...
6362 }
6363```
[email protected]449f3e42024-08-01 21:43:27 +08006364### **outputs**: Output files for actions and copy targets. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006365
6366```
6367 Outputs is valid for "copy", "action", and "action_foreach" target types and
6368 indicates the resulting files. Outputs must always refer to files in the
6369 build directory.
6370
6371 copy
6372 Copy targets should have exactly one entry in the outputs list. If there is
6373 exactly one source, this can be a literal file name or a source expansion.
6374 If there is more than one source, this must contain a source expansion to
6375 map a single input name to a single output name. See "gn help copy".
6376
6377 action_foreach
6378 Action_foreach targets must always use source expansions to map input files
6379 to output files. There can be more than one output, which means that each
6380 invocation of the script will produce a set of files (presumably based on
6381 the name of the input file). See "gn help action_foreach".
6382
6383 action
6384 Action targets (excluding action_foreach) must list literal output file(s)
6385 with no source expansions. See "gn help action".
6386```
[email protected]449f3e42024-08-01 21:43:27 +08006387### **partial_info_plist**: [filename] Path plist from asset catalog compiler. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006388
6389```
6390 Valid for create_bundle target, corresponds to the path for the partial
6391 Info.plist created by the asset catalog compiler that needs to be merged
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006392 with the application Info.plist (usually done by the post-processing script).
Brett Wilson796ed472018-07-16 15:11:09 -07006393
6394 The file will be generated regardless of whether the asset compiler has
6395 been invoked or not. See "gn help create_bundle".
6396```
[email protected]449f3e42024-08-01 21:43:27 +08006397### **pool**: Label of the pool used by binary targets actions. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006398
6399```
Petr Hosek7a6231e2022-10-22 23:14:18 +00006400 A fully-qualified label representing the pool that will be used for binary
6401 targets and actions. Pools are defined using the pool() {...} declaration.
Brett Wilson796ed472018-07-16 15:11:09 -07006402```
6403
6404#### **Example**
6405
6406```
Petr Hosek7a6231e2022-10-22 23:14:18 +00006407 executable("binary") {
6408 pool = "//build:custom_pool"
6409 ...
6410 }
6411
Brett Wilson796ed472018-07-16 15:11:09 -07006412 action("action") {
6413 pool = "//build:custom_pool"
6414 ...
6415 }
6416```
[email protected]449f3e42024-08-01 21:43:27 +08006417### **post_processing_args**: [string list] Args for the post-processing script. [Back to Top](#gn-reference)
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006418
6419```
6420 For create_bundle targets, post_processing_args is the list of arguments to
6421 pass to the post-processing script. Typically you would use source expansion
6422 (see "gn help source_expansion") to insert the source file names.
6423
6424 See also "gn help create_bundle".
6425```
[email protected]449f3e42024-08-01 21:43:27 +08006426### **post_processing_outputs**: [file list] Outputs of the post-processing step. [Back to Top](#gn-reference)
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006427
6428```
6429 Outputs from the post-processing step of a create_bundle target. Must refer to
6430 files in the build directory.
6431
6432 See also "gn help create_bundle".
6433```
[email protected]449f3e42024-08-01 21:43:27 +08006434### **post_processing_script**: [file name] Script for the post-processing step." [Back to Top](#gn-reference)
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006435
6436```
6437 An absolute or buildfile-relative file name of a Python script to run for a
6438 create_bundle target to perform the post-processing step.
6439
6440 See also "gn help create_bundle".
6441```
[email protected]449f3e42024-08-01 21:43:27 +08006442### **post_processing_sources**: [file list] Sources for the post-processing step. [Back to Top](#gn-reference)
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006443
6444```
6445 A list of files used as input for the post-processing step of a create_bundle
6446 target. Non-absolute paths will be resolved relative to the current build
6447 file.
6448
6449 See also "gn help create_bundle".
6450```
[email protected]449f3e42024-08-01 21:43:27 +08006451### **precompiled_header**: [string] Header file to precompile. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006452
6453```
6454 Precompiled headers will be used when a target specifies this value, or a
6455 config applying to this target specifies this value. In addition, the tool
6456 corresponding to the source files must also specify precompiled headers (see
6457 "gn help tool"). The tool will also specify what type of precompiled headers
6458 to use, by setting precompiled_header_type to either "gcc" or "msvc".
6459
6460 The precompiled header/source variables can be specified on a target or a
6461 config, but must be the same for all configs applying to a given target since
6462 a target can only have one precompiled header.
6463
6464 If you use both C and C++ sources, the precompiled header and source file
6465 will be compiled once per language. You will want to make sure to wrap C++
6466 includes in __cplusplus #ifdefs so the file will compile in C mode.
6467```
6468
6469#### **GCC precompiled headers**
6470
6471```
6472 When using GCC-style precompiled headers, "precompiled_source" contains the
6473 path of a .h file that is precompiled and then included by all source files
6474 in targets that set "precompiled_source".
6475
6476 The value of "precompiled_header" is not used with GCC-style precompiled
6477 headers.
6478```
6479
6480#### **MSVC precompiled headers**
6481
6482```
6483 When using MSVC-style precompiled headers, the "precompiled_header" value is
6484 a string corresponding to the header. This is NOT a path to a file that GN
6485 recognises, but rather the exact string that appears in quotes after
6486 an #include line in source code. The compiler will match this string against
6487 includes or forced includes (/FI).
6488
6489 MSVC also requires a source file to compile the header with. This must be
6490 specified by the "precompiled_source" value. In contrast to the header value,
6491 this IS a GN-style file name, and tells GN which source file to compile to
6492 make the .pch file used for subsequent compiles.
6493
6494 For example, if the toolchain specifies MSVC headers:
6495
6496 toolchain("vc_x64") {
6497 ...
6498 tool("cxx") {
6499 precompiled_header_type = "msvc"
6500 ...
6501
6502 You might make a config like this:
6503
6504 config("use_precompiled_headers") {
6505 precompiled_header = "build/precompile.h"
6506 precompiled_source = "//build/precompile.cc"
6507
6508 # Either your source files should #include "build/precompile.h"
6509 # first, or you can do this to force-include the header.
6510 cflags = [ "/FI$precompiled_header" ]
6511 }
6512
6513 And then define a target that uses the config:
6514
6515 executable("doom_melon") {
6516 configs += [ ":use_precompiled_headers" ]
6517 ...
6518```
[email protected]449f3e42024-08-01 21:43:27 +08006519### **precompiled_header_type**: [string] "gcc" or "msvc". [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006520
6521```
6522 See "gn help precompiled_header".
6523```
[email protected]449f3e42024-08-01 21:43:27 +08006524### **precompiled_source**: [file name] Source file to precompile. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006525
6526```
6527 The source file that goes along with the precompiled_header when using
6528 "msvc"-style precompiled headers. It will be implicitly added to the sources
6529 of the target. See "gn help precompiled_header".
6530```
[email protected]449f3e42024-08-01 21:43:27 +08006531### **product_type**: [string] Product type for the bundle. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006532
6533```
Sylvain Defresnee5aee7b2023-06-08 10:08:10 -04006534 Valid for "create_bundle" and "bundle_data" targets.
Brett Wilson796ed472018-07-16 15:11:09 -07006535
Sylvain Defresnee5aee7b2023-06-08 10:08:10 -04006536 Correspond to the type of the bundle. Used by transparent "create_bundle"
6537 target to control whether a "bundle_data" needs to be propagated or not.
6538
6539 When generating Xcode project, the product_type is propagated and only
6540 "create_bundle" with a non-empty product_type will have a corresponding
6541 target in the project.
Brett Wilson796ed472018-07-16 15:11:09 -07006542```
[email protected]449f3e42024-08-01 21:43:27 +08006543### **public**: Declare public header files for a target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006544
6545```
6546 A list of files that other targets can include. These permissions are checked
6547 via the "check" command (see "gn help check").
6548
6549 If no public files are declared, other targets (assuming they have visibility
6550 to depend on this target) can include any file in the sources list. If this
6551 variable is defined on a target, dependent targets may only include files on
6552 this whitelist unless that target is marked as a friend (see "gn help
6553 friend").
6554
6555 Header file permissions are also subject to visibility. A target must be
6556 visible to another target to include any files from it at all and the public
6557 headers indicate which subset of those files are permitted. See "gn help
6558 visibility" for more.
6559
6560 Public files are inherited through the dependency tree. So if there is a
6561 dependency A -> B -> C, then A can include C's public headers. However, the
6562 same is NOT true of visibility, so unless A is in C's visibility list, the
6563 include will be rejected.
6564
6565 GN only knows about files declared in the "sources" and "public" sections of
6566 targets. If a file is included that is not known to the build, it will be
6567 allowed.
6568
6569 It is common for test targets to need to include private headers for their
6570 associated code. In this case, list the test target in the "friend" list of
6571 the target that owns the private header to allow the inclusion. See
6572 "gn help friend" for more.
Julie Hockette2a29402018-07-31 10:11:42 -07006573
6574 When a binary target has no explicit or implicit public headers (a "public"
6575 list is defined but is empty), GN assumes that the target can not propagate
6576 any compile-time dependencies up the dependency tree. In this case, the build
6577 can be parallelized more efficiently.
6578 Say there are dependencies:
6579 A (shared library) -> B (shared library) -> C (action).
6580 Normally C must complete before any source files in A can compile (because
6581 there might be generated includes). But when B explicitly declares no public
6582 headers, C can execute in parallel with A's compile steps. C must still be
6583 complete before any dependents link.
Brett Wilson796ed472018-07-16 15:11:09 -07006584```
6585
6586#### **Examples**
6587
6588```
6589 These exact files are public:
6590 public = [ "foo.h", "bar.h" ]
6591
6592 No files are public (no targets may include headers from this one):
Julie Hockette2a29402018-07-31 10:11:42 -07006593 # This allows starting compilation in dependent targets earlier.
Brett Wilson796ed472018-07-16 15:11:09 -07006594 public = []
6595```
[email protected]449f3e42024-08-01 21:43:27 +08006596### **public_configs**: Configs to be applied on dependents. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006597
6598```
6599 A list of config labels.
6600
6601 Targets directly depending on this one will have the configs listed in this
6602 variable added to them. These configs will also apply to the current target.
Julie Hockette2a29402018-07-31 10:11:42 -07006603 Generally, public configs are used to apply defines and include directories
6604 necessary to compile this target's header files.
Brett Wilson796ed472018-07-16 15:11:09 -07006605
Julie Hockette2a29402018-07-31 10:11:42 -07006606 See also "gn help all_dependent_configs".
6607```
6608
6609#### **Propagation of public configs**
6610
6611```
6612 Public configs are applied to all targets that depend directly on this one.
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006613 These dependent targets can further push this target's public configs
Julie Hockette2a29402018-07-31 10:11:42 -07006614 higher in the dependency tree by depending on it via public_deps (see "gn
6615 help public_deps").
6616
6617 static_library("toplevel") {
6618 # This target will get "my_config" applied to it. However, since this
6619 # target uses "deps" and not "public_deps", targets that depend on this
6620 # one won't get it.
6621 deps = [ ":intermediate" ]
6622 }
6623
6624 static_library("intermediate") {
6625 # Depending on "lower" in any way will apply "my_config" to this target.
6626 # Additionall, since this target depends on "lower" via public_deps,
6627 # targets that depend on this one will also get "my_config".
6628 public_deps = [ ":lower" ]
6629 }
6630
6631 static_library("lower") {
6632 # This will get applied to all targets that depend on this one.
6633 public_configs = [ ":my_config" ]
6634 }
6635
6636 Public config propagation happens in a second phase once a target and all of
6637 its dependencies have been resolved. Therefore, a target will not see these
Brett Wilson796ed472018-07-16 15:11:09 -07006638 force-added configs in their "configs" variable while the script is running,
6639 and they can not be removed. As a result, this capability should generally
Julie Hockette2a29402018-07-31 10:11:42 -07006640 only be used to add defines and include directories rather than setting
6641 complicated flags that some targets may not want.
Brett Wilson796ed472018-07-16 15:11:09 -07006642
Julie Hockette2a29402018-07-31 10:11:42 -07006643 Public configs may or may not be propagated across toolchain boundaries
6644 depending on the value of the propagates_configs flag (see "gn help
6645 toolchain") on the toolchain of the target declaring the public_config.
6646```
6647
6648#### **Avoiding applying public configs to this target**
6649
6650```
6651 If you want the config to apply to targets that depend on this one, but NOT
6652 this one, define an extra layer of indirection using a group:
6653
6654 # External targets depend on this group.
6655 group("my_target") {
6656 # Config to apply to all targets that depend on this one.
6657 public_configs = [ ":external_settings" ]
6658 deps = [ ":internal_target" ]
6659 }
6660
6661 # Internal target to actually compile the sources.
6662 static_library("internal_target") {
6663 # Force all external targets to depend on the group instead of directly
6664 # on this so the "external_settings" config will get applied.
6665 visibility = [ ":my_target" ]
6666 ...
6667 }
Brett Wilson796ed472018-07-16 15:11:09 -07006668```
6669
6670#### **Ordering of flags and values**
6671
6672```
6673 1. Those set on the current target (not in a config).
6674 2. Those set on the "configs" on the target in order that the
6675 configs appear in the list.
6676 3. Those set on the "all_dependent_configs" on the target in order
6677 that the configs appear in the list.
6678 4. Those set on the "public_configs" on the target in order that
6679 those configs appear in the list.
6680 5. all_dependent_configs pulled from dependencies, in the order of
6681 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006682 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07006683 6. public_configs pulled from dependencies, in the order of the
6684 "deps" list. If a dependency is public, they will be applied
6685 recursively.
6686```
[email protected]449f3e42024-08-01 21:43:27 +08006687### **public_deps**: Declare public dependencies. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006688
6689```
6690 Public dependencies are like private dependencies (see "gn help deps") but
6691 additionally express that the current target exposes the listed deps as part
6692 of its public API.
6693
6694 This has several ramifications:
6695
6696 - public_configs that are part of the dependency are forwarded to direct
6697 dependents.
6698
6699 - Public headers in the dependency are usable by dependents (includes do
6700 not require a direct dependency or visibility).
6701
6702 - If the current target is a shared library, other shared libraries that it
6703 publicly depends on (directly or indirectly) are propagated up the
6704 dependency tree to dependents for linking.
Julie Hockette2a29402018-07-31 10:11:42 -07006705
6706 See also "gn help public_configs".
Brett Wilson796ed472018-07-16 15:11:09 -07006707```
6708
6709#### **Discussion**
6710
6711```
6712 Say you have three targets: A -> B -> C. C's visibility may allow B to depend
6713 on it but not A. Normally, this would prevent A from including any headers
6714 from C, and C's public_configs would apply only to B.
6715
6716 If B lists C in its public_deps instead of regular deps, A will now inherit
6717 C's public_configs and the ability to include C's public headers.
6718
6719 Generally if you are writing a target B and you include C's headers as part
6720 of B's public headers, or targets depending on B should consider B and C to
6721 be part of a unit, you should use public_deps instead of deps.
6722```
6723
6724#### **Example**
6725
6726```
6727 # This target can include files from "c" but not from
6728 # "super_secret_implementation_details".
6729 executable("a") {
6730 deps = [ ":b" ]
6731 }
6732
6733 shared_library("b") {
6734 deps = [ ":super_secret_implementation_details" ]
6735 public_deps = [ ":c" ]
6736 }
6737```
[email protected]449f3e42024-08-01 21:43:27 +08006738### **rebase**: Rebase collected metadata as files. [Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08006739
6740```
6741 A boolean that triggers a rebase of collected metadata strings based on their
6742 declared file. Defaults to false.
6743
6744 Metadata generally declares files as strings relative to the local build file.
6745 However, this data is often used in other contexts, and so setting this flag
6746 will force the metadata collection to be rebased according to the local build
6747 file's location and thus allow the filename to be used anywhere.
6748
6749 Setting this flag will raise an error if any target's specified metadata is
6750 not a string value.
6751
6752 See also "gn help generated_file".
6753```
[email protected]449f3e42024-08-01 21:43:27 +08006754### **response_file_contents**: Contents of a response file for actions. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006755
6756```
6757 Sometimes the arguments passed to a script can be too long for the system's
6758 command-line capabilities. This is especially the case on Windows where the
6759 maximum command-line length is less than 8K. A response file allows you to
6760 pass an unlimited amount of data to a script in a temporary file for an
6761 action or action_foreach target.
6762
6763 If the response_file_contents variable is defined and non-empty, the list
6764 will be treated as script args (including possibly substitution patterns)
6765 that will be written to a temporary file at build time. The name of the
6766 temporary file will be substituted for "{{response_file_name}}" in the script
6767 args.
6768
6769 The response file contents will always be quoted and escaped according to
6770 Unix shell rules. To parse the response file, the Python script should use
6771 "shlex.split(file_contents)".
6772```
6773
6774#### **Example**
6775
6776```
6777 action("process_lots_of_files") {
6778 script = "process.py",
6779 inputs = [ ... huge list of files ... ]
6780
6781 # Write all the inputs to a response file for the script. Also,
6782 # make the paths relative to the script working directory.
6783 response_file_contents = rebase_path(inputs, root_build_dir)
6784
6785 # The script expects the name of the response file in --file-list.
6786 args = [
6787 "--enable-foo",
6788 "--file-list={{response_file_name}}",
6789 ]
6790 }
6791```
[email protected]449f3e42024-08-01 21:43:27 +08006792### **rustflags**: Flags passed to the Rust compiler. [Back to Top](#gn-reference)
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01006793
6794```
6795 A list of strings.
6796
6797 "rustflags" are passed to all invocations of the Rust compiler.
6798```
[email protected]449f3e42024-08-01 21:43:27 +08006799### **script**: Script file for actions. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006800
6801```
6802 An absolute or buildfile-relative file name of a Python script to run for a
6803 action and action_foreach targets (see "gn help action" and "gn help
6804 action_foreach").
6805```
[email protected]449f3e42024-08-01 21:43:27 +08006806### **sources**: Source files for a target [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006807
6808```
6809 A list of files. Non-absolute paths will be resolved relative to the current
6810 build file.
6811```
6812
6813#### **Sources for binary targets**
6814
6815```
6816 For binary targets (source sets, executables, and libraries), the known file
6817 types will be compiled with the associated tools. Unknown file types and
6818 headers will be skipped. However, you should still list all C/C+ header files
6819 so GN knows about the existence of those files for the purposes of include
6820 checking.
6821
6822 As a special case, a file ending in ".def" will be treated as a Windows
6823 module definition file. It will be appended to the link line with a
6824 preceding "/DEF:" string. There must be at most one .def file in a target
6825 and they do not cross dependency boundaries (so specifying a .def file in a
6826 static library or source set will have no effect on the executable or shared
6827 library they're linked into).
Julie Hockettce1fa072019-05-07 17:44:37 -07006828
6829 For Rust targets that do not specify a crate_root, then the crate_root will
6830 look for a lib.rs file (or main.rs for executable) or a single file in
6831 sources, if sources contains only one file.
Brett Wilson796ed472018-07-16 15:11:09 -07006832```
6833
6834#### **Sources for non-binary targets**
6835
6836```
6837 action_foreach
6838 The sources are the set of files that the script will be executed over. The
6839 script will run once per file.
6840
6841 action
6842 The sources will be treated the same as inputs. See "gn help inputs" for
6843 more information and usage advice.
6844
6845 copy
6846 The source are the source files to copy.
6847```
[email protected]449f3e42024-08-01 21:43:27 +08006848### **swiftflags**: Flags passed to the swift compiler. [Back to Top](#gn-reference)
Sylvain Defresne89e64252020-08-07 13:01:06 +02006849
6850```
6851 A list of strings.
6852
6853 "swiftflags" are passed to any invocation of a tool that takes an .swift
6854 file as input.
6855```
6856
6857#### **Ordering of flags and values**
6858
6859```
6860 1. Those set on the current target (not in a config).
6861 2. Those set on the "configs" on the target in order that the
6862 configs appear in the list.
6863 3. Those set on the "all_dependent_configs" on the target in order
6864 that the configs appear in the list.
6865 4. Those set on the "public_configs" on the target in order that
6866 those configs appear in the list.
6867 5. all_dependent_configs pulled from dependencies, in the order of
6868 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006869 more than once, only the first occurrence will be used.
Sylvain Defresne89e64252020-08-07 13:01:06 +02006870 6. public_configs pulled from dependencies, in the order of the
6871 "deps" list. If a dependency is public, they will be applied
6872 recursively.
6873```
[email protected]449f3e42024-08-01 21:43:27 +08006874### **testonly**: Declares a target must only be used for testing. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006875
6876```
6877 Boolean. Defaults to false.
6878
6879 When a target is marked "testonly = true", it must only be depended on by
6880 other test-only targets. Otherwise, GN will issue an error that the
6881 depenedency is not allowed.
6882
6883 This feature is intended to prevent accidentally shipping test code in a
6884 final product.
6885```
6886
6887#### **Example**
6888
6889```
6890 source_set("test_support") {
6891 testonly = true
6892 ...
6893 }
6894```
[email protected]449f3e42024-08-01 21:43:27 +08006895### **transparent**: [bool] True if the bundle is transparent. [Back to Top](#gn-reference)
Sylvain Defresnee5aee7b2023-06-08 10:08:10 -04006896
6897```
6898 A boolean.
6899
6900 Valid for "create_bundle" target. If true, the "create_bundle" target will
6901 not package the "bundle_data" deps but will forward them to all targets that
6902 depends on it (unless the "bundle_data" target sets "product_type" to the
6903 same value as the "create_bundle" target).
6904```
[email protected]449f3e42024-08-01 21:43:27 +08006905### **visibility**: A list of labels that can depend on a target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006906
6907```
6908 A list of labels and label patterns that define which targets can depend on
6909 the current one. These permissions are checked via the "check" command (see
6910 "gn help check").
6911
6912 If visibility is not defined, it defaults to public ("*").
6913
6914 If visibility is defined, only the targets with labels that match it can
6915 depend on the current target. The empty list means no targets can depend on
6916 the current target.
6917
6918 Tip: Often you will want the same visibility for all targets in a BUILD file.
6919 In this case you can just put the definition at the top, outside of any
6920 target, and the targets will inherit that scope and see the definition.
6921```
6922
6923#### **Patterns**
6924
6925```
6926 See "gn help label_pattern" for more details on what types of patterns are
6927 supported. If a toolchain is specified, only targets in that toolchain will
6928 be matched. If a toolchain is not specified on a pattern, targets in all
6929 toolchains will be matched.
6930```
6931
6932#### **Examples**
6933
6934```
6935 Only targets in the current buildfile ("private"):
6936 visibility = [ ":*" ]
6937
6938 No targets (used for targets that should be leaf nodes):
6939 visibility = []
6940
6941 Any target ("public", the default):
6942 visibility = [ "*" ]
6943
6944 All targets in the current directory and any subdirectory:
6945 visibility = [ "./*" ]
6946
6947 Any target in "//bar/BUILD.gn":
6948 visibility = [ "//bar:*" ]
6949
6950 Any target in "//bar/" or any subdirectory thereof:
6951 visibility = [ "//bar/*" ]
6952
6953 Just these specific targets:
6954 visibility = [ ":mything", "//foo:something_else" ]
6955
6956 Any target in the current directory and any subdirectory thereof, plus
Petr Hosek7a6231e2022-10-22 23:14:18 +00006957 any targets in "//bar/" and any subdirectory thereof.
Brett Wilson796ed472018-07-16 15:11:09 -07006958 visibility = [ "./*", "//bar/*" ]
6959```
[email protected]449f3e42024-08-01 21:43:27 +08006960### **walk_keys**: Key(s) for managing the metadata collection walk. [Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08006961
6962```
Julie Hockett152c5142019-07-12 09:53:43 -06006963 Defaults to [""].
Nate Fischer8ed01d32019-01-08 17:32:01 -08006964
6965 These keys are used to control the next step in a collection walk, acting as
6966 barriers. If a specified key is defined in a target's metadata, the walk will
6967 use the targets listed in that value to determine which targets are walked.
6968
Julie Hockett152c5142019-07-12 09:53:43 -06006969 If no walk_keys are specified for a generated_file target (i.e. "[""]"), the
Nate Fischer8ed01d32019-01-08 17:32:01 -08006970 walk will touch all deps and data_deps of the specified target recursively.
6971
6972 See "gn help generated_file".
6973```
[email protected]449f3e42024-08-01 21:43:27 +08006974### **weak_frameworks**: [name list] Name of frameworks that must be weak linked. [Back to Top](#gn-reference)
Robert Sesekd0a6f072020-05-15 11:21:22 -04006975
6976```
6977 A list of framework names.
6978
6979 The frameworks named in that list will be weak linked with any dynamic link
6980 type target. Weak linking instructs the dynamic loader to attempt to load
6981 the framework, but if it is not able to do so, it leaves any imported symbols
6982 unresolved. This is typically used when a framework is present in a new
6983 version of an SDK but not on older versions of the OS that the software runs
6984 on.
6985```
6986
6987#### **Ordering of flags and values**
6988
6989```
6990 1. Those set on the current target (not in a config).
6991 2. Those set on the "configs" on the target in order that the
6992 configs appear in the list.
6993 3. Those set on the "all_dependent_configs" on the target in order
6994 that the configs appear in the list.
6995 4. Those set on the "public_configs" on the target in order that
6996 those configs appear in the list.
6997 5. all_dependent_configs pulled from dependencies, in the order of
6998 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006999 more than once, only the first occurrence will be used.
Robert Sesekd0a6f072020-05-15 11:21:22 -04007000 6. public_configs pulled from dependencies, in the order of the
7001 "deps" list. If a dependency is public, they will be applied
7002 recursively.
7003```
7004
7005#### **Example**
7006
7007```
7008 weak_frameworks = [ "OnlyOnNewerOSes.framework" ]
7009```
[email protected]449f3e42024-08-01 21:43:27 +08007010### **write_runtime_deps**: Writes the target's runtime_deps to the given path. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007011
7012```
7013 Does not synchronously write the file, but rather schedules it to be written
7014 at the end of generation.
7015
7016 If the file exists and the contents are identical to that being written, the
7017 file will not be updated. This will prevent unnecessary rebuilds of targets
7018 that depend on this file.
7019
7020 Path must be within the output directory.
7021
7022 See "gn help runtime_deps" for how the runtime dependencies are computed.
7023
7024 The format of this file will list one file per line with no escaping. The
7025 files will be relative to the root_build_dir. The first line of the file will
7026 be the main output file of the target itself. The file contents will be the
7027 same as requesting the runtime deps be written on the command line (see "gn
7028 help --runtime-deps-list-file").
7029```
[email protected]449f3e42024-08-01 21:43:27 +08007030### **xcasset_compiler_flags**: Flags passed to xcassets compiler. [Back to Top](#gn-reference)
Harley Li0a9affb2020-06-03 10:38:42 -04007031
7032```
7033 A list of strings.
7034
7035 Valid for create_bundle target. Those flags are directly passed to
7036 xcassets compiler, corresponding to {{xcasset_compiler_flags}} substitution
7037 in compile_xcassets tool.
7038```
[email protected]449f3e42024-08-01 21:43:27 +08007039### **xcode_extra_attributes**: [scope] Extra attributes for Xcode projects. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007040
7041```
7042 The value defined in this scope will be copied to the EXTRA_ATTRIBUTES
7043 property of the generated Xcode project. They are only meaningful when
7044 generating with --ide=xcode.
7045
7046 See "gn help create_bundle" for more information.
7047```
[email protected]449f3e42024-08-01 21:43:27 +08007048### **xcode_test_application_name**: Name for Xcode test target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007049
7050```
7051 Each unit and ui test target must have a test application target, and this
7052 value is used to specify the relationship. Only meaningful to Xcode (used as
7053 part of the Xcode project generation).
7054
7055 See "gn help create_bundle" for more information.
7056```
7057
Julie Hockette2a29402018-07-31 10:11:42 -07007058#### **Example**
Brett Wilson796ed472018-07-16 15:11:09 -07007059
7060```
7061 create_bundle("chrome_xctest") {
7062 test_application_name = "chrome"
7063 ...
7064 }
7065```
7066## Other help topics
7067
[email protected]449f3e42024-08-01 21:43:27 +08007068### **Build Arguments Overview** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007069
7070```
7071 Build arguments are variables passed in from outside of the build that build
7072 files can query to determine how the build works.
7073```
7074
7075#### **How build arguments are set**
7076
7077```
7078 First, system default arguments are set based on the current system. The
7079 built-in arguments are:
7080 - host_cpu
7081 - host_os
7082 - current_cpu
7083 - current_os
7084 - target_cpu
7085 - target_os
7086
7087 Next, project-specific overrides are applied. These are specified inside
7088 the default_args variable of //.gn. See "gn help dotfile" for more.
7089
7090 If specified, arguments from the --args command line flag are used. If that
7091 flag is not specified, args from previous builds in the build directory will
7092 be used (this is in the file args.gn in the build directory).
7093
7094 Last, for targets being compiled with a non-default toolchain, the toolchain
7095 overrides are applied. These are specified in the toolchain_args section of a
7096 toolchain definition. The use-case for this is that a toolchain may be
7097 building code for a different platform, and that it may want to always
7098 specify Posix, for example. See "gn help toolchain" for more.
7099
7100 If you specify an override for a build argument that never appears in a
7101 "declare_args" call, a nonfatal error will be displayed.
7102```
7103
7104#### **Examples**
7105
7106```
7107 gn args out/FooBar
7108 Create the directory out/FooBar and open an editor. You would type
7109 something like this into that file:
7110 enable_doom_melon=false
7111 os="android"
7112
7113 gn gen out/FooBar --args="enable_doom_melon=true os=\"android\""
7114 This will overwrite the build directory with the given arguments. (Note
7115 that the quotes inside the args command will usually need to be escaped
7116 for your shell to pass through strings values.)
7117```
7118
7119#### **How build arguments are used**
7120
7121```
7122 If you want to use an argument, you use declare_args() and specify default
7123 values. These default values will apply if none of the steps listed in the
7124 "How build arguments are set" section above apply to the given argument, but
7125 the defaults will not override any of these.
7126
7127 Often, the root build config file will declare global arguments that will be
7128 passed to all buildfiles. Individual build files can also specify arguments
7129 that apply only to those files. It is also useful to specify build args in an
7130 "import"-ed file if you want such arguments to apply to multiple buildfiles.
7131```
[email protected]449f3e42024-08-01 21:43:27 +08007132### **.gn file** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007133
7134```
7135 When gn starts, it will search the current directory and parent directories
7136 for a file called ".gn". This indicates the source root. You can override
7137 this detection by using the --root command-line argument
7138
7139 The .gn file in the source root will be executed. The syntax is the same as a
7140 buildfile, but with very limited build setup-specific meaning.
7141
7142 If you specify --root, by default GN will look for the file .gn in that
7143 directory. If you want to specify a different file, you can additionally pass
7144 --dotfile:
7145
7146 gn gen out/Debug --root=/home/build --dotfile=/home/my_gn_file.gn
7147```
7148
7149#### **Variables**
7150
7151```
7152 arg_file_template [optional]
7153 Path to a file containing the text that should be used as the default
7154 args.gn content when you run `gn args`.
7155
7156 buildconfig [required]
7157 Path to the build config file. This file will be used to set up the
7158 build file execution environment for each toolchain.
7159
7160 check_targets [optional]
7161 A list of labels and label patterns that should be checked when running
Erik Staab5d109d72020-06-29 22:53:23 -07007162 "gn check" or "gn gen --check". If neither check_targets or
7163 no_check_targets (see below) is specified, all targets will be checked.
7164 It is an error to specify both check_targets and no_check_targets. If it
7165 is the empty list, no targets will be checked. To bypass this list,
7166 request an explicit check of targets, like "//*".
7167
7168 The format of this list is identical to that of "visibility" so see "gn
7169 help visibility" for examples.
7170
7171 no_check_targets [optional]
7172 A list of labels and label patterns that should *not* be checked when
7173 running "gn check" or "gn gen --check". All other targets will be checked.
7174 If neither check_targets (see above) or no_check_targets is specified, all
7175 targets will be checked. It is an error to specify both check_targets and
7176 no_check_targets.
Brett Wilson796ed472018-07-16 15:11:09 -07007177
7178 The format of this list is identical to that of "visibility" so see "gn
7179 help visibility" for examples.
7180
James Robinson49f59032020-01-08 14:05:51 -08007181 check_system_includes [optional]
7182 Boolean to control whether system style includes are checked by default
7183 when running "gn check" or "gn gen --check". System style includes are
7184 includes that use angle brackets <> instead of double quotes "". If this
7185 setting is omitted or set to false, these includes will be ignored by
7186 default. They can be checked explicitly by running
7187 "gn check --check-system" or "gn gen --check=system"
7188
Brett Wilson796ed472018-07-16 15:11:09 -07007189 exec_script_whitelist [optional]
7190 A list of .gn/.gni files (not labels) that have permission to call the
7191 exec_script function. If this list is defined, calls to exec_script will
7192 be checked against this list and GN will fail if the current file isn't
7193 in the list.
7194
7195 This is to allow the use of exec_script to be restricted since is easy to
7196 use inappropriately. Wildcards are not supported. Files in the
7197 secondary_source tree (if defined) should be referenced by ignoring the
7198 secondary tree and naming them as if they are in the main tree.
7199
7200 If unspecified, the ability to call exec_script is unrestricted.
7201
7202 Example:
7203 exec_script_whitelist = [
7204 "//base/BUILD.gn",
7205 "//build/my_config.gni",
7206 ]
7207
Brett Wilson1da84bb2022-09-14 15:35:29 -07007208 export_compile_commands [optional]
7209 A list of label patterns for which to generate a Clang compilation
7210 database (see "gn help label_pattern" for the string format).
7211
7212 When specified, GN will generate a compile_commands.json file in the root
7213 of the build directory containing information on how to compile each
7214 source file reachable from any label matching any pattern in the list.
7215 This is used for Clang-based tooling and some editor integration. See
7216 https://clang.llvm.org/docs/JSONCompilationDatabase.html
7217
7218 The switch --add-export-compile-commands to "gn gen" (see "gn help gen")
7219 appends to this value which provides a per-user way to customize it.
7220
7221 The deprecated switch --export-compile-commands to "gn gen" (see "gn help
7222 gen") adds to the export target list using a different format.
7223
7224 Example:
7225 export_compile_commands = [
7226 "//base/*",
7227 "//tools:doom_melon",
7228 ]
7229
Brett Wilson796ed472018-07-16 15:11:09 -07007230 root [optional]
7231 Label of the root build target. The GN build will start by loading the
7232 build file containing this target name. This defaults to "//:" which will
Harley Li0a9affb2020-06-03 10:38:42 -04007233 cause the file //BUILD.gn to be loaded. Note that build_file_extension
7234 applies to the default case as well.
Brett Wilson796ed472018-07-16 15:11:09 -07007235
Nico Weberad9eab22020-11-15 22:20:28 -05007236 The command-line switch --root-target will override this value (see "gn
7237 help --root-target").
7238
David 'Digit' Turnerb8562a42023-10-23 18:05:37 +02007239 root_patterns [optional]
7240 A list of label pattern strings. When not defined or empty, the GN build
7241 graph will contain all targets from any BUILD.gn evaluated in the default
7242 toolchain context, and their transitive dependencies.
7243
7244 When set to a non empty list, only the targets in the default toolchain
7245 matching these patterns, and their transitive dependencies, will be defined
7246 instead.
7247
7248 The command-line switch --root-pattern will override this value (see
7249 "gn help --root-pattern")
7250
Brett Wilson796ed472018-07-16 15:11:09 -07007251 script_executable [optional]
Brett Wilsond0f8bc92022-04-22 14:01:40 -07007252 By default, GN runs the scripts used in action targets and exec_script
7253 calls using the Python interpreter found in PATH. This value specifies the
7254 Python executable or other interpreter to use instead.
James Robinson61377e32020-02-13 15:20:07 -08007255
Brett Wilsond0f8bc92022-04-22 14:01:40 -07007256 If set to the empty string, the scripts will be executed directly.
7257
7258 The command-line switch --script-executable will override this value (see
7259 "gn help --script-executable")
Brett Wilson796ed472018-07-16 15:11:09 -07007260
7261 secondary_source [optional]
7262 Label of an alternate directory tree to find input files. When searching
7263 for a BUILD.gn file (or the build config file discussed above), the file
7264 will first be looked for in the source root. If it's not found, the
7265 secondary source root will be checked (which would contain a parallel
7266 directory hierarchy).
7267
7268 This behavior is intended to be used when BUILD.gn files can't be checked
7269 in to certain source directories for whatever reason.
7270
7271 The secondary source root must be inside the main source tree.
7272
7273 default_args [optional]
7274 Scope containing the default overrides for declared arguments. These
7275 overrides take precedence over the default values specified in the
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01007276 declare_args() block, but can be overridden using --args or the
Brett Wilson796ed472018-07-16 15:11:09 -07007277 args.gn file.
7278
7279 This is intended to be used when subprojects declare arguments with
7280 default values that need to be changed for whatever reason.
Harley Li0a9affb2020-06-03 10:38:42 -04007281
7282 build_file_extension [optional]
7283 If set to a non-empty string, this is added to the name of all build files
7284 to load.
7285 GN will look for build files named "BUILD.$build_file_extension.gn".
7286 This is intended to be used during migrations or other situations where
7287 there are two independent GN builds in the same directories.
Petr Hosek317fdc12020-05-28 10:23:42 -07007288
7289 ninja_required_version [optional]
7290 When set specifies the minimum required version of Ninja. The default
7291 required version is 1.7.2. Specifying a higher version might enable the
7292 use of some of newer features that can make the build more efficient.
Brett Wilson796ed472018-07-16 15:11:09 -07007293```
7294
7295#### **Example .gn file contents**
7296
7297```
7298 buildconfig = "//build/config/BUILDCONFIG.gn"
7299
7300 check_targets = [
7301 "//doom_melon/*", # Check everything in this subtree.
7302 "//tools:mind_controlling_ant", # Check this specific target.
7303 ]
7304
7305 root = "//:root"
7306
7307 secondary_source = "//build/config/temporary_buildfiles/"
7308
7309 default_args = {
7310 # Default to release builds for this project.
7311 is_debug = false
7312 is_component_build = false
7313 }
7314```
[email protected]449f3e42024-08-01 21:43:27 +08007315### **Build graph and execution overview** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007316
7317#### **Overall build flow**
7318
7319```
7320 1. Look for ".gn" file (see "gn help dotfile") in the current directory and
7321 walk up the directory tree until one is found. Set this directory to be
7322 the "source root" and interpret this file to find the name of the build
7323 config file.
7324
7325 2. Execute the build config file identified by .gn to set up the global
7326 variables and default toolchain name. Any arguments, variables, defaults,
7327 etc. set up in this file will be visible to all files in the build.
7328
7329 3. Load the //BUILD.gn (in the source root directory).
7330
7331 4. Recursively evaluate rules and load BUILD.gn in other directories as
7332 necessary to resolve dependencies. If a BUILD file isn't found in the
7333 specified location, GN will look in the corresponding location inside
7334 the secondary_source defined in the dotfile (see "gn help dotfile").
7335
7336 5. When a target's dependencies are resolved, write out the `.ninja`
7337 file to disk.
7338
7339 6. When all targets are resolved, write out the root build.ninja file.
Harley Li0a9affb2020-06-03 10:38:42 -04007340
7341 Note that the BUILD.gn file name may be modulated by .gn arguments such as
7342 build_file_extension.
Brett Wilson796ed472018-07-16 15:11:09 -07007343```
7344
7345#### **Executing target definitions and templates**
7346
7347```
7348 Build files are loaded in parallel. This means it is impossible to
7349 interrogate a target from GN code for any information not derivable from its
7350 label (see "gn help label"). The exception is the get_target_outputs()
7351 function which requires the target being interrogated to have been defined
7352 previously in the same file.
7353
7354 Targets are declared by their type and given a name:
7355
7356 static_library("my_static_library") {
7357 ... target parameter definitions ...
7358 }
7359
7360 There is also a generic "target" function for programmatically defined types
7361 (see "gn help target"). You can define new types using templates (see "gn
7362 help template"). A template defines some custom code that expands to one or
7363 more other targets.
7364
7365 Before executing the code inside the target's { }, the target defaults are
7366 applied (see "gn help set_defaults"). It will inject implicit variable
7367 definitions that can be overridden by the target code as necessary. Typically
7368 this mechanism is used to inject a default set of configs that define the
7369 global compiler and linker flags.
7370```
7371
7372#### **Which targets are built**
7373
7374```
7375 All targets encountered in the default toolchain (see "gn help toolchain")
7376 will have build rules generated for them, even if no other targets reference
7377 them. Their dependencies must resolve and they will be added to the implicit
7378 "all" rule (see "gn help ninja_rules").
7379
7380 Targets in non-default toolchains will only be generated when they are
7381 required (directly or transitively) to build a target in the default
7382 toolchain.
7383
Tyler Mandry4a648092022-02-15 19:47:09 +00007384 Some targets might be associated but without a formal build dependency (for
7385 example, related tools or optional variants). A target that is marked as
7386 "generated" can propagate its generated state to an associated target using
7387 "gen_deps". This will make the referenced dependency have Ninja rules
7388 generated in the same cases the source target has but without a build-time
7389 dependency and even in non-default toolchains.
7390
Brett Wilson796ed472018-07-16 15:11:09 -07007391 See also "gn help ninja_rules".
7392```
7393
7394#### **Dependencies**
7395
7396```
7397 The only difference between "public_deps" and "deps" except for pushing
7398 configs around the build tree and allowing includes for the purposes of "gn
7399 check".
7400
7401 A target's "data_deps" are guaranteed to be built whenever the target is
7402 built, but the ordering is not defined. The meaning of this is dependencies
7403 required at runtime. Currently data deps will be complete before the target
7404 is linked, but this is not semantically guaranteed and this is undesirable
7405 from a build performance perspective. Since we hope to change this in the
7406 future, do not rely on this behavior.
7407```
[email protected]449f3e42024-08-01 21:43:27 +08007408### **Language and grammar for GN build files** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007409
7410#### **Tokens**
7411
7412```
7413 GN build files are read as sequences of tokens. While splitting the file
7414 into tokens, the next token is the longest sequence of characters that form a
7415 valid token.
7416```
7417
7418#### **White space and comments**
7419
7420```
7421 White space is comprised of spaces (U+0020), horizontal tabs (U+0009),
7422 carriage returns (U+000D), and newlines (U+000A).
7423
7424 Comments start at the character "#" and stop at the next newline.
7425
7426 White space and comments are ignored except that they may separate tokens
7427 that would otherwise combine into a single token.
7428```
7429
7430#### **Identifiers**
7431
7432```
7433 Identifiers name variables and functions.
7434
7435 identifier = letter { letter | digit } .
7436 letter = "A" ... "Z" | "a" ... "z" | "_" .
7437 digit = "0" ... "9" .
7438```
7439
7440#### **Keywords**
7441
7442```
7443 The following keywords are reserved and may not be used as identifiers:
7444
7445 else false if true
7446```
7447
7448#### **Integer literals**
7449
7450```
7451 An integer literal represents a decimal integer value.
7452
7453 integer = [ "-" ] digit { digit } .
7454
7455 Leading zeros and negative zero are disallowed.
7456```
7457
7458#### **String literals**
7459
7460```
7461 A string literal represents a string value consisting of the quoted
7462 characters with possible escape sequences and variable expansions.
7463
7464 string = `"` { char | escape | expansion } `"` .
7465 escape = `\` ( "$" | `"` | char ) .
Nico Weberad9eab22020-11-15 22:20:28 -05007466 BracketExpansion = "{" ( identifier | ArrayAccess | ScopeAccess ) "}" .
Brett Wilson796ed472018-07-16 15:11:09 -07007467 Hex = "0x" [0-9A-Fa-f][0-9A-Fa-f]
7468 expansion = "$" ( identifier | BracketExpansion | Hex ) .
Nico Weberad9eab22020-11-15 22:20:28 -05007469 char = /* any character except "$", `"`, or newline */ .
Brett Wilson796ed472018-07-16 15:11:09 -07007470
7471 After a backslash, certain sequences represent special characters:
7472
7473 \" U+0022 quotation mark
7474 \$ U+0024 dollar sign
7475 \\ U+005C backslash
7476
7477 All other backslashes represent themselves.
7478
7479 To insert an arbitrary byte value, use $0xFF. For example, to insert a
7480 newline character: "Line one$0x0ALine two".
7481
7482 An expansion will evaluate the variable following the '$' and insert a
7483 stringified version of it into the result. For example, to concat two path
7484 components with a slash separating them:
7485 "$var_one/$var_two"
7486 Use the "${var_one}" format to be explicitly deliniate the variable for
7487 otherwise-ambiguous cases.
7488```
7489
7490#### **Punctuation**
7491
7492```
7493 The following character sequences represent punctuation:
7494
7495 + += == != ( )
7496 - -= < <= [ ]
7497 ! = > >= { }
7498 && || . ,
7499```
7500
7501#### **Grammar**
7502
7503```
7504 The input tokens form a syntax tree following a context-free grammar:
7505
7506 File = StatementList .
7507
7508 Statement = Assignment | Call | Condition .
7509 LValue = identifier | ArrayAccess | ScopeAccess .
7510 Assignment = LValue AssignOp Expr .
7511 Call = identifier "(" [ ExprList ] ")" [ Block ] .
7512 Condition = "if" "(" Expr ")" Block
7513 [ "else" ( Condition | Block ) ] .
7514 Block = "{" StatementList "}" .
7515 StatementList = { Statement } .
7516
7517 ArrayAccess = identifier "[" Expr "]" .
7518 ScopeAccess = identifier "." identifier .
7519 Expr = UnaryExpr | Expr BinaryOp Expr .
7520 UnaryExpr = PrimaryExpr | UnaryOp UnaryExpr .
7521 PrimaryExpr = identifier | integer | string | Call
7522 | ArrayAccess | ScopeAccess | Block
7523 | "(" Expr ")"
7524 | "[" [ ExprList [ "," ] ] "]" .
7525 ExprList = Expr { "," Expr } .
7526
7527 AssignOp = "=" | "+=" | "-=" .
7528 UnaryOp = "!" .
7529 BinaryOp = "+" | "-" // highest priority
7530 | "<" | "<=" | ">" | ">="
7531 | "==" | "!="
7532 | "&&"
7533 | "||" . // lowest priority
7534
7535 All binary operators are left-associative.
7536```
7537
7538#### **Types**
7539
7540```
7541 The GN language is dynamically typed. The following types are used:
7542
7543 - Boolean: Uses the keywords "true" and "false". There is no implicit
7544 conversion between booleans and integers.
7545
7546 - Integers: All numbers in GN are signed 64-bit integers.
7547
7548 - Strings: Strings are 8-bit with no enforced encoding. When a string is
7549 used to interact with other systems with particular encodings (like the
7550 Windows and Mac filesystems) it is assumed to be UTF-8. See "String
7551 literals" above for more.
7552
7553 - Lists: Lists are arbitrary-length ordered lists of values. See "Lists"
7554 below for more.
7555
7556 - Scopes: Scopes are like dictionaries that use variable names for keys. See
7557 "Scopes" below for more.
7558```
7559
7560#### **Lists**
7561
7562```
7563 Lists are created with [] and using commas to separate items:
7564
7565 mylist = [ 0, 1, 2, "some string" ]
7566
7567 A comma after the last item is optional. Lists are dereferenced using 0-based
7568 indexing:
7569
7570 mylist[0] += 1
7571 var = mylist[2]
7572
7573 Lists can be concatenated using the '+' and '+=' operators. Bare values can
7574 not be concatenated with lists, to add a single item, it must be put into a
7575 list of length one.
7576
7577 Items can be removed from lists using the '-' and '-=' operators. This will
7578 remove all occurrences of every item in the right-hand list from the
7579 left-hand list. It is an error to remove an item not in the list. This is to
7580 prevent common typos and to detect dead code that is removing things that no
7581 longer apply.
7582
7583 It is an error to use '=' to replace a nonempty list with another nonempty
7584 list. This is to prevent accidentally overwriting data when in most cases
7585 '+=' was intended. To overwrite a list on purpose, first assign it to the
7586 empty list:
7587
7588 mylist = []
7589 mylist = otherlist
Brett Wilson796ed472018-07-16 15:11:09 -07007590```
7591
7592#### **Scopes**
7593
7594```
7595 All execution happens in the context of a scope which holds the current state
7596 (like variables). With the exception of loops and conditions, '{' introduces
Tyler Mandry4a648092022-02-15 19:47:09 +00007597 a new scope.
Brett Wilson796ed472018-07-16 15:11:09 -07007598
Tyler Mandry4a648092022-02-15 19:47:09 +00007599 Most scopes have a parent reference to the old scope. Variable reads
7600 recursively search all parent scopes until the variable is found or there are
7601 no more scopes. Variable writes always go into the current scope. This means
7602 that after the closing '}' (again excepting loops and conditions), all local
7603 variables will be restored to the previous values. This also means that "foo
7604 = foo" can do useful work by copying a variable into the current scope that
7605 was defined in a containing scope.
Brett Wilson796ed472018-07-16 15:11:09 -07007606
Tyler Mandry4a648092022-02-15 19:47:09 +00007607 Scopes can be assigned to variables. Examples of such scopes are the
7608 implicitly-created "invoker" when invoking a template (which refers to the
7609 variables set by the invoking code), scopes created by functions like
7610 exec_script, and scopes explicitly created like
Brett Wilson796ed472018-07-16 15:11:09 -07007611
7612 empty_scope = {}
7613 myvalues = {
7614 foo = 21
7615 bar = "something"
7616 }
7617
Tyler Mandry4a648092022-02-15 19:47:09 +00007618 In the case of explicitly created scopes and scopes created by functions like
7619 exec_script, there is no reference to the parent scope. Such scopes are fully
7620 self-contained and do not "inherit" values from their defining scope.
7621
7622 Inside an explicit scope definition can be any GN code including conditionals
7623 and function calls. After the close of the scope, it will contain all
7624 variables explicitly set by the code contained inside it. After this, the
7625 values can be read, modified, or added to:
Brett Wilson796ed472018-07-16 15:11:09 -07007626
7627 myvalues.foo += 2
7628 empty_scope.new_thing = [ 1, 2, 3 ]
Nate Fischer8ed01d32019-01-08 17:32:01 -08007629
7630 Scope equality is defined as single-level scopes identical within the current
7631 scope. That is, all values in the first scope must be present and identical
7632 within the second, and vice versa. Note that this means inherited scopes are
7633 always unequal by definition.
Brett Wilson796ed472018-07-16 15:11:09 -07007634```
[email protected]449f3e42024-08-01 21:43:27 +08007635### **Input and output conversion** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007636
7637```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007638 Input and output conversions are arguments to file and process functions
7639 that specify how to convert data to or from external formats. The possible
7640 values for parameters specifying conversions are:
7641
Brett Wilson796ed472018-07-16 15:11:09 -07007642 "" (the default)
Julie Hockett09171292018-07-31 14:35:10 -07007643 input: Discard the result and return None.
7644
7645 output: If value is a list, then "list lines"; otherwise "value".
Brett Wilson796ed472018-07-16 15:11:09 -07007646
7647 "list lines"
Julie Hockett09171292018-07-31 14:35:10 -07007648 input:
7649 Return the file contents as a list, with a string for each line. The
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007650 newlines will not be present in the result. The last line may or may
7651 not end in a newline.
Brett Wilson796ed472018-07-16 15:11:09 -07007652
Julie Hockett09171292018-07-31 14:35:10 -07007653 After splitting, each individual line will be trimmed of whitespace on
7654 both ends.
7655
7656 output:
7657 Renders the value contents as a list, with a string for each line. The
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007658 newlines will not be present in the result. The last line will end in
7659 with a newline.
Brett Wilson796ed472018-07-16 15:11:09 -07007660
7661 "scope"
Julie Hockett09171292018-07-31 14:35:10 -07007662 input:
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007663 Execute the block as GN code and return a scope with the resulting
7664 values in it. If the input was:
Julie Hockett09171292018-07-31 14:35:10 -07007665 a = [ "hello.cc", "world.cc" ]
7666 b = 26
7667 and you read the result into a variable named "val", then you could
7668 access contents the "." operator on "val":
7669 sources = val.a
7670 some_count = val.b
7671
7672 output:
7673 Renders the value contents as a GN code block, reversing the input
7674 result above.
Brett Wilson796ed472018-07-16 15:11:09 -07007675
7676 "string"
Julie Hockett09171292018-07-31 14:35:10 -07007677 input: Return the file contents into a single string.
7678
7679 output:
7680 Render the value contents into a single string. The output is:
7681 a string renders with quotes, e.g. "str"
7682 an integer renders as a stringified integer, e.g. "6"
7683 a boolean renders as the associated string, e.g. "true"
7684 a list renders as a representation of its contents, e.g. "[\"str\", 6]"
7685 a scope renders as a GN code block of its values. If the Value was:
7686 Value val;
7687 val.a = [ "hello.cc", "world.cc" ];
7688 val.b = 26
7689 the resulting output would be:
7690 "{
7691 a = [ \"hello.cc\", \"world.cc\" ]
7692 b = 26
7693 }"
Brett Wilson796ed472018-07-16 15:11:09 -07007694
7695 "value"
Julie Hockett09171292018-07-31 14:35:10 -07007696 input:
7697 Parse the input as if it was a literal rvalue in a buildfile. Examples of
7698 typical program output using this mode:
7699 [ "foo", "bar" ] (result will be a list)
7700 or
7701 "foo bar" (result will be a string)
7702 or
7703 5 (result will be an integer)
Brett Wilson796ed472018-07-16 15:11:09 -07007704
Julie Hockett09171292018-07-31 14:35:10 -07007705 Note that if the input is empty, the result will be a null value which
7706 will produce an error if assigned to a variable.
7707
7708 output:
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007709 Render the value contents as a literal rvalue. Strings render with
7710 escaped quotes.
Brett Wilson796ed472018-07-16 15:11:09 -07007711
7712 "json"
Julie Hockett09171292018-07-31 14:35:10 -07007713 input: Parse the input as a JSON and convert it to equivalent GN rvalue.
7714
7715 output: Convert the Value to equivalent JSON value.
7716
7717 The data type mapping is:
Brett Wilson796ed472018-07-16 15:11:09 -07007718 a string in JSON maps to string in GN
7719 an integer in JSON maps to integer in GN
7720 a float in JSON is unsupported and will result in an error
7721 an object in JSON maps to scope in GN
7722 an array in JSON maps to list in GN
7723 a boolean in JSON maps to boolean in GN
7724 a null in JSON is unsupported and will result in an error
7725
Julie Hockett09171292018-07-31 14:35:10 -07007726 Nota that the input dictionary keys have to be valid GN identifiers
7727 otherwise they will produce an error.
Brett Wilson796ed472018-07-16 15:11:09 -07007728
Julie Hockett09171292018-07-31 14:35:10 -07007729 "trim ..." (input only)
Brett Wilson796ed472018-07-16 15:11:09 -07007730 Prefixing any of the other transformations with the word "trim" will
7731 result in whitespace being trimmed from the beginning and end of the
7732 result before processing.
7733
7734 Examples: "trim string" or "trim list lines"
7735
7736 Note that "trim value" is useless because the value parser skips
7737 whitespace anyway.
7738```
[email protected]449f3e42024-08-01 21:43:27 +08007739### **File patterns** [Back to Top](#gn-reference)
Sylvain Defresneaff489a2020-03-11 18:27:43 +01007740
7741```
7742 File patterns are VERY limited regular expressions. They must match the
7743 entire input string to be counted as a match. In regular expression parlance,
7744 there is an implicit "^...$" surrounding your input. If you want to match a
7745 substring, you need to use wildcards at the beginning and end.
7746
7747 There are only two special tokens understood by the pattern matcher.
7748 Everything else is a literal.
7749
7750 - "*" Matches zero or more of any character. It does not depend on the
7751 preceding character (in regular expression parlance it is equivalent to
7752 ".*").
7753
7754 - "\b" Matches a path boundary. This will match the beginning or end of a
7755 string, or a slash.
7756```
7757
7758#### **Pattern examples**
7759
7760```
7761 "*asdf*"
7762 Matches a string containing "asdf" anywhere.
7763
7764 "asdf"
7765 Matches only the exact string "asdf".
7766
7767 "*.cc"
7768 Matches strings ending in the literal ".cc".
7769
7770 "\bwin/*"
7771 Matches "win/foo" and "foo/win/bar.cc" but not "iwin/foo".
7772```
[email protected]449f3e42024-08-01 21:43:27 +08007773### **Label patterns** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007774
7775```
7776 A label pattern is a way of expressing one or more labels in a portion of the
7777 source tree. They are not general regular expressions.
7778
7779 They can take the following forms only:
7780
7781 - Explicit (no wildcard):
7782 "//foo/bar:baz"
7783 ":baz"
7784
7785 - Wildcard target names:
7786 "//foo/bar:*" (all targets in the //foo/bar/BUILD.gn file)
7787 ":*" (all targets in the current build file)
7788
7789 - Wildcard directory names ("*" is only supported at the end)
7790 "*" (all targets)
7791 "//foo/bar/*" (all targets in any subdir of //foo/bar)
7792 "./*" (all targets in the current build file or sub dirs)
7793
Julie Hockette2a29402018-07-31 10:11:42 -07007794 Any of the above forms can additionally take an explicit toolchain
7795 in parenthesis at the end of the label pattern. In this case, the
7796 toolchain must be fully qualified (no wildcards are supported in the
7797 toolchain name).
Brett Wilson796ed472018-07-16 15:11:09 -07007798
Julie Hockette2a29402018-07-31 10:11:42 -07007799 "//foo:bar(//build/toolchain:mac)"
Brett Wilson796ed472018-07-16 15:11:09 -07007800 An explicit target in an explicit toolchain.
7801
7802 ":*(//build/toolchain/linux:32bit)"
7803 All targets in the current build file using the 32-bit Linux toolchain.
7804
7805 "//foo/*(//build/toolchain:win)"
7806 All targets in //foo and any subdirectory using the Windows
7807 toolchain.
7808```
[email protected]449f3e42024-08-01 21:43:27 +08007809### **About labels** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007810
7811```
7812 Everything that can participate in the dependency graph (targets, configs,
7813 and toolchains) are identified by labels. A common label looks like:
7814
7815 //base/test:test_support
7816
7817 This consists of a source-root-absolute path, a colon, and a name. This means
7818 to look for the thing named "test_support" in "base/test/BUILD.gn".
7819
7820 You can also specify system absolute paths if necessary. Typically such
7821 paths would be specified via a build arg so the developer can specify where
7822 the component is on their system.
7823
7824 /usr/local/foo:bar (Posix)
7825 /C:/Program Files/MyLibs:bar (Windows)
7826```
7827
7828#### **Toolchains**
7829
7830```
7831 A canonical label includes the label of the toolchain being used. Normally,
7832 the toolchain label is implicitly inherited from the current execution
7833 context, but you can override this to specify cross-toolchain dependencies:
7834
7835 //base/test:test_support(//build/toolchain/win:msvc)
7836
7837 Here GN will look for the toolchain definition called "msvc" in the file
7838 "//build/toolchain/win" to know how to compile this target.
7839```
7840
7841#### **Relative labels**
7842
7843```
7844 If you want to refer to something in the same buildfile, you can omit
7845 the path name and just start with a colon. This format is recommended for
7846 all same-file references.
7847
7848 :base
7849
7850 Labels can be specified as being relative to the current directory.
7851 Stylistically, we prefer to use absolute paths for all non-file-local
7852 references unless a build file needs to be run in different contexts (like a
7853 project needs to be both standalone and pulled into other projects in
7854 difference places in the directory hierarchy).
7855
7856 source/plugin:myplugin
7857 ../net:url_request
7858```
7859
7860#### **Implicit names**
7861
7862```
7863 If a name is unspecified, it will inherit the directory name. Stylistically,
7864 we prefer to omit the colon and name when possible:
7865
7866 //net -> //net:net
7867 //tools/gn -> //tools/gn:gn
7868```
[email protected]449f3e42024-08-01 21:43:27 +08007869### **Metadata Collection** [Back to Top](#gn-reference)
Julie Hockett152c5142019-07-12 09:53:43 -06007870
7871```
7872 Metadata is information attached to targets throughout the dependency tree. GN
7873 allows for the collection of this data into files written during the generation
Keir Mierle45611e32019-11-12 11:18:00 -08007874 step, enabling users to expose and aggregate this data based on the dependency
Julie Hockett152c5142019-07-12 09:53:43 -06007875 tree.
7876```
7877
7878#### **generated_file targets**
7879
7880```
7881 Similar to the write_file() function, the generated_file target type
7882 creates a file in the specified location with the specified content. The
Keir Mierle45611e32019-11-12 11:18:00 -08007883 primary difference between write_file() and this target type is that the
Julie Hockett152c5142019-07-12 09:53:43 -06007884 write_file function does the file write at parse time, while the
7885 generated_file target type writes at target resolution time. See
7886 "gn help generated_file" for more detail.
7887
Keir Mierle45611e32019-11-12 11:18:00 -08007888 When written at target resolution time, generated_file enables GN to
Julie Hockett152c5142019-07-12 09:53:43 -06007889 collect and write aggregated metadata from dependents.
7890
Keir Mierle45611e32019-11-12 11:18:00 -08007891 A generated_file target can declare either 'contents' to write statically
7892 known contents to a file or 'data_keys' to aggregate metadata and write the
7893 result to a file. It can also specify 'walk_keys' (to restrict the metadata
Julie Hockett152c5142019-07-12 09:53:43 -06007894 collection), 'output_conversion', and 'rebase'.
7895```
7896
7897#### **Collection and Aggregation**
7898
7899```
7900 Targets can declare a 'metadata' variable containing a scope, and this
Keir Mierle45611e32019-11-12 11:18:00 -08007901 metadata may be collected and written out to a file specified by
7902 generated_file aggregation targets. The 'metadata' scope must contain
7903 only list values since the aggregation step collects a list of these values.
Julie Hockett152c5142019-07-12 09:53:43 -06007904
7905 During the target resolution, generated_file targets will walk their
7906 dependencies recursively, collecting metadata based on the specified
7907 'data_keys'. 'data_keys' is specified as a list of strings, used by the walk
7908 to identify which variables in dependencies' 'metadata' scopes to collect.
7909
Keir Mierle45611e32019-11-12 11:18:00 -08007910 The walk begins with the listed dependencies of the 'generated_file' target.
7911 The 'metadata' scope for each dependency is inspected for matching elements
7912 of the 'generated_file' target's 'data_keys' list. If a match is found, the
7913 data from the dependent's matching key list is appended to the aggregate walk
7914 list. Note that this means that if more than one walk key is specified, the
7915 data in all of them will be aggregated into one list. From there, the walk
7916 will then recurse into the dependencies of each target it encounters,
7917 collecting the specified metadata for each.
Julie Hockett152c5142019-07-12 09:53:43 -06007918
7919 For example:
7920
7921 group("a") {
7922 metadata = {
7923 doom_melon = [ "enable" ]
7924 my_files = [ "foo.cpp" ]
7925 my_extra_files = [ "bar.cpp" ]
7926 }
7927
7928 deps = [ ":b" ]
7929 }
7930
7931 group("b") {
7932 metadata = {
7933 my_files = [ "baz.cpp" ]
7934 }
7935 }
7936
7937 generated_file("metadata") {
7938 outputs = [ "$root_build_dir/my_files.json" ]
7939 data_keys = [ "my_files", "my_extra_files" ]
7940
7941 deps = [ ":a" ]
7942 }
7943
7944 The above will produce the following file data:
7945
7946 foo.cpp
7947 bar.cpp
7948 baz.cpp
7949
Keir Mierle45611e32019-11-12 11:18:00 -08007950 The dependency walk can be limited by using the 'walk_keys'. This is a list of
Julie Hockett152c5142019-07-12 09:53:43 -06007951 labels that should be included in the walk. All labels specified here should
7952 also be in one of the deps lists. These keys act as barriers, where the walk
Keir Mierle45611e32019-11-12 11:18:00 -08007953 will only recurse into the targets listed. An empty list in all specified
Julie Hockett152c5142019-07-12 09:53:43 -06007954 barriers will end that portion of the walk.
7955
7956 group("a") {
7957 metadata = {
7958 my_files = [ "foo.cpp" ]
Sylvain Defresne3028c6a2020-07-20 11:28:59 +02007959 my_files_barrier = [ ":b" ]
Julie Hockett152c5142019-07-12 09:53:43 -06007960 }
7961
7962 deps = [ ":b", ":c" ]
7963 }
7964
7965 group("b") {
7966 metadata = {
7967 my_files = [ "bar.cpp" ]
7968 }
7969 }
7970
7971 group("c") {
7972 metadata = {
7973 my_files = [ "doom_melon.cpp" ]
7974 }
7975 }
7976
7977 generated_file("metadata") {
7978 outputs = [ "$root_build_dir/my_files.json" ]
Sylvain Defresne3028c6a2020-07-20 11:28:59 +02007979 data_keys = [ "my_files" ]
7980 walk_keys = [ "my_files_barrier" ]
Julie Hockett152c5142019-07-12 09:53:43 -06007981
7982 deps = [ ":a" ]
7983 }
7984
7985 The above will produce the following file data (note that `doom_melon.cpp` is
7986 not included):
7987
7988 foo.cpp
7989 bar.cpp
7990
7991 A common example of this sort of barrier is in builds that have host tools
7992 built as part of the tree, but do not want the metadata from those host tools
7993 to be collected with the target-side code.
7994```
7995
7996#### **Common Uses**
7997
7998```
7999 Metadata can be used to collect information about the different targets in the
8000 build, and so a common use is to provide post-build tooling with a set of data
8001 necessary to do aggregation tasks. For example, if each test target specifies
8002 the output location of its binary to run in a metadata field, that can be
8003 collected into a single file listing the locations of all tests in the
8004 dependency tree. A local build tool (or continuous integration infrastructure)
8005 can then use that file to know which tests exist, and where, and run them
8006 accordingly.
8007
8008 Another use is in image creation, where a post-build image tool needs to know
8009 various pieces of information about the components it should include in order
8010 to put together the correct image.
8011```
[email protected]449f3e42024-08-01 21:43:27 +08008012### **Ninja build rules** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008013
8014#### **The "all" and "default" rules**
8015
8016```
8017 All generated targets (see "gn help execution") will be added to an implicit
8018 build rule called "all" so "ninja all" will always compile everything. The
8019 default rule will be used by Ninja if no specific target is specified (just
8020 typing "ninja"). If there is a target named "default" in the root build file,
8021 it will be the default build rule, otherwise the implicit "all" rule will be
8022 used.
8023```
8024
8025#### **Phony rules**
8026
8027```
8028 GN generates Ninja "phony" rules for targets in the default toolchain. The
8029 phony rules can collide with each other and with the names of generated files
8030 so are generated with the following priority:
8031
8032 1. Actual files generated by the build always take precedence.
8033
8034 2. Targets in the toplevel //BUILD.gn file.
8035
8036 3. Targets in toplevel directories matching the names of the directories.
8037 So "ninja foo" can be used to compile "//foo:foo". This only applies to
8038 the first level of directories since usually these are the most
8039 important (so this won't apply to "//foo/bar:bar").
8040
8041 4. The short names of executables if there is only one executable with that
8042 short name. Use "ninja doom_melon" to compile the
8043 "//tools/fruit:doom_melon" executable.
8044
Sylvain Defresne5e19d2f2022-12-12 18:20:36 +01008045 Note that for Apple platforms, create_bundle targets with a product_type
8046 of "com.apple.product-type.application" are considered as executable
8047 for this rule (as they define application bundles).
8048
Brett Wilson796ed472018-07-16 15:11:09 -07008049 5. The short names of all targets if there is only one target with that
8050 short name.
8051
8052 6. Full label name with no leading slashes. So you can use
8053 "ninja tools/fruit:doom_melon" to build "//tools/fruit:doom_melon".
8054
8055 7. Labels with an implicit name part (when the short names match the
8056 directory). So you can use "ninja foo/bar" to compile "//foo/bar:bar".
8057
8058 These "phony" rules are provided only for running Ninja since this matches
8059 people's historical expectations for building. For consistency with the rest
8060 of the program, GN introspection commands accept explicit labels.
8061
8062 To explicitly compile a target in a non-default toolchain, you must give
8063 Ninja the exact name of the output file relative to the build directory.
8064```
[email protected]449f3e42024-08-01 21:43:27 +08008065### **nogncheck**: Skip an include line from checking. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008066
8067```
8068 GN's header checker helps validate that the includes match the build
8069 dependency graph. Sometimes an include might be conditional or otherwise
8070 problematic, but you want to specifically allow it. In this case, it can be
8071 whitelisted.
8072
8073 Include lines containing the substring "nogncheck" will be excluded from
8074 header checking. The most common case is a conditional include:
8075
8076 #if defined(ENABLE_DOOM_MELON)
8077 #include "tools/doom_melon/doom_melon.h" // nogncheck
8078 #endif
8079
8080 If the build file has a conditional dependency on the corresponding target
8081 that matches the conditional include, everything will always link correctly:
8082
8083 source_set("mytarget") {
8084 ...
8085 if (enable_doom_melon) {
8086 defines = [ "ENABLE_DOOM_MELON" ]
8087 deps += [ "//tools/doom_melon" ]
8088 }
8089
8090 But GN's header checker does not understand preprocessor directives, won't
8091 know it matches the build dependencies, and will flag this include as
8092 incorrect when the condition is false.
8093```
8094
8095#### **More information**
8096
8097```
8098 The topic "gn help check" has general information on how checking works and
8099 advice on fixing problems. Targets can also opt-out of checking, see
8100 "gn help check_includes".
8101```
[email protected]449f3e42024-08-01 21:43:27 +08008102### **Runtime dependencies** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008103
8104```
8105 Runtime dependencies of a target are exposed via the "runtime_deps" category
8106 of "gn desc" (see "gn help desc") or they can be written at build generation
8107 time via write_runtime_deps(), or --runtime-deps-list-file (see "gn help
8108 --runtime-deps-list-file").
8109
8110 To a first approximation, the runtime dependencies of a target are the set of
8111 "data" files, data directories, and the shared libraries from all transitive
8112 dependencies. Executables, shared libraries, and loadable modules are
8113 considered runtime dependencies of themselves.
8114```
8115
8116#### **Executables**
8117
8118```
8119 Executable targets and those executable targets' transitive dependencies are
8120 not considered unless that executable is listed in "data_deps". Otherwise, GN
8121 assumes that the executable (and everything it requires) is a build-time
8122 dependency only.
8123```
8124
8125#### **Actions and copies**
8126
8127```
8128 Action and copy targets that are listed as "data_deps" will have all of their
8129 outputs and data files considered as runtime dependencies. Action and copy
8130 targets that are "deps" or "public_deps" will have only their data files
8131 considered as runtime dependencies. These targets can list an output file in
8132 both the "outputs" and "data" lists to force an output file as a runtime
8133 dependency in all cases.
8134
8135 The different rules for deps and data_deps are to express build-time (deps)
8136 vs. run-time (data_deps) outputs. If GN counted all build-time copy steps as
8137 data dependencies, there would be a lot of extra stuff, and if GN counted all
8138 run-time dependencies as regular deps, the build's parallelism would be
8139 unnecessarily constrained.
8140
8141 This rule can sometimes lead to unintuitive results. For example, given the
8142 three targets:
8143 A --[data_deps]--> B --[deps]--> ACTION
8144 GN would say that A does not have runtime deps on the result of the ACTION,
8145 which is often correct. But the purpose of the B target might be to collect
8146 many actions into one logic unit, and the "data"-ness of A's dependency is
8147 lost. Solutions:
8148
8149 - List the outputs of the action in its data section (if the results of
8150 that action are always runtime files).
8151 - Have B list the action in data_deps (if the outputs of the actions are
8152 always runtime files).
8153 - Have B list the action in both deps and data deps (if the outputs might be
8154 used in both contexts and you don't care about unnecessary entries in the
8155 list of files required at runtime).
8156 - Split B into run-time and build-time versions with the appropriate "deps"
8157 for each.
8158```
8159
8160#### **Static libraries and source sets**
8161
8162```
8163 The results of static_library or source_set targets are not considered
8164 runtime dependencies since these are assumed to be intermediate targets only.
8165 If you need to list a static library as a runtime dependency, you can
8166 manually compute the .a/.lib file name for the current platform and list it
8167 in the "data" list of a target (possibly on the static library target
8168 itself).
8169```
8170
8171#### **Multiple outputs**
8172
8173```
8174 Linker tools can specify which of their outputs should be considered when
8175 computing the runtime deps by setting runtime_outputs. If this is unset on
8176 the tool, the default will be the first output only.
8177```
[email protected]449f3e42024-08-01 21:43:27 +08008178### **How Source Expansion Works** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008179
8180```
8181 Source expansion is used for the action_foreach and copy target types to map
8182 source file names to output file names or arguments.
8183
8184 To perform source expansion in the outputs, GN maps every entry in the
8185 sources to every entry in the outputs list, producing the cross product of
8186 all combinations, expanding placeholders (see below).
8187
8188 Source expansion in the args works similarly, but performing the placeholder
8189 substitution produces a different set of arguments for each invocation of the
8190 script.
8191
8192 If no placeholders are found, the outputs or args list will be treated as a
8193 static list of literal file names that do not depend on the sources.
8194
8195 See "gn help copy" and "gn help action_foreach" for more on how this is
8196 applied.
8197```
8198
8199#### **Placeholders**
8200
8201```
8202 This section discusses only placeholders for actions. There are other
8203 placeholders used in the definition of tools. See "gn help tool" for those.
8204
8205 {{source}}
8206 The name of the source file including directory (*). This will generally
8207 be used for specifying inputs to a script in the "args" variable.
8208 "//foo/bar/baz.txt" => "../../foo/bar/baz.txt"
8209
8210 {{source_file_part}}
8211 The file part of the source including the extension.
8212 "//foo/bar/baz.txt" => "baz.txt"
8213
8214 {{source_name_part}}
8215 The filename part of the source file with no directory or extension. This
8216 will generally be used for specifying a transformation from a source file
8217 to a destination file with the same name but different extension.
8218 "//foo/bar/baz.txt" => "baz"
8219
8220 {{source_dir}}
8221 The directory (*) containing the source file with no trailing slash.
8222 "//foo/bar/baz.txt" => "../../foo/bar"
8223
8224 {{source_root_relative_dir}}
8225 The path to the source file's directory relative to the source root, with
8226 no leading "//" or trailing slashes. If the path is system-absolute,
8227 (beginning in a single slash) this will just return the path with no
8228 trailing slash. This value will always be the same, regardless of whether
8229 it appears in the "outputs" or "args" section.
8230 "//foo/bar/baz.txt" => "foo/bar"
8231
8232 {{source_gen_dir}}
8233 The generated file directory (*) corresponding to the source file's path.
8234 This will be different than the target's generated file directory if the
8235 source file is in a different directory than the BUILD.gn file.
8236 "//foo/bar/baz.txt" => "gen/foo/bar"
8237
8238 {{source_out_dir}}
8239 The object file directory (*) corresponding to the source file's path,
8240 relative to the build directory. this us be different than the target's
8241 out directory if the source file is in a different directory than the
8242 build.gn file.
8243 "//foo/bar/baz.txt" => "obj/foo/bar"
8244
8245 {{source_target_relative}}
8246 The path to the source file relative to the target's directory. This will
8247 generally be used for replicating the source directory layout in the
Robert Sesek252674d2019-05-10 14:08:52 -04008248 output directory. This can only be used in actions and bundle_data
8249 targets. It is an error to use in process_file_template where there is no
8250 "target".
Brett Wilson796ed472018-07-16 15:11:09 -07008251 "//foo/bar/baz.txt" => "baz.txt"
8252```
8253
8254#### **(*) Note on directories**
8255
8256```
8257 Paths containing directories (except the source_root_relative_dir) will be
8258 different depending on what context the expansion is evaluated in. Generally
8259 it should "just work" but it means you can't concatenate strings containing
8260 these values with reasonable results.
8261
8262 Details: source expansions can be used in the "outputs" variable, the "args"
8263 variable, and in calls to "process_file_template". The "args" are passed to a
8264 script which is run from the build directory, so these directories will
8265 relative to the build directory for the script to find. In the other cases,
8266 the directories will be source- absolute (begin with a "//") because the
8267 results of those expansions will be handled by GN internally.
8268```
8269
8270#### **Examples**
8271
8272```
8273 Non-varying outputs:
8274 action("hardcoded_outputs") {
8275 sources = [ "input1.idl", "input2.idl" ]
8276 outputs = [ "$target_out_dir/output1.dat",
8277 "$target_out_dir/output2.dat" ]
8278 }
8279 The outputs in this case will be the two literal files given.
8280
8281 Varying outputs:
8282 action_foreach("varying_outputs") {
8283 sources = [ "input1.idl", "input2.idl" ]
8284 outputs = [ "{{source_gen_dir}}/{{source_name_part}}.h",
8285 "{{source_gen_dir}}/{{source_name_part}}.cc" ]
8286 }
8287 Performing source expansion will result in the following output names:
8288 //out/Debug/obj/mydirectory/input1.h
8289 //out/Debug/obj/mydirectory/input1.cc
8290 //out/Debug/obj/mydirectory/input2.h
8291 //out/Debug/obj/mydirectory/input2.cc
8292```
[email protected]449f3e42024-08-01 21:43:27 +08008293### **Available global switches** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008294
8295```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08008296 Do "gn help --the_switch_you_want_help_on" for more. Individual commands may
8297 take command-specific switches not listed here. See the help on your specific
8298 command for more.
8299```
8300```
8301 * --args: Specifies build arguments overrides.
8302 * --color: Force colored output.
8303 * --dotfile: Override the name of the ".gn" file.
8304 * --fail-on-unused-args: Treat unused build args as fatal errors.
8305 * --markdown: Write help output in the Markdown format.
RJ Ascani6966efb2020-10-19 16:50:11 -07008306 * --ninja-executable: Set the Ninja executable.
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08008307 * --nocolor: Force non-colored output.
8308 * -q: Quiet mode. Don't print output on success.
8309 * --root: Explicitly specify source root.
Nico Weberad9eab22020-11-15 22:20:28 -05008310 * --root-target: Override the root target.
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08008311 * --runtime-deps-list-file: Save runtime dependencies for targets in file.
8312 * --script-executable: Set the executable used to execute scripts.
8313 * --threads: Specify number of worker threads.
8314 * --time: Outputs a summary of how long everything took.
8315 * --tracelog: Writes a Chrome-compatible trace log to the given file.
8316 * -v: Verbose logging.
8317 * --version: Prints the GN version number and exits.
Brett Wilson796ed472018-07-16 15:11:09 -07008318```
8319