blob: f2e6c42ef54ef316ede724af4bc9d6eb117e434c [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
Brett Wilson225e90c2024-08-09 10:17:48 -07001957 Generated file: contents, data_keys, rebase, walk_keys, output_conversion,
1958 outputs
Brett Wilsond0f8bc92022-04-22 14:01:40 -07001959```
1960
Nate Fischer8ed01d32019-01-08 17:32:01 -08001961#### **Example (metadata collection)**
1962
1963```
1964 Given the following targets defined in //base/BUILD.gn, where A depends on B
1965 and B depends on C and D:
1966
1967 group("a") {
1968 metadata = {
1969 doom_melon = [ "enable" ]
1970 my_files = [ "foo.cpp" ]
1971
Keir Mierle45611e32019-11-12 11:18:00 -08001972 # Note: this is functionally equivalent to not defining `my_barrier`
1973 # at all in this target's metadata.
Nate Fischer8ed01d32019-01-08 17:32:01 -08001974 my_barrier = [ "" ]
1975 }
1976
1977 deps = [ ":b" ]
1978 }
1979
Julie Hockettd69a9c32019-01-23 14:36:18 -08001980 group("b") {
Nate Fischer8ed01d32019-01-08 17:32:01 -08001981 metadata = {
1982 my_files = [ "bar.cpp" ]
1983 my_barrier = [ ":c" ]
1984 }
1985
1986 deps = [ ":c", ":d" ]
1987 }
1988
1989 group("c") {
1990 metadata = {
1991 doom_melon = [ "disable" ]
1992 my_files = [ "baz.cpp" ]
1993 }
1994 }
1995
1996 group("d") {
1997 metadata = {
1998 my_files = [ "missing.cpp" ]
1999 }
2000 }
2001
2002 If the following generated_file target is defined:
2003
2004 generated_file("my_files_metadata") {
2005 outputs = [ "$root_build_dir/my_files.json" ]
2006 data_keys = [ "my_files" ]
2007
2008 deps = [ "//base:a" ]
2009 }
2010
2011 The following will be written to "$root_build_dir/my_files.json" (less the
2012 comments):
2013 [
2014 "baz.cpp", // from //base:c via //base:b
2015 "missing.cpp" // from //base:d via //base:b
2016 "bar.cpp", // from //base:b via //base:a
2017 "foo.cpp", // from //base:a
2018 ]
2019
2020 Alternatively, as an example of using walk_keys, if the following
2021 generated_file target is defined:
2022
2023 generated_file("my_files_metadata") {
2024 outputs = [ "$root_build_dir/my_files.json" ]
2025 data_keys = [ "my_files" ]
2026 walk_keys = [ "my_barrier" ]
2027
2028 deps = [ "//base:a" ]
2029 }
2030
2031 The following will be written to "$root_build_dir/my_files.json" (again less
2032 the comments):
2033 [
2034 "baz.cpp", // from //base:c via //base:b
2035 "bar.cpp", // from //base:b via //base:a
2036 "foo.cpp", // from //base:a
2037 ]
2038
2039 If `rebase` is used in the following generated_file target:
2040
2041 generated_file("my_files_metadata") {
2042 outputs = [ "$root_build_dir/my_files.json" ]
2043 data_keys = [ "my_files" ]
2044 walk_keys = [ "my_barrier" ]
2045 rebase = root_build_dir
2046
2047 deps = [ "//base:a" ]
2048 }
2049
2050 The following will be written to "$root_build_dir/my_files.json" (again less
2051 the comments) (assuming root_build_dir = "//out"):
2052 [
2053 "../base/baz.cpp", // from //base:c via //base:b
2054 "../base/bar.cpp", // from //base:b via //base:a
2055 "../base/foo.cpp", // from //base:a
2056 ]
2057```
[email protected]449f3e42024-08-01 21:43:27 +08002058### **group**: Declare a named group of targets. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002059
2060```
2061 This target type allows you to create meta-targets that just collect a set of
2062 dependencies into one named target. Groups can additionally specify configs
2063 that apply to their dependents.
2064```
2065
2066#### **Variables**
2067
2068```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002069 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2070 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002071 Dependent configs: all_dependent_configs, public_configs
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002072 General: check_includes, configs, data, friend, inputs, metadata,
2073 output_extension, output_name, public, sources, testonly,
2074 visibility
Brett Wilson796ed472018-07-16 15:11:09 -07002075```
2076
2077#### **Example**
2078
2079```
2080 group("all") {
2081 deps = [
2082 "//project:runner",
2083 "//project:unit_tests",
2084 ]
2085 }
2086```
[email protected]449f3e42024-08-01 21:43:27 +08002087### **loadable_module**: Declare a loadable module target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002088
2089```
2090 This target type allows you to create an object file that is (and can only
2091 be) loaded and unloaded at runtime.
2092
2093 A loadable module will be specified on the linker line for targets listing
2094 the loadable module in its "deps". If you don't want this (if you don't need
2095 to dynamically load the library at runtime), then you should use a
2096 "shared_library" target type instead.
2097```
2098
Julie Hockettce1fa072019-05-07 17:44:37 -07002099#### **Language and compilation**
2100
2101```
2102 The tools and commands used to create this target type will be
2103 determined by the source files in its sources. Targets containing
2104 multiple compiler-incompatible languages are not allowed (e.g. a
2105 target containing both C and C++ sources is acceptable, but a
2106 target containing C and Rust sources is not).
2107```
2108
Brett Wilson796ed472018-07-16 15:11:09 -07002109#### **Variables**
2110
2111```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002112 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2113 cflags_objcc, defines, include_dirs, inputs, ldflags,
2114 lib_dirs, libs, precompiled_header, precompiled_source,
2115 rustenv, rustflags, swiftflags, testonly
2116 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2117 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002118 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08002119 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002120 output_extension, output_name, public, sources, testonly,
Nate Fischer8ed01d32019-01-08 17:32:01 -08002121 visibility
Petr Hosekadd1bb12019-09-11 14:39:38 -07002122 Rust variables: aliased_deps, crate_root, crate_name, crate_type
Julie Hockettce1fa072019-05-07 17:44:37 -07002123```
[email protected]449f3e42024-08-01 21:43:27 +08002124### **rust_library**: Declare a Rust library target. [Back to Top](#gn-reference)
Julie Hockettce1fa072019-05-07 17:44:37 -07002125
2126```
2127 A Rust library is an archive containing additional rust-c provided metadata.
2128 These are the files produced by the rustc compiler with the `.rlib`
2129 extension, and are the intermediate step for most Rust-based binaries.
2130```
2131
2132#### **Language and compilation**
2133
2134```
2135 The tools and commands used to create this target type will be
2136 determined by the source files in its sources. Targets containing
2137 multiple compiler-incompatible languages are not allowed (e.g. a
2138 target containing both C and C++ sources is acceptable, but a
2139 target containing C and Rust sources is not).
2140```
2141
2142#### **Variables**
2143
2144```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002145 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2146 cflags_objcc, defines, include_dirs, inputs, ldflags,
2147 lib_dirs, libs, precompiled_header, precompiled_source,
2148 rustenv, rustflags, swiftflags, testonly
2149 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2150 write_runtime_deps
Julie Hockettce1fa072019-05-07 17:44:37 -07002151 Dependent configs: all_dependent_configs, public_configs
2152 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002153 output_extension, output_name, public, sources, testonly,
Julie Hockettce1fa072019-05-07 17:44:37 -07002154 visibility
Petr Hosekadd1bb12019-09-11 14:39:38 -07002155 Rust variables: aliased_deps, crate_root, crate_name
Brett Wilson796ed472018-07-16 15:11:09 -07002156```
[email protected]449f3e42024-08-01 21:43:27 +08002157### **rust_proc_macro**: Declare a Rust procedural macro target. [Back to Top](#gn-reference)
Petr Hosekfe36c7c2019-11-26 14:38:08 -08002158
2159```
2160 A Rust procedural macro allows creating syntax extensions as execution of a
2161 function. They are compiled as dynamic libraries and used by the compiler at
2162 runtime.
2163
2164 Their use is the same as of other Rust libraries, but their build has some
2165 additional restrictions in terms of supported flags.
2166```
2167
2168#### **Language and compilation**
2169
2170```
2171 The tools and commands used to create this target type will be
2172 determined by the source files in its sources. Targets containing
2173 multiple compiler-incompatible languages are not allowed (e.g. a
2174 target containing both C and C++ sources is acceptable, but a
2175 target containing C and Rust sources is not).
2176```
2177
2178#### **Variables**
2179
2180```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002181 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2182 cflags_objcc, defines, include_dirs, inputs, ldflags,
2183 lib_dirs, libs, precompiled_header, precompiled_source,
2184 rustenv, rustflags, swiftflags, testonly
2185 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2186 write_runtime_deps
Petr Hosekfe36c7c2019-11-26 14:38:08 -08002187 Dependent configs: all_dependent_configs, public_configs
2188 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002189 output_extension, output_name, public, sources, testonly,
Petr Hosekfe36c7c2019-11-26 14:38:08 -08002190 visibility
2191 Rust variables: aliased_deps, crate_root, crate_name
2192```
[email protected]449f3e42024-08-01 21:43:27 +08002193### **shared_library**: Declare a shared library target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002194
2195```
2196 A shared library will be specified on the linker line for targets listing the
2197 shared library in its "deps". If you don't want this (say you dynamically
2198 load the library at runtime), then you should depend on the shared library
2199 via "data_deps" or, on Darwin platforms, use a "loadable_module" target type
2200 instead.
2201```
2202
Julie Hockettce1fa072019-05-07 17:44:37 -07002203#### **Language and compilation**
2204
2205```
2206 The tools and commands used to create this target type will be
2207 determined by the source files in its sources. Targets containing
2208 multiple compiler-incompatible languages are not allowed (e.g. a
2209 target containing both C and C++ sources is acceptable, but a
2210 target containing C and Rust sources is not).
2211```
2212
Brett Wilson796ed472018-07-16 15:11:09 -07002213#### **Variables**
2214
2215```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002216 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2217 cflags_objcc, defines, include_dirs, inputs, ldflags,
2218 lib_dirs, libs, precompiled_header, precompiled_source,
2219 rustenv, rustflags, swiftflags, testonly
2220 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2221 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002222 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08002223 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002224 output_extension, output_name, public, sources, testonly,
Nate Fischer8ed01d32019-01-08 17:32:01 -08002225 visibility
Petr Hosekadd1bb12019-09-11 14:39:38 -07002226 Rust variables: aliased_deps, crate_root, crate_name, crate_type
Brett Wilson796ed472018-07-16 15:11:09 -07002227```
[email protected]449f3e42024-08-01 21:43:27 +08002228### **source_set**: Declare a source set target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002229
2230```
Robert Sesekd0a6f072020-05-15 11:21:22 -04002231 Only C-language source sets are supported at the moment.
Julie Hockettce1fa072019-05-07 17:44:37 -07002232```
2233
2234#### **C-language source_sets**
2235
2236```
Brett Wilson796ed472018-07-16 15:11:09 -07002237 A source set is a collection of sources that get compiled, but are not linked
2238 to produce any kind of library. Instead, the resulting object files are
2239 implicitly added to the linker line of all targets that depend on the source
2240 set.
2241
2242 In most cases, a source set will behave like a static library, except no
2243 actual library file will be produced. This will make the build go a little
2244 faster by skipping creation of a large static library, while maintaining the
2245 organizational benefits of focused build targets.
2246
2247 The main difference between a source set and a static library is around
2248 handling of exported symbols. Most linkers assume declaring a function
2249 exported means exported from the static library. The linker can then do dead
2250 code elimination to delete code not reachable from exported functions.
2251
2252 A source set will not do this code elimination since there is no link step.
Julie Hockette2a29402018-07-31 10:11:42 -07002253 This allows you to link many source sets into a shared library and have the
Brett Wilson796ed472018-07-16 15:11:09 -07002254 "exported symbol" notation indicate "export from the final shared library and
2255 not from the intermediate targets." There is no way to express this concept
2256 when linking multiple static libraries into a shared library.
2257```
2258
2259#### **Variables**
2260
2261```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002262 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2263 cflags_objcc, defines, include_dirs, inputs, ldflags,
2264 lib_dirs, libs, precompiled_header, precompiled_source,
2265 rustenv, rustflags, swiftflags, testonly
2266 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2267 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002268 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08002269 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002270 output_extension, output_name, public, sources, testonly,
Nate Fischer8ed01d32019-01-08 17:32:01 -08002271 visibility
Brett Wilson796ed472018-07-16 15:11:09 -07002272```
[email protected]449f3e42024-08-01 21:43:27 +08002273### **static_library**: Declare a static library target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002274
2275```
2276 Make a ".a" / ".lib" file.
2277
2278 If you only need the static library for intermediate results in the build,
2279 you should consider a source_set instead since it will skip the (potentially
2280 slow) step of creating the intermediate library file.
2281```
2282
2283#### **Variables**
2284
2285```
2286 complete_static_lib
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002287 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2288 cflags_objcc, defines, include_dirs, inputs, ldflags,
2289 lib_dirs, libs, precompiled_header, precompiled_source,
2290 rustenv, rustflags, swiftflags, testonly
2291 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2292 write_runtime_deps
Brett Wilson796ed472018-07-16 15:11:09 -07002293 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08002294 General: check_includes, configs, data, friend, inputs, metadata,
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002295 output_extension, output_name, public, sources, testonly,
Nate Fischer8ed01d32019-01-08 17:32:01 -08002296 visibility
Petr Hosekadd1bb12019-09-11 14:39:38 -07002297 Rust variables: aliased_deps, crate_root, crate_name
Julie Hockettce1fa072019-05-07 17:44:37 -07002298
2299 The tools and commands used to create this target type will be
2300 determined by the source files in its sources. Targets containing
2301 multiple compiler-incompatible languages are not allowed (e.g. a
2302 target containing both C and C++ sources is acceptable, but a
2303 target containing C and Rust sources is not).
Brett Wilson796ed472018-07-16 15:11:09 -07002304```
[email protected]449f3e42024-08-01 21:43:27 +08002305### **target**: Declare a target with the given programmatic type. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002306
2307```
2308 target(target_type_string, target_name_string) { ... }
2309
2310 The target() function is a way to invoke a built-in target or template with a
2311 type determined at runtime. This is useful for cases where the type of a
2312 target might not be known statically.
2313
2314 Only templates and built-in target functions are supported for the
2315 target_type_string parameter. Arbitrary functions, configs, and toolchains
2316 are not supported.
2317
2318 The call:
2319 target("source_set", "doom_melon") {
2320 Is equivalent to:
2321 source_set("doom_melon") {
2322```
2323
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002324#### **Common target variables**
2325
2326```
2327 Deps: assert_no_deps, data_deps, deps, public_deps, runtime_deps,
2328 write_runtime_deps
2329 Dependent configs: all_dependent_configs, public_configs
2330 General: check_includes, configs, data, friend, inputs, metadata,
2331 output_extension, output_name, public, sources, testonly,
2332 visibility
2333
2334 Targets will also have variables specific to that type, see "gn help "
2335 for more.
2336```
2337
Brett Wilson796ed472018-07-16 15:11:09 -07002338#### **Example**
2339
2340```
2341 if (foo_build_as_shared) {
2342 my_type = "shared_library"
2343 } else {
2344 my_type = "source_set"
2345 }
2346
2347 target(my_type, "foo") {
2348 ...
2349 }
2350```
2351## Buildfile functions
2352
[email protected]449f3e42024-08-01 21:43:27 +08002353### **assert**: Assert an expression is true at generation time. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002354
2355```
2356 assert( [, ])
2357
2358 If the condition is false, the build will fail with an error. If the
2359 optional second argument is provided, that string will be printed
2360 with the error message.
2361```
2362
2363#### **Examples**
2364
2365```
2366 assert(is_win)
2367 assert(defined(sources), "Sources must be defined");
2368```
[email protected]449f3e42024-08-01 21:43:27 +08002369### **config**: Defines a configuration object. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002370
2371```
2372 Configuration objects can be applied to targets and specify sets of compiler
2373 flags, includes, defines, etc. They provide a way to conveniently group sets
2374 of this configuration information.
2375
2376 A config is referenced by its label just like a target.
2377
2378 The values in a config are additive only. If you want to remove a flag you
2379 need to remove the corresponding config that sets it. The final set of flags,
2380 defines, etc. for a target is generated in this order:
2381
Nico Weber693f9fb2021-10-08 15:33:57 -04002382 1. The values specified directly on the target (rather than using a config).
Brett Wilson796ed472018-07-16 15:11:09 -07002383 2. The configs specified in the target's "configs" list, in order.
2384 3. Public_configs from a breadth-first traversal of the dependency tree in
2385 the order that the targets appear in "deps".
2386 4. All dependent configs from a breadth-first traversal of the dependency
2387 tree in the order that the targets appear in "deps".
2388```
2389
Joe Armstrong39413942019-03-15 10:34:03 +08002390#### **More background**
2391
2392```
2393 Configs solve a problem where the build system needs to have a higher-level
2394 understanding of various compiler settings. For example, some compiler flags
2395 have to appear in a certain order relative to each other, some settings like
2396 defines and flags logically go together, and the build system needs to
2397 de-duplicate flags even though raw command-line parameters can't always be
2398 operated on in that way.
2399
2400 The config gives a name to a group of settings that can then be reasoned
2401 about by GN. GN can know that configs with the same label are the same thing
2402 so can be de-duplicated. It allows related settings to be grouped so they
2403 are added or removed as a unit. And it allows targets to refer to settings
2404 with conceptual names ("no_rtti", "enable_exceptions", etc.) rather than
2405 having to hard-coding every compiler's flags each time they are referred to.
2406```
2407
Brett Wilson796ed472018-07-16 15:11:09 -07002408#### **Variables valid in a config definition**
Joe Armstrong39413942019-03-15 10:34:03 +08002409
Brett Wilson796ed472018-07-16 15:11:09 -07002410```
Brett Wilsond0f8bc92022-04-22 14:01:40 -07002411 Flags: asmflags, cflags, cflags_c, cflags_cc, cflags_objc,
2412 cflags_objcc, defines, include_dirs, inputs, ldflags,
2413 lib_dirs, libs, precompiled_header, precompiled_source,
2414 rustenv, rustflags, swiftflags, testonly
Brett Wilson796ed472018-07-16 15:11:09 -07002415 Nested configs: configs
Tomasz Åšniatowski46b572c2021-09-03 21:47:17 +02002416 General: visibility
Brett Wilson796ed472018-07-16 15:11:09 -07002417```
2418
2419#### **Variables on a target used to apply configs**
2420
2421```
2422 all_dependent_configs, configs, public_configs
2423```
2424
2425#### **Example**
2426
2427```
2428 config("myconfig") {
Joe Armstrongf5ad8072019-05-08 08:42:56 +08002429 include_dirs = [ "include/common" ]
Brett Wilson796ed472018-07-16 15:11:09 -07002430 defines = [ "ENABLE_DOOM_MELON" ]
2431 }
2432
2433 executable("mything") {
2434 configs = [ ":myconfig" ]
2435 }
2436```
[email protected]449f3e42024-08-01 21:43:27 +08002437### **declare_args**: Declare build arguments. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002438
2439```
2440 Introduces the given arguments into the current scope. If they are not
2441 specified on the command line or in a toolchain's arguments, the default
2442 values given in the declare_args block will be used. However, these defaults
2443 will not override command-line values.
2444
2445 See also "gn help buildargs" for an overview.
2446
2447 The precise behavior of declare args is:
2448
2449 1. The declare_args() block executes. Any variable defined in the enclosing
2450 scope is available for reading, but any variable defined earlier in
2451 the current scope is not (since the overrides haven't been applied yet).
2452
2453 2. At the end of executing the block, any variables set within that scope
Petr Hosek7617b592019-10-02 09:52:21 -07002454 are saved, with the values specified in the block used as the "default value"
2455 for that argument. Once saved, these variables are available for override
2456 via args.gn.
Brett Wilson796ed472018-07-16 15:11:09 -07002457
2458 3. User-defined overrides are applied. Anything set in "gn args" now
2459 overrides any default values. The resulting set of variables is promoted
2460 to be readable from the following code in the file.
2461
2462 This has some ramifications that may not be obvious:
2463
2464 - You should not perform difficult work inside a declare_args block since
2465 this only sets a default value that may be discarded. In particular,
2466 don't use the result of exec_script() to set the default value. If you
2467 want to have a script-defined default, set some default "undefined" value
2468 like [], "", or -1, and after the declare_args block, call exec_script if
2469 the value is unset by the user.
2470
2471 - Because you cannot read the value of a variable defined in the same
2472 block, if you need to make the default value of one arg depend
2473 on the possibly-overridden value of another, write two separate
2474 declare_args() blocks:
2475
2476 declare_args() {
2477 enable_foo = true
2478 }
2479 declare_args() {
2480 # Bar defaults to same user-overridden state as foo.
2481 enable_bar = enable_foo
2482 }
2483```
2484
2485#### **Example**
2486
2487```
2488 declare_args() {
2489 enable_teleporter = true
2490 enable_doom_melon = false
2491 }
2492
2493 If you want to override the (default disabled) Doom Melon:
2494 gn --args="enable_doom_melon=true enable_teleporter=true"
2495 This also sets the teleporter, but it's already defaulted to on so it will
2496 have no effect.
2497```
[email protected]449f3e42024-08-01 21:43:27 +08002498### **defined**: Returns whether an identifier is defined. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002499
2500```
2501 Returns true if the given argument is defined. This is most useful in
2502 templates to assert that the caller set things up properly.
2503
2504 You can pass an identifier:
2505 defined(foo)
2506 which will return true or false depending on whether foo is defined in the
2507 current scope.
2508
2509 You can also check a named scope:
2510 defined(foo.bar)
2511 which will return true or false depending on whether bar is defined in the
2512 named scope foo. It will throw an error if foo is not defined or is not a
2513 scope.
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07002514
2515 You can also check a named scope using a subscript string expression:
2516 defined(foo[bar + "_name"])
Takuto Ikuta26aa46c2023-05-09 16:28:45 +09002517 which will return true or false depending on whether the subscript
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07002518 expression expands to the name of a member of the scope foo. It will
2519 throw an error if foo is not defined or is not a scope, or if the
2520 expression does not expand to a string, or if it is an empty string.
Brett Wilson796ed472018-07-16 15:11:09 -07002521```
2522
2523#### **Example**
2524
2525```
2526 template("mytemplate") {
2527 # To help users call this template properly...
2528 assert(defined(invoker.sources), "Sources must be defined")
2529
2530 # If we want to accept an optional "values" argument, we don't
2531 # want to dereference something that may not be defined.
2532 if (defined(invoker.values)) {
2533 values = invoker.values
2534 } else {
2535 values = "some default value"
2536 }
2537 }
2538```
[email protected]449f3e42024-08-01 21:43:27 +08002539### **exec_script**: Synchronously run a script and return the output. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002540
2541```
2542 exec_script(filename,
2543 arguments = [],
2544 input_conversion = "",
2545 file_dependencies = [])
2546
2547 Runs the given script, returning the stdout of the script. The build
2548 generation will fail if the script does not exist or returns a nonzero exit
2549 code.
2550
2551 The current directory when executing the script will be the root build
2552 directory. If you are passing file names, you will want to use the
2553 rebase_path() function to make file names relative to this path (see "gn help
2554 rebase_path").
Gary Miguelce7fa362018-09-17 12:48:17 -07002555
2556 The default script interpreter is Python ("python" on POSIX, "python.exe" or
2557 "python.bat" on Windows). This can be configured by the script_executable
2558 variable, see "gn help dotfile".
Brett Wilson796ed472018-07-16 15:11:09 -07002559```
2560
2561#### **Arguments**:
2562
2563```
2564 filename:
Gary Miguelce7fa362018-09-17 12:48:17 -07002565 File name of script to execute. Non-absolute names will be treated as
2566 relative to the current build file.
Brett Wilson796ed472018-07-16 15:11:09 -07002567
2568 arguments:
2569 A list of strings to be passed to the script as arguments. May be
2570 unspecified or the empty list which means no arguments.
2571
2572 input_conversion:
Sylvain Defresne72d5a6e2021-06-15 17:01:32 +02002573 Controls how the file is read and parsed. See `gn help io_conversion`.
Brett Wilson796ed472018-07-16 15:11:09 -07002574
2575 If unspecified, defaults to the empty string which causes the script
2576 result to be discarded. exec script will return None.
2577
2578 dependencies:
2579 (Optional) A list of files that this script reads or otherwise depends
2580 on. These dependencies will be added to the build result such that if any
2581 of them change, the build will be regenerated and the script will be
2582 re-run.
2583
2584 The script itself will be an implicit dependency so you do not need to
2585 list it.
2586```
2587
2588#### **Example**
2589
2590```
2591 all_lines = exec_script(
2592 "myscript.py", [some_input], "list lines",
2593 [ rebase_path("data_file.txt", root_build_dir) ])
2594
2595 # This example just calls the script with no arguments and discards the
2596 # result.
2597 exec_script("//foo/bar/myscript.py")
2598```
[email protected]449f3e42024-08-01 21:43:27 +08002599### **filter_exclude**: Remove values that match a set of patterns. [Back to Top](#gn-reference)
Sylvain Defresneaff489a2020-03-11 18:27:43 +01002600
2601```
2602 filter_exclude(values, exclude_patterns)
2603
2604 The argument values must be a list of strings.
2605
2606 The argument exclude_patterns must be a list of file patterns (see
2607 "gn help file_pattern"). Any elements in values matching at least one
2608 of those patterns will be excluded.
2609```
2610
2611#### **Examples**
2612```
2613 values = [ "foo.cc", "foo.h", "foo.proto" ]
2614 result = filter_exclude(values, [ "*.proto" ])
2615 # result will be [ "foo.cc", "foo.h" ]
2616```
[email protected]449f3e42024-08-01 21:43:27 +08002617### **filter_include**: Remove values that do not match a set of patterns. [Back to Top](#gn-reference)
Sylvain Defresneaff489a2020-03-11 18:27:43 +01002618
2619```
2620 filter_include(values, include_patterns)
2621
2622 The argument values must be a list of strings.
2623
2624 The argument include_patterns must be a list of file patterns (see
2625 "gn help file_pattern"). Only elements from values matching at least
2626 one of the pattern will be included.
2627```
2628
2629#### **Examples**
2630```
2631 values = [ "foo.cc", "foo.h", "foo.proto" ]
2632 result = filter_include(values, [ "*.proto" ])
2633 # result will be [ "foo.proto" ]
2634```
[email protected]449f3e42024-08-01 21:43:27 +08002635### **filter_labels_exclude**: Remove labels that match a set of patterns. [Back to Top](#gn-reference)
Aaron Woode05c0aa2024-02-14 13:40:53 -08002636
2637```
2638 filter_labels_exclude(labels, exclude_patterns)
2639
2640 The argument labels must be a list of strings.
2641
2642 The argument exclude_patterns must be a list of label patterns (see
2643 "gn help label_pattern"). Only elements from labels matching at least
2644 one of the patterns will be excluded.
2645```
2646
2647#### **Examples**
2648```
2649 labels = [ "//foo:baz", "//foo/bar:baz", "//bar:baz" ]
2650 result = filter_labels_exclude(labels, [ "//foo:*" ])
2651 # result will be [ "//foo/bar:baz", "//bar:baz" ]
2652```
[email protected]449f3e42024-08-01 21:43:27 +08002653### **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 -08002654
2655```
2656 filter_labels_include(labels, include_patterns)
2657
2658 The argument labels must be a list of strings.
2659
2660 The argument include_patterns must be a list of label patterns (see
2661 "gn help label_pattern"). Only elements from labels matching at least
2662 one of the patterns will be included.
2663```
2664
2665#### **Examples**
2666```
2667 labels = [ "//foo:baz", "//foo/bar:baz", "//bar:baz" ]
2668 result = filter_labels_include(labels, [ "//foo:*" ])
2669 # result will be [ "//foo:baz" ]
2670```
[email protected]449f3e42024-08-01 21:43:27 +08002671### **foreach**: Iterate over a list. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002672
2673```
2674 foreach(, ) {
2675
2676 }
2677
2678 Executes the loop contents block over each item in the list, assigning the
2679 loop_var to each item in sequence. The will be a copy so assigning
2680 to it will not mutate the list. The loop will iterate over a copy of
2681 so mutating it inside the loop will not affect iteration.
2682
2683 The block does not introduce a new scope, so that variable assignments inside
2684 the loop will be visible once the loop terminates.
2685
2686 The loop variable will temporarily shadow any existing variables with the
2687 same name for the duration of the loop. After the loop terminates the loop
2688 variable will no longer be in scope, and the previous value (if any) will be
2689 restored.
2690```
2691
2692#### **Example**
2693
2694```
2695 mylist = [ "a", "b", "c" ]
2696 foreach(i, mylist) {
2697 print(i)
2698 }
2699
2700 Prints:
2701 a
2702 b
2703 c
2704```
[email protected]449f3e42024-08-01 21:43:27 +08002705### **forward_variables_from**: Copies variables from a different scope. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002706
2707```
2708 forward_variables_from(from_scope, variable_list_or_star,
2709 variable_to_not_forward_list = [])
2710
2711 Copies the given variables from the given scope to the local scope if they
2712 exist. This is normally used in the context of templates to use the values of
2713 variables defined in the template invocation to a template-defined target.
2714
2715 The variables in the given variable_list will be copied if they exist in the
2716 given scope or any enclosing scope. If they do not exist, nothing will happen
2717 and they be left undefined in the current scope.
2718
2719 As a special case, if the variable_list is a string with the value of "*",
2720 all variables from the given scope will be copied. "*" only copies variables
2721 set directly on the from_scope, not enclosing ones. Otherwise it would
2722 duplicate all global variables.
2723
2724 When an explicit list of variables is supplied, if the variable exists in the
2725 current (destination) scope already, an error will be thrown. If "*" is
2726 specified, variables in the current scope will be clobbered (the latter is
2727 important because most targets have an implicit configs list, which means it
2728 wouldn't work at all if it didn't clobber).
2729
Brett Wilson796ed472018-07-16 15:11:09 -07002730 If variables_to_not_forward_list is non-empty, then it must contains a list
2731 of variable names that will not be forwarded. This is mostly useful when
2732 variable_list_or_star has a value of "*".
2733```
2734
2735#### **Examples**
2736
2737```
Andrew Grieve57a964c2018-09-14 10:50:56 -04002738 # forward_variables_from(invoker, ["foo"])
2739 # is equivalent to:
2740 assert(!defined(foo))
2741 if (defined(invoker.foo)) {
2742 foo = invoker.foo
2743 }
2744
Brett Wilson796ed472018-07-16 15:11:09 -07002745 # This is a common action template. It would invoke a script with some given
2746 # parameters, and wants to use the various types of deps and the visibility
2747 # from the invoker if it's defined. It also injects an additional dependency
2748 # to all targets.
2749 template("my_test") {
2750 action(target_name) {
2751 forward_variables_from(invoker, [ "data_deps", "deps",
Julie Hockette2a29402018-07-31 10:11:42 -07002752 "public_deps", "visibility"])
Brett Wilson796ed472018-07-16 15:11:09 -07002753 # Add our test code to the dependencies.
2754 # "deps" may or may not be defined at this point.
2755 if (defined(deps)) {
2756 deps += [ "//tools/doom_melon" ]
2757 } else {
2758 deps = [ "//tools/doom_melon" ]
2759 }
2760 }
2761 }
2762
Julie Hockette2a29402018-07-31 10:11:42 -07002763 # This is a template around a target whose type depends on a global variable.
2764 # It forwards all values from the invoker.
Brett Wilson796ed472018-07-16 15:11:09 -07002765 template("my_wrapper") {
2766 target(my_wrapper_target_type, target_name) {
2767 forward_variables_from(invoker, "*")
2768 }
2769 }
2770
2771 # A template that wraps another. It adds behavior based on one
2772 # variable, and forwards all others to the nested target.
2773 template("my_ios_test_app") {
2774 ios_test_app(target_name) {
2775 forward_variables_from(invoker, "*", ["test_bundle_name"])
2776 if (!defined(extra_substitutions)) {
2777 extra_substitutions = []
2778 }
2779 extra_substitutions += [ "BUNDLE_ID_TEST_NAME=$test_bundle_name" ]
2780 }
2781 }
2782```
[email protected]449f3e42024-08-01 21:43:27 +08002783### **get_label_info**: Get an attribute from a target's label. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002784
2785```
2786 get_label_info(target_label, what)
2787
2788 Given the label of a target, returns some attribute of that target. The
2789 target need not have been previously defined in the same file, since none of
2790 the attributes depend on the actual target definition, only the label itself.
2791
2792 See also "gn help get_target_outputs".
2793```
2794
2795#### **Possible values for the "what" parameter**
2796
2797```
2798 "name"
2799 The short name of the target. This will match the value of the
2800 "target_name" variable inside that target's declaration. For the label
2801 "//foo/bar:baz" this will return "baz".
2802
2803 "dir"
2804 The directory containing the target's definition, with no slash at the
2805 end. For the label "//foo/bar:baz" this will return "//foo/bar".
2806
2807 "target_gen_dir"
2808 The generated file directory for the target. This will match the value of
2809 the "target_gen_dir" variable when inside that target's declaration.
2810
2811 "root_gen_dir"
2812 The root of the generated file tree for the target. This will match the
2813 value of the "root_gen_dir" variable when inside that target's
2814 declaration.
2815
2816 "target_out_dir
2817 The output directory for the target. This will match the value of the
2818 "target_out_dir" variable when inside that target's declaration.
2819
2820 "root_out_dir"
2821 The root of the output file tree for the target. This will match the
2822 value of the "root_out_dir" variable when inside that target's
2823 declaration.
2824
2825 "label_no_toolchain"
2826 The fully qualified version of this label, not including the toolchain.
2827 For the input ":bar" it might return "//foo:bar".
2828
2829 "label_with_toolchain"
2830 The fully qualified version of this label, including the toolchain. For
2831 the input ":bar" it might return "//foo:bar(//toolchain:x64)".
2832
2833 "toolchain"
2834 The label of the toolchain. This will match the value of the
2835 "current_toolchain" variable when inside that target's declaration.
2836```
2837
2838#### **Examples**
2839
2840```
2841 get_label_info(":foo", "name")
2842 # Returns string "foo".
2843
2844 get_label_info("//foo/bar:baz", "target_gen_dir")
2845 # Returns string "//out/Debug/gen/foo/bar".
2846```
[email protected]449f3e42024-08-01 21:43:27 +08002847### **get_path_info**: Extract parts of a file or directory name. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002848
2849```
2850 get_path_info(input, what)
2851
2852 The first argument is either a string representing a file or directory name,
2853 or a list of such strings. If the input is a list the return value will be a
2854 list containing the result of applying the rule to each item in the input.
2855```
2856
2857#### **Possible values for the "what" parameter**
2858
2859```
2860 "file"
2861 The substring after the last slash in the path, including the name and
2862 extension. If the input ends in a slash, the empty string will be
2863 returned.
2864 "foo/bar.txt" => "bar.txt"
2865 "bar.txt" => "bar.txt"
2866 "foo/" => ""
2867 "" => ""
2868
2869 "name"
2870 The substring of the file name not including the extension.
2871 "foo/bar.txt" => "bar"
2872 "foo/bar" => "bar"
2873 "foo/" => ""
2874
2875 "extension"
2876 The substring following the last period following the last slash, or the
2877 empty string if not found. The period is not included.
2878 "foo/bar.txt" => "txt"
2879 "foo/bar" => ""
2880
2881 "dir"
2882 The directory portion of the name, not including the slash.
2883 "foo/bar.txt" => "foo"
2884 "//foo/bar" => "//foo"
2885 "foo" => "."
2886
2887 The result will never end in a slash, so if the resulting is empty, the
2888 system ("/") or source ("//") roots, a "." will be appended such that it
2889 is always legal to append a slash and a filename and get a valid path.
2890
2891 "out_dir"
2892 The output file directory corresponding to the path of the given file,
2893 not including a trailing slash.
2894 "//foo/bar/baz.txt" => "//out/Default/obj/foo/bar"
2895
2896 "gen_dir"
2897 The generated file directory corresponding to the path of the given file,
2898 not including a trailing slash.
2899 "//foo/bar/baz.txt" => "//out/Default/gen/foo/bar"
2900
2901 "abspath"
2902 The full absolute path name to the file or directory. It will be resolved
2903 relative to the current directory, and then the source- absolute version
2904 will be returned. If the input is system- absolute, the same input will
2905 be returned.
2906 "foo/bar.txt" => "//mydir/foo/bar.txt"
2907 "foo/" => "//mydir/foo/"
2908 "//foo/bar" => "//foo/bar" (already absolute)
2909 "/usr/include" => "/usr/include" (already absolute)
2910
2911 If you want to make the path relative to another directory, or to be
2912 system-absolute, see rebase_path().
2913```
2914
2915#### **Examples**
2916```
2917 sources = [ "foo.cc", "foo.h" ]
2918 result = get_path_info(source, "abspath")
2919 # result will be [ "//mydir/foo.cc", "//mydir/foo.h" ]
2920
2921 result = get_path_info("//foo/bar/baz.cc", "dir")
2922 # result will be "//foo/bar"
2923
2924 # Extract the source-absolute directory name,
Joe Armstrong39413942019-03-15 10:34:03 +08002925 result = get_path_info(get_path_info(path, "dir"), "abspath")
Brett Wilson796ed472018-07-16 15:11:09 -07002926```
[email protected]449f3e42024-08-01 21:43:27 +08002927### **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 -07002928
2929```
2930 get_target_outputs(target_label)
2931
2932 Returns a list of output files for the named target. The named target must
2933 have been previously defined in the current file before this function is
2934 called (it can't reference targets in other files because there isn't a
2935 defined execution order, and it obviously can't reference targets that are
2936 defined after the function call).
2937
Julie Hockettce1fa072019-05-07 17:44:37 -07002938 Only copy, generated_file, and action targets are supported. The outputs from
2939 binary targets will depend on the toolchain definition which won't
2940 necessarily have been loaded by the time a given line of code has run, and
2941 source sets and groups have no useful output file.
Brett Wilson796ed472018-07-16 15:11:09 -07002942```
2943
2944#### **Return value**
2945
2946```
2947 The names in the resulting list will be absolute file paths (normally like
2948 "//out/Debug/bar.exe", depending on the build directory).
2949
Julie Hockettce1fa072019-05-07 17:44:37 -07002950 action, copy, and generated_file targets: this will just return the files
2951 specified in the "outputs" variable of the target.
Brett Wilson796ed472018-07-16 15:11:09 -07002952
2953 action_foreach targets: this will return the result of applying the output
2954 template to the sources (see "gn help source_expansion"). This will be the
2955 same result (though with guaranteed absolute file paths), as
2956 process_file_template will return for those inputs (see "gn help
2957 process_file_template").
2958
Brett Wilson796ed472018-07-16 15:11:09 -07002959 source sets and groups: this will return a list containing the path of the
Takuto Ikuta50ecf4c2024-08-19 18:43:24 +09002960 phony target that Ninja completes once all outputs are generated. This
Brett Wilson796ed472018-07-16 15:11:09 -07002961 probably isn't very useful.
2962```
2963
2964#### **Example**
2965
2966```
2967 # Say this action generates a bunch of C source files.
2968 action_foreach("my_action") {
2969 sources = [ ... ]
2970 outputs = [ ... ]
2971 }
2972
2973 # Compile the resulting source files into a source set.
2974 source_set("my_lib") {
2975 sources = get_target_outputs(":my_action")
2976 }
2977```
[email protected]449f3e42024-08-01 21:43:27 +08002978### **getenv**: Get an environment variable. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002979
2980```
2981 value = getenv(env_var_name)
2982
2983 Returns the value of the given environment variable. If the value is not
2984 found, it will try to look up the variable with the "opposite" case (based on
2985 the case of the first letter of the variable), but is otherwise
2986 case-sensitive.
2987
2988 If the environment variable is not found, the empty string will be returned.
2989 Note: it might be nice to extend this if we had the concept of "none" in the
2990 language to indicate lookup failure.
2991```
2992
2993#### **Example**
2994
2995```
2996 home_dir = getenv("HOME")
2997```
[email protected]449f3e42024-08-01 21:43:27 +08002998### **import**: Import a file into the current scope. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07002999
3000```
3001 The import command loads the rules and variables resulting from executing the
3002 given file into the current scope.
3003
3004 By convention, imported files are named with a .gni extension.
3005
3006 An import is different than a C++ "include". The imported file is executed in
3007 a standalone environment from the caller of the import command. The results
3008 of this execution are cached for other files that import the same .gni file.
3009
3010 Note that you can not import a BUILD.gn file that's otherwise used in the
3011 build. Files must either be imported or implicitly loaded as a result of deps
3012 rules, but not both.
3013
3014 The imported file's scope will be merged with the scope at the point import
3015 was called. If there is a conflict (both the current scope and the imported
3016 file define some variable or rule with the same name but different value), a
3017 runtime error will be thrown. Therefore, it's good practice to minimize the
3018 stuff that an imported file defines.
3019
3020 Variables and templates beginning with an underscore '_' are considered
3021 private and will not be imported. Imported files can use such variables for
3022 internal computation without affecting other files.
3023```
3024
3025#### **Examples**
3026
3027```
3028 import("//build/rules/idl_compilation_rule.gni")
3029
3030 # Looks in the current directory.
3031 import("my_vars.gni")
3032```
[email protected]449f3e42024-08-01 21:43:27 +08003033### **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 -08003034
3035```
3036 label_matches(target_label, patterns)
3037
3038 The argument patterns must be a list of label patterns (see
3039 "gn help label_pattern"). If the target_label matches any of the patterns,
3040 the function returns the value true.
3041```
3042
3043#### **Examples**
3044```
3045 result = label_matches("//baz:bar", [ "//foo/bar/*", "//baz:*" ])
3046 # result will be true
3047```
[email protected]449f3e42024-08-01 21:43:27 +08003048### **not_needed**: Mark variables from scope as not needed. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003049
3050```
3051 not_needed(variable_list_or_star, variable_to_ignore_list = [])
3052 not_needed(from_scope, variable_list_or_star,
3053 variable_to_ignore_list = [])
3054
3055 Mark the variables in the current or given scope as not needed, which means
3056 you will not get an error about unused variables for these. The
3057 variable_to_ignore_list allows excluding variables from "all matches" if
3058 variable_list_or_star is "*".
3059```
3060
3061#### **Example**
3062
3063```
3064 not_needed("*", [ "config" ])
3065 not_needed([ "data_deps", "deps" ])
3066 not_needed(invoker, "*", [ "config" ])
3067 not_needed(invoker, [ "data_deps", "deps" ])
3068```
[email protected]449f3e42024-08-01 21:43:27 +08003069### **pool**: Defines a pool object. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003070
3071```
3072 Pool objects can be applied to a tool to limit the parallelism of the
3073 build. This object has a single property "depth" corresponding to
3074 the number of tasks that may run simultaneously.
3075
3076 As the file containing the pool definition may be executed in the
3077 context of more than one toolchain it is recommended to specify an
3078 explicit toolchain when defining and referencing a pool.
3079
Julie Hockette2a29402018-07-31 10:11:42 -07003080 A pool named "console" defined in the root build file represents Ninja's
3081 console pool. Targets using this pool will have access to the console's
3082 stdin and stdout, and output will not be buffered. This special pool must
3083 have a depth of 1. Pools not defined in the root must not be named "console".
3084 The console pool can only be defined for the default toolchain.
3085 Refer to the Ninja documentation on the console pool for more info.
3086
Brett Wilson796ed472018-07-16 15:11:09 -07003087 A pool is referenced by its label just like a target.
3088```
3089
3090#### **Variables**
3091
3092```
3093 depth*
3094 * = required
3095```
3096
3097#### **Example**
3098
3099```
3100 if (current_toolchain == default_toolchain) {
3101 pool("link_pool") {
3102 depth = 1
3103 }
3104 }
3105
3106 toolchain("toolchain") {
3107 tool("link") {
3108 command = "..."
Petr Hosekadd1bb12019-09-11 14:39:38 -07003109 pool = ":link_pool($default_toolchain)"
Brett Wilson796ed472018-07-16 15:11:09 -07003110 }
3111 }
3112```
[email protected]449f3e42024-08-01 21:43:27 +08003113### **print**: Prints to the console. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003114
3115```
3116 Prints all arguments to the console separated by spaces. A newline is
3117 automatically appended to the end.
3118
3119 This function is intended for debugging. Note that build files are run in
3120 parallel so you may get interleaved prints. A buildfile may also be executed
3121 more than once in parallel in the context of different toolchains so the
3122 prints from one file may be duplicated or
3123 interleaved with itself.
3124```
3125
3126#### **Examples**
3127
3128```
3129 print("Hello world")
3130
3131 print(sources, deps)
3132```
[email protected]449f3e42024-08-01 21:43:27 +08003133### **print_stack_trace**: Prints a stack trace. [Back to Top](#gn-reference)
Aaron Wood24062bb2022-04-25 20:37:48 -07003134
3135```
3136 Prints the current file location, and all template invocations that led up to
3137 this location, to the console.
3138```
3139
3140#### **Examples**
3141
3142```
3143 template("foo"){
3144 print_stack_trace()
3145 }
3146 template("bar"){
3147 foo(target_name + ".foo") {
3148 baz = invoker.baz
3149 }
3150 }
3151 bar("lala") {
3152 baz = 42
3153 }
3154
3155 will print out the following:
3156
3157 print_stack_trace() initiated at //build.gn:2
3158 bar("lala") //BUILD.gn:9
3159 foo("lala.foo") //BUILD.gn:5
3160 print_stack_trace() //BUILD.gn:2
3161```
[email protected]449f3e42024-08-01 21:43:27 +08003162### **process_file_template**: Do template expansion over a list of files. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003163
3164```
3165 process_file_template(source_list, template)
3166
3167 process_file_template applies a template list to a source file list,
3168 returning the result of applying each template to each source. This is
3169 typically used for computing output file names from input files.
3170
3171 In most cases, get_target_outputs() will give the same result with shorter,
3172 more maintainable code. This function should only be used when that function
3173 can't be used (like there's no target or the target is defined in another
3174 build file).
3175```
3176
3177#### **Arguments**
3178
3179```
3180 The source_list is a list of file names.
3181
3182 The template can be a string or a list. If it is a list, multiple output
3183 strings are generated for each input.
3184
3185 The template should contain source expansions to which each name in the
3186 source list is applied. See "gn help source_expansion".
3187```
3188
3189#### **Example**
3190
3191```
3192 sources = [
3193 "foo.idl",
3194 "bar.idl",
3195 ]
3196 myoutputs = process_file_template(
3197 sources,
3198 [ "$target_gen_dir/{{source_name_part}}.cc",
3199 "$target_gen_dir/{{source_name_part}}.h" ])
3200
3201 The result in this case will be:
3202 [ "//out/Debug/foo.cc"
3203 "//out/Debug/foo.h"
3204 "//out/Debug/bar.cc"
3205 "//out/Debug/bar.h" ]
3206```
[email protected]449f3e42024-08-01 21:43:27 +08003207### **read_file**: Read a file into a variable. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003208
3209```
3210 read_file(filename, input_conversion)
3211
3212 Whitespace will be trimmed from the end of the file. Throws an error if the
3213 file can not be opened.
3214```
3215
3216#### **Arguments**
3217
3218```
3219 filename
3220 Filename to read, relative to the build file.
3221
3222 input_conversion
Sylvain Defresne72d5a6e2021-06-15 17:01:32 +02003223 Controls how the file is read and parsed. See `gn help io_conversion`.
Brett Wilson796ed472018-07-16 15:11:09 -07003224```
3225
3226#### **Example**
3227
3228```
3229 lines = read_file("foo.txt", "list lines")
3230```
[email protected]449f3e42024-08-01 21:43:27 +08003231### **rebase_path**: Rebase a file or directory to another location. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003232
3233```
3234 converted = rebase_path(input,
3235 new_base = "",
3236 current_base = ".")
3237
3238 Takes a string argument representing a file name, or a list of such strings
3239 and converts it/them to be relative to a different base directory.
3240
3241 When invoking the compiler or scripts, GN will automatically convert sources
3242 and include directories to be relative to the build directory. However, if
3243 you're passing files directly in the "args" array or doing other manual
3244 manipulations where GN doesn't know something is a file name, you will need
3245 to convert paths to be relative to what your tool is expecting.
3246
3247 The common case is to use this to convert paths relative to the current
3248 directory to be relative to the build directory (which will be the current
3249 directory when executing scripts).
3250
3251 If you want to convert a file path to be source-absolute (that is, beginning
3252 with a double slash like "//foo/bar"), you should use the get_path_info()
3253 function. This function won't work because it will always make relative
3254 paths, and it needs to support making paths relative to the source root, so
Robert Sesekd0a6f072020-05-15 11:21:22 -04003255 it can't also generate source-absolute paths without more special-cases.
Brett Wilson796ed472018-07-16 15:11:09 -07003256```
3257
3258#### **Arguments**
3259
3260```
3261 input
Robert Sesekd0a6f072020-05-15 11:21:22 -04003262 A string or list of strings representing file or directory names. These
Brett Wilson796ed472018-07-16 15:11:09 -07003263 can be relative paths ("foo/bar.txt"), system absolute paths
3264 ("/foo/bar.txt"), or source absolute paths ("//foo/bar.txt").
3265
3266 new_base
3267 The directory to convert the paths to be relative to. This can be an
3268 absolute path or a relative path (which will be treated as being relative
3269 to the current BUILD-file's directory).
3270
3271 As a special case, if new_base is the empty string (the default), all
3272 paths will be converted to system-absolute native style paths with system
3273 path separators. This is useful for invoking external programs.
3274
3275 current_base
3276 Directory representing the base for relative paths in the input. If this
3277 is not an absolute path, it will be treated as being relative to the
3278 current build file. Use "." (the default) to convert paths from the
3279 current BUILD-file's directory.
3280```
3281
3282#### **Return value**
3283
3284```
3285 The return value will be the same type as the input value (either a string or
3286 a list of strings). All relative and source-absolute file names will be
3287 converted to be relative to the requested output System-absolute paths will
3288 be unchanged.
3289
3290 Whether an output path will end in a slash will match whether the
3291 corresponding input path ends in a slash. It will return "." or "./"
3292 (depending on whether the input ends in a slash) to avoid returning empty
3293 strings. This means if you want a root path ("//" or "/") not ending in a
3294 slash, you can add a dot ("//.").
3295```
3296
3297#### **Example**
3298
3299```
3300 # Convert a file in the current directory to be relative to the build
3301 # directory (the current dir when executing compilers and scripts).
3302 foo = rebase_path("myfile.txt", root_build_dir)
3303 # might produce "../../project/myfile.txt".
3304
3305 # Convert a file to be system absolute:
3306 foo = rebase_path("myfile.txt")
3307 # Might produce "D:\\source\\project\\myfile.txt" on Windows or
3308 # "/home/you/source/project/myfile.txt" on Linux.
3309
3310 # Typical usage for converting to the build directory for a script.
3311 action("myscript") {
3312 # Don't convert sources, GN will automatically convert these to be relative
3313 # to the build directory when it constructs the command line for your
3314 # script.
3315 sources = [ "foo.txt", "bar.txt" ]
3316
3317 # Extra file args passed manually need to be explicitly converted
3318 # to be relative to the build directory:
3319 args = [
3320 "--data",
3321 rebase_path("//mything/data/input.dat", root_build_dir),
3322 "--rel",
3323 rebase_path("relative_path.txt", root_build_dir)
3324 ] + rebase_path(sources, root_build_dir)
3325 }
3326```
[email protected]449f3e42024-08-01 21:43:27 +08003327### **set_default_toolchain**: Sets the default toolchain name. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003328
3329```
3330 set_default_toolchain(toolchain_label)
3331
3332 The given label should identify a toolchain definition (see "gn help
3333 toolchain"). This toolchain will be used for all targets unless otherwise
3334 specified.
3335
3336 This function is only valid to call during the processing of the build
3337 configuration file. Since the build configuration file is processed
3338 separately for each toolchain, this function will be a no-op when called
3339 under any non-default toolchains.
3340
3341 For example, the default toolchain should be appropriate for the current
3342 environment. If the current environment is 32-bit and somebody references a
3343 target with a 64-bit toolchain, we wouldn't want processing of the build
3344 config file for the 64-bit toolchain to reset the default toolchain to
3345 64-bit, we want to keep it 32-bits.
3346```
3347
3348#### **Argument**
3349
3350```
3351 toolchain_label
3352 Toolchain name.
3353```
3354
3355#### **Example**
3356
3357```
3358 # Set default toolchain only has an effect when run in the context of the
3359 # default toolchain. Pick the right one according to the current CPU
3360 # architecture.
3361 if (target_cpu == "x64") {
3362 set_default_toolchain("//toolchains:64")
3363 } else if (target_cpu == "x86") {
3364 set_default_toolchain("//toolchains:32")
3365 }
3366```
[email protected]449f3e42024-08-01 21:43:27 +08003367### **set_defaults**: Set default values for a target type. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003368
3369```
3370 set_defaults() { }
3371
3372 Sets the default values for a given target type. Whenever target_type_name is
3373 seen in the future, the values specified in set_default's block will be
3374 copied into the current scope.
3375
3376 When the target type is used, the variable copying is very strict. If a
3377 variable with that name is already in scope, the build will fail with an
3378 error.
3379
3380 set_defaults can be used for built-in target types ("executable",
3381 "shared_library", etc.) and custom ones defined via the "template" command.
3382 It can be called more than once and the most recent call in any scope will
3383 apply, but there is no way to refer to the previous defaults and modify them
3384 (each call to set_defaults must supply a complete list of all defaults it
3385 wants). If you want to share defaults, store them in a separate variable.
3386```
3387
3388#### **Example**
3389
3390```
3391 set_defaults("static_library") {
3392 configs = [ "//tools/mything:settings" ]
3393 }
3394
Nico Webere49cb722018-08-28 13:10:29 -04003395 static_library("mylib") {
Brett Wilson796ed472018-07-16 15:11:09 -07003396 # The configs will be auto-populated as above. You can remove it if
3397 # you don't want the default for a particular default:
3398 configs -= [ "//tools/mything:settings" ]
3399 }
3400```
[email protected]449f3e42024-08-01 21:43:27 +08003401### **split_list**: Splits a list into N different sub-lists. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003402
3403```
3404 result = split_list(input, n)
3405
3406 Given a list and a number N, splits the list into N sub-lists of
3407 approximately equal size. The return value is a list of the sub-lists. The
3408 result will always be a list of size N. If N is greater than the number of
3409 elements in the input, it will be padded with empty lists.
3410
3411 The expected use is to divide source files into smaller uniform chunks.
3412```
3413
3414#### **Example**
3415
3416```
3417 The code:
3418 mylist = [1, 2, 3, 4, 5, 6]
3419 print(split_list(mylist, 3))
3420
3421 Will print:
3422 [[1, 2], [3, 4], [5, 6]
3423```
[email protected]449f3e42024-08-01 21:43:27 +08003424### **string_join**: Concatenates a list of strings with a separator. [Back to Top](#gn-reference)
Keir Mierle6ae63302019-11-08 23:02:18 -08003425
3426```
3427 result = string_join(separator, strings)
3428
3429 Concatenate a list of strings with intervening occurrences of separator.
3430```
3431
3432#### **Examples**
3433
3434```
3435 string_join("", ["a", "b", "c"]) --> "abc"
3436 string_join("|", ["a", "b", "c"]) --> "a|b|c"
3437 string_join(", ", ["a", "b", "c"]) --> "a, b, c"
3438 string_join("s", ["", ""]) --> "s"
3439```
[email protected]449f3e42024-08-01 21:43:27 +08003440### **string_replace**: Replaces substring in the given string. [Back to Top](#gn-reference)
Petr Hosekc0744ed2018-08-04 16:13:59 -07003441
3442```
3443 result = string_replace(str, old, new[, max])
3444
3445 Returns a copy of the string str in which the occurrences of old have been
3446 replaced with new, optionally restricting the number of replacements. The
3447 replacement is performed sequentially, so if new contains old, it won't be
3448 replaced.
3449```
3450
3451#### **Example**
3452
3453```
3454 The code:
3455 mystr = "Hello, world!"
3456 print(string_replace(mystr, "world", "GN"))
3457
3458 Will print:
3459 Hello, GN!
3460```
[email protected]449f3e42024-08-01 21:43:27 +08003461### **string_split**: Split string into a list of strings. [Back to Top](#gn-reference)
Keir Mierle6ae63302019-11-08 23:02:18 -08003462
3463```
3464 result = string_split(str[, sep])
3465
3466 Split string into all substrings separated by separator and returns a list
3467 of the substrings between those separators.
3468
3469 If the separator argument is omitted, the split is by any whitespace, and
3470 any leading/trailing whitespace is ignored; similar to Python's str.split().
3471```
3472
3473#### **Examples without a separator (split on whitespace)**:
3474
3475```
3476 string_split("") --> []
3477 string_split("a") --> ["a"]
3478 string_split(" aa bb") --> ["aa", "bb"]
3479```
3480
3481#### **Examples with a separator (split on separators)**:
3482
3483```
3484 string_split("", "|") --> [""]
3485 string_split(" a b ", " ") --> ["", "", "a", "b", "", ""]
3486 string_split("aa+-bb+-c", "+-") --> ["aa", "bb", "c"]
3487```
[email protected]449f3e42024-08-01 21:43:27 +08003488### **template**: Define a template rule. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003489
3490```
3491 A template defines a custom name that acts like a function. It provides a way
3492 to add to the built-in target types.
3493
3494 The template() function is used to declare a template. To invoke the
3495 template, just use the name of the template like any other target type.
3496
3497 Often you will want to declare your template in a special file that other
3498 files will import (see "gn help import") so your template rule can be shared
3499 across build files.
3500```
3501
3502#### **Variables and templates**:
3503
3504```
3505 When you call template() it creates a closure around all variables currently
3506 in scope with the code in the template block. When the template is invoked,
3507 the closure will be executed.
3508
3509 When the template is invoked, the code in the caller is executed and passed
3510 to the template code as an implicit "invoker" variable. The template uses
3511 this to read state out of the invoking code.
3512
3513 One thing explicitly excluded from the closure is the "current directory"
3514 against which relative file names are resolved. The current directory will be
3515 that of the invoking code, since typically that code specifies the file
3516 names. This means all files internal to the template should use absolute
3517 names.
3518
3519 A template will typically forward some or all variables from the invoking
3520 scope to a target that it defines. Often, such variables might be optional.
3521 Use the pattern:
3522
3523 if (defined(invoker.deps)) {
3524 deps = invoker.deps
3525 }
3526
3527 The function forward_variables_from() provides a shortcut to forward one or
3528 more or possibly all variables in this manner:
3529
3530 forward_variables_from(invoker, ["deps", "public_deps"])
3531```
3532
3533#### **Target naming**
3534
3535```
3536 Your template should almost always define a built-in target with the name the
3537 template invoker specified. For example, if you have an IDL template and
3538 somebody does:
3539 idl("foo") {...
3540 you will normally want this to expand to something defining a source_set or
3541 static_library named "foo" (among other things you may need). This way, when
3542 another target specifies a dependency on "foo", the static_library or
3543 source_set will be linked.
3544
3545 It is also important that any other targets your template expands to have
3546 unique names, or you will get collisions.
3547
3548 Access the invoking name in your template via the implicit "target_name"
3549 variable. This should also be the basis for how other targets that a template
3550 expands to ensure uniqueness.
3551
3552 A typical example would be a template that defines an action to generate some
3553 source files, and a source_set to compile that source. Your template would
3554 name the source_set "target_name" because that's what you want external
3555 targets to depend on to link your code. And you would name the action
3556 something like "${target_name}_action" to make it unique. The source set
3557 would have a dependency on the action to make it run.
3558```
3559
3560#### **Overriding builtin targets**
3561
3562```
3563 You can use template to redefine a built-in target in which case your template
3564 takes a precedence over the built-in one. All uses of the target from within
3565 the template definition will refer to the built-in target which makes it
3566 possible to extend the behavior of the built-in target:
3567
3568 template("shared_library") {
3569 shared_library(shlib) {
Julie Hockette2a29402018-07-31 10:11:42 -07003570 forward_variables_from(invoker, "*")
Brett Wilson796ed472018-07-16 15:11:09 -07003571 ...
3572 }
3573 }
3574```
3575
3576#### **Example of defining a template**
3577
3578```
3579 template("my_idl") {
3580 # Be nice and help callers debug problems by checking that the variables
3581 # the template requires are defined. This gives a nice message rather than
3582 # giving the user an error about an undefined variable in the file defining
3583 # the template
3584 #
3585 # You can also use defined() to give default values to variables
3586 # unspecified by the invoker.
3587 assert(defined(invoker.sources),
3588 "Need sources in $target_name listing the idl files.")
3589
3590 # Name of the intermediate target that does the code gen. This must
3591 # incorporate the target name so it's unique across template
3592 # instantiations.
3593 code_gen_target_name = target_name + "_code_gen"
3594
3595 # Intermediate target to convert IDL to C source. Note that the name is
3596 # based on the name the invoker of the template specified. This way, each
3597 # time the template is invoked we get a unique intermediate action name
3598 # (since all target names are in the global scope).
3599 action_foreach(code_gen_target_name) {
3600 # Access the scope defined by the invoker via the implicit "invoker"
3601 # variable.
3602 sources = invoker.sources
3603
3604 # Note that we need an absolute path for our script file name. The
3605 # current directory when executing this code will be that of the invoker
3606 # (this is why we can use the "sources" directly above without having to
3607 # rebase all of the paths). But if we need to reference a script relative
3608 # to the template file, we'll need to use an absolute path instead.
3609 script = "//tools/idl/idl_code_generator.py"
3610
3611 # Tell GN how to expand output names given the sources.
3612 # See "gn help source_expansion" for more.
3613 outputs = [ "$target_gen_dir/{{source_name_part}}.cc",
3614 "$target_gen_dir/{{source_name_part}}.h" ]
3615 }
3616
3617 # Name the source set the same as the template invocation so instancing
3618 # this template produces something that other targets can link to in their
3619 # deps.
3620 source_set(target_name) {
3621 # Generates the list of sources, we get these from the action_foreach
3622 # above.
3623 sources = get_target_outputs(":$code_gen_target_name")
3624
3625 # This target depends on the files produced by the above code gen target.
3626 deps = [ ":$code_gen_target_name" ]
3627 }
3628 }
3629```
3630
3631#### **Example of invoking the resulting template**
3632
3633```
3634 # This calls the template code above, defining target_name to be
3635 # "foo_idl_files" and "invoker" to be the set of stuff defined in the curly
3636 # brackets.
3637 my_idl("foo_idl_files") {
3638 # Goes into the template as "invoker.sources".
3639 sources = [ "foo.idl", "bar.idl" ]
3640 }
3641
3642 # Here is a target that depends on our template.
3643 executable("my_exe") {
3644 # Depend on the name we gave the template call above. Internally, this will
3645 # produce a dependency from executable to the source_set inside the
3646 # template (since it has this name), which will in turn depend on the code
3647 # gen action.
3648 deps = [ ":foo_idl_files" ]
3649 }
3650```
[email protected]449f3e42024-08-01 21:43:27 +08003651### **tool**: Specify arguments to a toolchain tool. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07003652
3653#### **Usage**
3654
3655```
3656 tool() {
3657
3658 }
3659```
3660
3661#### **Tool types**
3662
3663```
3664 Compiler tools:
3665 "cc": C compiler
3666 "cxx": C++ compiler
Sylvain Defresne89e64252020-08-07 13:01:06 +02003667 "cxx_module": C++ compiler used for Clang .modulemap files
Brett Wilson796ed472018-07-16 15:11:09 -07003668 "objc": Objective C compiler
3669 "objcxx": Objective C++ compiler
3670 "rc": Resource compiler (Windows .rc files)
3671 "asm": Assembler
Sylvain Defresne89e64252020-08-07 13:01:06 +02003672 "swift": Swift compiler driver
Brett Wilson796ed472018-07-16 15:11:09 -07003673
3674 Linker tools:
3675 "alink": Linker for static libraries (archives)
3676 "solink": Linker for shared libraries
3677 "link": Linker for executables
3678
3679 Other tools:
3680 "stamp": Tool for creating stamp files
3681 "copy": Tool to copy files.
3682 "action": Defaults for actions
3683
3684 Platform specific tools:
3685 "copy_bundle_data": [iOS, macOS] Tool to copy files in a bundle.
3686 "compile_xcassets": [iOS, macOS] Tool to compile asset catalogs.
Julie Hockettce1fa072019-05-07 17:44:37 -07003687
3688 Rust tools:
Petr Hosek7617b592019-10-02 09:52:21 -07003689 "rust_bin": Tool for compiling Rust binaries
3690 "rust_cdylib": Tool for compiling C-compatible dynamic libraries.
3691 "rust_dylib": Tool for compiling Rust dynamic libraries.
3692 "rust_macro": Tool for compiling Rust procedural macros.
3693 "rust_rlib": Tool for compiling Rust libraries.
3694 "rust_staticlib": Tool for compiling Rust static libraries.
Brett Wilson796ed472018-07-16 15:11:09 -07003695```
3696
3697#### **Tool variables**
3698
3699```
3700 command [string with substitutions]
3701 Valid for: all tools except "action" (required)
3702
3703 The command to run.
3704
Joe Armstrong23d22bc2019-06-28 15:31:03 +08003705 command_launcher [string]
3706 Valid for: all tools except "action" (optional)
3707
3708 The prefix with which to launch the command (e.g. the path to a Goma or
3709 CCache compiler launcher).
3710
3711 Note that this prefix will not be included in the compilation database or
3712 IDE files generated from the build.
3713
Brett Wilson796ed472018-07-16 15:11:09 -07003714 default_output_dir [string with substitutions]
3715 Valid for: linker tools
3716
3717 Default directory name for the output file relative to the
3718 root_build_dir. It can contain other substitution patterns. This will
3719 be the default value for the {{output_dir}} expansion (discussed below)
3720 but will be overridden by the "output_dir" variable in a target, if one
3721 is specified.
3722
3723 GN doesn't do anything with this string other than pass it along,
3724 potentially with target-specific overrides. It is the tool's job to use
3725 the expansion so that the files will be in the right place.
3726
3727 default_output_extension [string]
3728 Valid for: linker tools
3729
3730 Extension for the main output of a linkable tool. It includes the
3731 leading dot. This will be the default value for the
3732 {{output_extension}} expansion (discussed below) but will be overridden
3733 by by the "output extension" variable in a target, if one is specified.
3734 Empty string means no extension.
3735
3736 GN doesn't actually do anything with this extension other than pass it
3737 along, potentially with target-specific overrides. One would typically
3738 use the {{output_extension}} value in the "outputs" to read this value.
3739
3740 Example: default_output_extension = ".exe"
3741
3742 depfile [string with substitutions]
3743 Valid for: compiler tools (optional)
3744
3745 If the tool can write ".d" files, this specifies the name of the
3746 resulting file. These files are used to list header file dependencies
3747 (or other implicit input dependencies) that are discovered at build
3748 time. See also "depsformat".
3749
3750 Example: depfile = "{{output}}.d"
3751
3752 depsformat [string]
3753 Valid for: compiler tools (when depfile is specified)
3754
3755 Format for the deps outputs. This is either "gcc" or "msvc". See the
3756 ninja documentation for "deps" for more information.
3757
3758 Example: depsformat = "gcc"
3759
3760 description [string with substitutions, optional]
3761 Valid for: all tools
3762
3763 What to print when the command is run.
3764
3765 Example: description = "Compiling {{source}}"
3766
Julie Hockettce1fa072019-05-07 17:44:37 -07003767 exe_output_extension [string, optional, rust tools only]
3768 rlib_output_extension [string, optional, rust tools only]
3769 dylib_output_extension [string, optional, rust tools only]
3770 cdylib_output_extension [string, optional, rust tools only]
Petr Hosekfe36c7c2019-11-26 14:38:08 -08003771 rust_proc_macro_output_extension [string, optional, rust tools only]
Julie Hockettce1fa072019-05-07 17:44:37 -07003772 Valid for: Rust tools
3773
3774 These specify the default tool output for each of the crate types.
3775 The default is empty for executables, shared, and static libraries and
3776 ".rlib" for rlibs. Note that the Rust compiler complains with an error
3777 if external crates do not take the form `lib.rlib` or
3778 `lib.`, where `` is `.so`,
3779 `.dylib`, or `.dll` as appropriate for the platform.
3780
Brett Wilson796ed472018-07-16 15:11:09 -07003781 lib_switch [string, optional, link tools only]
3782 lib_dir_switch [string, optional, link tools only]
3783 Valid for: Linker tools except "alink"
3784
3785 These strings will be prepended to the libraries and library search
Sylvain Defresnea09ec162020-01-16 12:36:40 +01003786 directories, respectively, because linkers differ on how to specify
3787 them.
3788
Brett Wilson796ed472018-07-16 15:11:09 -07003789 If you specified:
3790 lib_switch = "-l"
3791 lib_dir_switch = "-L"
Sylvain Defresnea09ec162020-01-16 12:36:40 +01003792 then the "{{libs}}" expansion for
3793 [ "freetype", "expat" ]
3794 would be
3795 "-lfreetype -lexpat".
3796
3797 framework_switch [string, optional, link tools only]
Robert Sesekd0a6f072020-05-15 11:21:22 -04003798 weak_framework_switch [string, optional, link tools only]
Sylvain Defresnea09ec162020-01-16 12:36:40 +01003799 framework_dir_switch [string, optional, link tools only]
3800 Valid for: Linker tools
3801
3802 These strings will be prepended to the frameworks and framework search
3803 path directories, respectively, because linkers differ on how to specify
3804 them.
3805
3806 If you specified:
3807 framework_switch = "-framework "
Robert Sesekd0a6f072020-05-15 11:21:22 -04003808 weak_framework_switch = "-weak_framework "
Sylvain Defresnea09ec162020-01-16 12:36:40 +01003809 framework_dir_switch = "-F"
Robert Sesekd0a6f072020-05-15 11:21:22 -04003810 and:
3811 framework_dirs = [ "$root_out_dir" ]
3812 frameworks = [ "UIKit.framework", "Foo.framework" ]
3813 weak_frameworks = [ "MediaPlayer.framework" ]
3814 would be:
3815 "-F. -framework UIKit -framework Foo -weak_framework MediaPlayer"
Brett Wilson796ed472018-07-16 15:11:09 -07003816
Sylvain Defresne89e64252020-08-07 13:01:06 +02003817 swiftmodule_switch [string, optional, link tools only]
3818 Valid for: Linker tools except "alink"
3819
3820 The string will be prependend to the path to the .swiftmodule files
3821 that are embedded in the linker output.
3822
3823 If you specified:
3824 swiftmodule_swift = "-Wl,-add_ast_path,"
3825 then the "{{swiftmodules}}" expansion for
3826 [ "obj/foo/Foo.swiftmodule" ]
3827 would be
3828 "-Wl,-add_ast_path,obj/foo/Foo.swiftmodule"
3829
danakj4fb095d2024-05-30 11:40:51 -04003830 rust_swiftmodule_switch [string, optional, link tools only]
3831 Valid for: Linker tools except "alink"
3832
3833 Like swiftmodule_switch, but for targets built/linked with the Rust
3834 compiler. The string will be prependend to the path to the
3835 .swiftmodule files that are embedded in the linker output.
3836
3837 If you specified:
3838 rust_swiftmodule_swift = "-Clink-arg=-Wl,-add_ast_path,"
3839 then the "{{swiftmodules}}" expansion for
3840 [ "obj/foo/Foo.swiftmodule" ]
3841 would be
3842 "-Clink-arg=-Wl,-add_ast_path,obj/foo/Foo.swiftmodule"
3843
Brett Wilson796ed472018-07-16 15:11:09 -07003844 outputs [list of strings with substitutions]
3845 Valid for: Linker and compiler tools (required)
3846
3847 An array of names for the output files the tool produces. These are
3848 relative to the build output directory. There must always be at least
3849 one output file. There can be more than one output (a linker might
3850 produce a library and an import library, for example).
3851
3852 This array just declares to GN what files the tool will produce. It is
3853 your responsibility to specify the tool command that actually produces
3854 these files.
3855
3856 If you specify more than one output for shared library links, you
3857 should consider setting link_output, depend_output, and
3858 runtime_outputs.
3859
3860 Example for a compiler tool that produces .obj files:
3861 outputs = [
3862 "{{source_out_dir}}/{{source_name_part}}.obj"
3863 ]
3864
3865 Example for a linker tool that produces a .dll and a .lib. The use of
3866 {{target_output_name}}, {{output_extension}} and {{output_dir}} allows
3867 the target to override these values.
3868 outputs = [
Nico Weberad9eab22020-11-15 22:20:28 -05003869 "{{output_dir}}/{{target_output_name}}{{output_extension}}",
Brett Wilson796ed472018-07-16 15:11:09 -07003870 "{{output_dir}}/{{target_output_name}}.lib",
3871 ]
3872
Sylvain Defresne89e64252020-08-07 13:01:06 +02003873 partial_outputs [list of strings with substitutions]
3874 Valid for: "swift" only
3875
3876 An array of names for the partial outputs the tool produces. These
3877 are relative to the build output directory. The expansion will be
3878 evaluated for each file listed in the "sources" of the target.
3879
3880 This is used to deal with whole module optimization, allowing to
3881 list one object file per source file when whole module optimization
3882 is disabled.
3883
Brett Wilson796ed472018-07-16 15:11:09 -07003884 pool [label, optional]
3885 Valid for: all tools (optional)
3886
3887 Label of the pool to use for the tool. Pools are used to limit the
3888 number of tasks that can execute concurrently during the build.
3889
3890 See also "gn help pool".
3891
3892 link_output [string with substitutions]
3893 depend_output [string with substitutions]
David 'Digit' Turnere3d088c2024-08-12 16:36:30 +02003894 Valid for: "solink", "rust_dylib" or "rust_cdylib" only (optional)
Brett Wilson796ed472018-07-16 15:11:09 -07003895
David 'Digit' Turnere3d088c2024-08-12 16:36:30 +02003896 These two files specify which of the outputs from the tool should
3897 be used for linking and dependency tracking. These should match entries
3898 in the "outputs". If unspecified, the first item in the "outputs" array
3899 will be used for all. See "Separate linking and dependencies for shared
3900 libraries" below for more.
Brett Wilson796ed472018-07-16 15:11:09 -07003901
3902 On Windows, where the tools produce a .dll shared library and a .lib
3903 import library, you will want the first two to be the import library
3904 and the third one to be the .dll file. On Linux, if you're not doing
3905 the separate linking/dependency optimization, all of these should be
3906 the .so output.
3907
3908 output_prefix [string]
3909 Valid for: Linker tools (optional)
3910
3911 Prefix to use for the output name. Defaults to empty. This prefix will
3912 be prepended to the name of the target (or the output_name if one is
3913 manually specified for it) if the prefix is not already there. The
3914 result will show up in the {{output_name}} substitution pattern.
3915
3916 Individual targets can opt-out of the output prefix by setting:
3917 output_prefix_override = true
3918 (see "gn help output_prefix_override").
3919
3920 This is typically used to prepend "lib" to libraries on
3921 Posix systems:
3922 output_prefix = "lib"
3923
3924 precompiled_header_type [string]
3925 Valid for: "cc", "cxx", "objc", "objcxx"
3926
3927 Type of precompiled headers. If undefined or the empty string,
3928 precompiled headers will not be used for this tool. Otherwise use "gcc"
3929 or "msvc".
3930
3931 For precompiled headers to be used for a given target, the target (or a
3932 config applied to it) must also specify a "precompiled_header" and, for
3933 "msvc"-style headers, a "precompiled_source" value. If the type is
3934 "gcc", then both "precompiled_header" and "precompiled_source" must
3935 resolve to the same file, despite the different formats required for
3936 each."
3937
3938 See "gn help precompiled_header" for more.
3939
3940 restat [boolean]
3941 Valid for: all tools (optional, defaults to false)
3942
3943 Requests that Ninja check the file timestamp after this tool has run to
3944 determine if anything changed. Set this if your tool has the ability to
3945 skip writing output if the output file has not changed.
3946
3947 Normally, Ninja will assume that when a tool runs the output be new and
3948 downstream dependents must be rebuild. When this is set to trye, Ninja
3949 can skip rebuilding downstream dependents for input changes that don't
3950 actually affect the output.
3951
3952 Example:
3953 restat = true
3954
3955 rspfile [string with substitutions]
3956 Valid for: all tools except "action" (optional)
3957
3958 Name of the response file. If empty, no response file will be
3959 used. See "rspfile_content".
3960
3961 rspfile_content [string with substitutions]
3962 Valid for: all tools except "action" (required when "rspfile" is used)
3963
3964 The contents to be written to the response file. This may include all
3965 or part of the command to send to the tool which allows you to get
3966 around OS command-line length limits.
3967
3968 This example adds the inputs and libraries to a response file, but
3969 passes the linker flags directly on the command line:
3970 tool("link") {
3971 command = "link -o {{output}} {{ldflags}} @{{output}}.rsp"
3972 rspfile = "{{output}}.rsp"
Adrian Taylorac6cc952020-04-26 20:49:18 -07003973 rspfile_content = "{{inputs}} {{solibs}} {{libs}} {{rlibs}}"
Brett Wilson796ed472018-07-16 15:11:09 -07003974 }
3975
3976 runtime_outputs [string list with substitutions]
3977 Valid for: linker tools
3978
3979 If specified, this list is the subset of the outputs that should be
3980 added to runtime deps (see "gn help runtime_deps"). By default (if
3981 runtime_outputs is empty or unspecified), it will be the link_output.
Adrian Taylor4aa9bdf2021-11-15 19:00:06 -08003982
3983 rust_sysroot
3984 Valid for: Rust tools
3985
3986 A path relative to root_out_dir. This is not used in the build
3987 process, but may be used when generating metadata for rust-analyzer.
3988 (See --export-rust-project). It enables such metadata to include
3989 information about the Rust standard library.
Adrian Taylore3978de2023-05-26 12:07:53 +01003990
3991 dynamic_link_switch
3992 Valid for: Rust tools which link
3993
3994 A switch to be optionally inserted into linker command lines
3995 to indicate that subsequent items may be dynamically linked.
3996 For ld-like linkers, -Clink-arg=-Bdynamic may be a good choice.
3997 This switch is inserted by gn into rustc command lines before
3998 listing any non-Rust dependencies. This may be necessary because
3999 sometimes rustc puts the linker into a mode where it would otherwise
4000 link against static libraries by default. This flag will be
4001 inserted into the {{rustdeps}} variable at the appropriate place;
4002 {{ldflags}} can't be used for the same purpose because the flags
4003 may not be inserted at the desired place in the command line.
Brett Wilson796ed472018-07-16 15:11:09 -07004004```
4005
4006#### **Expansions for tool variables**
4007
4008```
4009 All paths are relative to the root build directory, which is the current
4010 directory for running all tools. These expansions are available to all tools:
4011
4012 {{label}}
4013 The label of the current target. This is typically used in the
4014 "description" field for link tools. The toolchain will be omitted from
4015 the label for targets in the default toolchain, and will be included
4016 for targets in other toolchains.
4017
4018 {{label_name}}
4019 The short name of the label of the target. This is the part after the
4020 colon. For "//foo/bar:baz" this will be "baz". Unlike
4021 {{target_output_name}}, this is not affected by the "output_prefix" in
4022 the tool or the "output_name" set on the target.
4023
Scott Graham501b49a2020-08-05 13:03:37 -07004024 {{label_no_toolchain}}
4025 The label of the current target, never including the toolchain
4026 (otherwise, this is identical to {{label}}). This is used as the module
4027 name when using .modulemap files.
4028
Brett Wilson796ed472018-07-16 15:11:09 -07004029 {{output}}
4030 The relative path and name of the output(s) of the current build step.
4031 If there is more than one output, this will expand to a list of all of
4032 them. Example: "out/base/my_file.o"
4033
4034 {{target_gen_dir}}
4035 {{target_out_dir}}
4036 The directory of the generated file and output directories,
4037 respectively, for the current target. There is no trailing slash. See
4038 also {{output_dir}} for linker tools. Example: "out/base/test"
4039
4040 {{target_output_name}}
4041 The short name of the current target with no path information, or the
4042 value of the "output_name" variable if one is specified in the target.
4043 This will include the "output_prefix" if any. See also {{label_name}}.
4044
4045 Example: "libfoo" for the target named "foo" and an output prefix for
4046 the linker tool of "lib".
4047
4048 Compiler tools have the notion of a single input and a single output, along
4049 with a set of compiler-specific flags. The following expansions are
4050 available:
4051
4052 {{asmflags}}
4053 {{cflags}}
4054 {{cflags_c}}
4055 {{cflags_cc}}
4056 {{cflags_objc}}
4057 {{cflags_objcc}}
4058 {{defines}}
4059 {{include_dirs}}
4060 Strings correspond that to the processed flags/defines/include
4061 directories specified for the target.
4062 Example: "--enable-foo --enable-bar"
4063
4064 Defines will be prefixed by "-D" and include directories will be
4065 prefixed by "-I" (these work with Posix tools as well as Microsoft
4066 ones).
4067
Scott Graham484245b2020-08-11 10:58:50 -07004068 {{module_deps}}
4069 {{module_deps_no_self}}
4070 Strings that correspond to the flags necessary to depend upon the Clang
4071 modules referenced by the current target. The "_no_self" version doesn't
4072 include the module for the current target, and can be used to compile
4073 the pcm itself.
4074
Brett Wilson796ed472018-07-16 15:11:09 -07004075 {{source}}
4076 The relative path and name of the current input file.
4077 Example: "../../base/my_file.cc"
4078
4079 {{source_file_part}}
4080 The file part of the source including the extension (with no directory
4081 information).
4082 Example: "foo.cc"
4083
4084 {{source_name_part}}
4085 The filename part of the source file with no directory or extension.
4086 Example: "foo"
4087
4088 {{source_gen_dir}}
4089 {{source_out_dir}}
4090 The directory in the generated file and output directories,
4091 respectively, for the current input file. If the source file is in the
4092 same directory as the target is declared in, they will will be the same
4093 as the "target" versions above. Example: "gen/base/test"
4094
Julie Hockette2a29402018-07-31 10:11:42 -07004095 Linker tools have multiple inputs and (potentially) multiple outputs. The
Brett Wilson796ed472018-07-16 15:11:09 -07004096 static library tool ("alink") is not considered a linker tool. The following
4097 expansions are available:
4098
4099 {{inputs}}
4100 {{inputs_newline}}
4101 Expands to the inputs to the link step. This will be a list of object
4102 files and static libraries.
4103 Example: "obj/foo.o obj/bar.o obj/somelibrary.a"
4104
4105 The "_newline" version will separate the input files with newlines
4106 instead of spaces. This is useful in response files: some linkers can
4107 take a "-filelist" flag which expects newline separated files, and some
4108 Microsoft tools have a fixed-sized buffer for parsing each line of a
4109 response file.
4110
4111 {{ldflags}}
4112 Expands to the processed set of ldflags and library search paths
4113 specified for the target.
4114 Example: "-m64 -fPIC -pthread -L/usr/local/mylib"
4115
4116 {{libs}}
4117 Expands to the list of system libraries to link to. Each will be
4118 prefixed by the "lib_switch".
4119
Brett Wilson796ed472018-07-16 15:11:09 -07004120 Example: "-lfoo -lbar"
4121
4122 {{output_dir}}
4123 The value of the "output_dir" variable in the target, or the the value
4124 of the "default_output_dir" value in the tool if the target does not
4125 override the output directory. This will be relative to the
4126 root_build_dir and will not end in a slash. Will be "." for output to
4127 the root_build_dir.
4128
4129 This is subtly different than {{target_out_dir}} which is defined by GN
4130 based on the target's path and not overridable. {{output_dir}} is for
4131 the final output, {{target_out_dir}} is generally for object files and
4132 other outputs.
4133
4134 Usually {{output_dir}} would be defined in terms of either
4135 {{target_out_dir}} or {{root_out_dir}}
4136
4137 {{output_extension}}
4138 The value of the "output_extension" variable in the target, or the
4139 value of the "default_output_extension" value in the tool if the target
4140 does not specify an output extension.
4141 Example: ".so"
4142
4143 {{solibs}}
4144 Extra libraries from shared library dependencies not specified in the
4145 {{inputs}}. This is the list of link_output files from shared libraries
David 'Digit' Turnere3d088c2024-08-12 16:36:30 +02004146 (if the solink, rust_dylib and rust_cdylib tools specify a "link_output"
4147 variable separate from the "depend_output").
Brett Wilson796ed472018-07-16 15:11:09 -07004148
4149 These should generally be treated the same as libs by your tool.
4150
4151 Example: "libfoo.so libbar.so"
4152
Adrian Taylorac6cc952020-04-26 20:49:18 -07004153 {{rlibs}}
4154 Any Rust .rlibs which need to be linked into a final C++ target.
4155 These should be treated as {{inputs}} except that sometimes
4156 they might have different linker directives applied.
4157
4158 Example: "obj/foo/libfoo.rlib"
4159
Sylvain Defresnea09ec162020-01-16 12:36:40 +01004160 {{frameworks}}
4161 Shared libraries packaged as framework bundle. This is principally
4162 used on Apple's platforms (macOS and iOS). All name must be ending
4163 with ".framework" suffix; the suffix will be stripped when expanding
Robert Sesekd0a6f072020-05-15 11:21:22 -04004164 {{frameworks}} and each item will be preceded by "-framework" or
4165 "-weak_framework".
Sylvain Defresnea09ec162020-01-16 12:36:40 +01004166
Sylvain Defresne89e64252020-08-07 13:01:06 +02004167 {{swiftmodules}}
4168 Swift .swiftmodule files that needs to be embedded into the binary.
4169 This is necessary to correctly link with object generated by the
4170 Swift compiler (the .swiftmodule file cannot be embedded in object
4171 files directly). Those will be prefixed with "swiftmodule_switch"
4172 value.
4173
Brett Wilson796ed472018-07-16 15:11:09 -07004174 The static library ("alink") tool allows {{arflags}} plus the common tool
4175 substitutions.
4176
4177 The copy tool allows the common compiler/linker substitutions, plus
4178 {{source}} which is the source of the copy. The stamp tool allows only the
4179 common tool substitutions.
4180
4181 The copy_bundle_data and compile_xcassets tools only allows the common tool
4182 substitutions. Both tools are required to create iOS/macOS bundles and need
4183 only be defined on those platforms.
4184
4185 The copy_bundle_data tool will be called with one source and needs to copy
4186 (optionally optimizing the data representation) to its output. It may be
4187 called with a directory as input and it needs to be recursively copied.
4188
4189 The compile_xcassets tool will be called with one or more source (each an
4190 asset catalog) that needs to be compiled to a single output. The following
4191 substitutions are available:
4192
4193 {{inputs}}
4194 Expands to the list of .xcassets to use as input to compile the asset
4195 catalog.
4196
4197 {{bundle_product_type}}
4198 Expands to the product_type of the bundle that will contain the
4199 compiled asset catalog. Usually corresponds to the product_type
4200 property of the corresponding create_bundle target.
4201
4202 {{bundle_partial_info_plist}}
4203 Expands to the path to the partial Info.plist generated by the
4204 assets catalog compiler. Usually based on the target_name of
4205 the create_bundle target.
Julie Hockettce1fa072019-05-07 17:44:37 -07004206
Harley Li0a9affb2020-06-03 10:38:42 -04004207 {{xcasset_compiler_flags}}
4208 Expands to the list of flags specified in corresponding
4209 create_bundle target.
4210
Sylvain Defresne06cdcc82024-03-21 13:48:59 +01004211 The inputs for compile_xcassets tool will be found from the bundle_data
4212 dependencies by looking for any file matching "*/*.xcassets/*" pattern.
4213 The "$assets.xcassets" directory will be added as input to the tool.
4214
Sylvain Defresne89e64252020-08-07 13:01:06 +02004215 The Swift tool has multiple input and outputs. It must have exactly one
4216 output of .swiftmodule type, but can have one or more object file outputs,
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01004217 in addition to other type of outputs. The following expansions are available:
Sylvain Defresne89e64252020-08-07 13:01:06 +02004218
4219 {{module_name}}
4220 Expands to the string representing the module name of target under
4221 compilation (see "module_name" variable).
4222
4223 {{module_dirs}}
4224 Expands to the list of -I for the target Swift module search
4225 path computed from target dependencies.
4226
4227 {{swiftflags}}
4228 Expands to the list of strings representing Swift compiler flags.
4229
Julie Hockettce1fa072019-05-07 17:44:37 -07004230 Rust tools have the notion of a single input and a single output, along
4231 with a set of compiler-specific flags. The following expansions are
4232 available:
4233
4234 {{crate_name}}
4235 Expands to the string representing the crate name of target under
4236 compilation.
4237
4238 {{crate_type}}
4239 Expands to the string representing the type of crate for the target
4240 under compilation.
4241
4242 {{externs}}
4243 Expands to the list of --extern flags needed to include addition Rust
4244 libraries in this target. Includes any specified renamed dependencies.
4245
Julie Hockettce1fa072019-05-07 17:44:37 -07004246 {{rustdeps}}
4247 Expands to the list of -Ldependency= strings needed to compile
4248 this target.
4249
4250 {{rustenv}}
4251 Expands to the list of environment variables.
4252
4253 {{rustflags}}
4254 Expands to the list of strings representing Rust compiler flags.
Brett Wilson796ed472018-07-16 15:11:09 -07004255```
4256
4257#### **Separate linking and dependencies for shared libraries**
4258
4259```
4260 Shared libraries are special in that not all changes to them require that
4261 dependent targets be re-linked. If the shared library is changed but no
4262 imports or exports are different, dependent code needn't be relinked, which
4263 can speed up the build.
4264
4265 If your link step can output a list of exports from a shared library and
4266 writes the file only if the new one is different, the timestamp of this file
4267 can be used for triggering re-links, while the actual shared library would be
4268 used for linking.
4269
4270 You will need to specify
4271 restat = true
4272 in the linker tool to make this work, so Ninja will detect if the timestamp
4273 of the dependency file has changed after linking (otherwise it will always
4274 assume that running a command updates the output):
4275
4276 tool("solink") {
4277 command = "..."
4278 outputs = [
4279 "{{output_dir}}/{{target_output_name}}{{output_extension}}",
Nico Weberad9eab22020-11-15 22:20:28 -05004280 "{{output_dir}}/{{target_output_name}}{{output_extension}}.TOC",
Brett Wilson796ed472018-07-16 15:11:09 -07004281 ]
4282 link_output =
4283 "{{output_dir}}/{{target_output_name}}{{output_extension}}"
4284 depend_output =
Nico Weberad9eab22020-11-15 22:20:28 -05004285 "{{output_dir}}/{{target_output_name}}{{output_extension}}.TOC"
Brett Wilson796ed472018-07-16 15:11:09 -07004286 restat = true
4287 }
4288```
4289
4290#### **Example**
4291
4292```
4293 toolchain("my_toolchain") {
4294 # Put these at the top to apply to all tools below.
4295 lib_switch = "-l"
4296 lib_dir_switch = "-L"
4297
4298 tool("cc") {
4299 command = "gcc {{source}} -o {{output}}"
4300 outputs = [ "{{source_out_dir}}/{{source_name_part}}.o" ]
4301 description = "GCC {{source}}"
4302 }
4303 tool("cxx") {
4304 command = "g++ {{source}} -o {{output}}"
4305 outputs = [ "{{source_out_dir}}/{{source_name_part}}.o" ]
4306 description = "G++ {{source}}"
4307 }
4308 };
4309```
[email protected]449f3e42024-08-01 21:43:27 +08004310### **toolchain**: Defines a toolchain. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004311
4312```
4313 A toolchain is a set of commands and build flags used to compile the source
4314 code. The toolchain() function defines these commands.
4315```
4316
4317#### **Toolchain overview**
4318
4319```
4320 You can have more than one toolchain in use at once in a build and a target
4321 can exist simultaneously in multiple toolchains. A build file is executed
4322 once for each toolchain it is referenced in so the GN code can vary all
4323 parameters of each target (or which targets exist) on a per-toolchain basis.
4324
4325 When you have a simple build with only one toolchain, the build config file
4326 is loaded only once at the beginning of the build. It must call
4327 set_default_toolchain() (see "gn help set_default_toolchain") to tell GN the
4328 label of the toolchain definition to use. The "toolchain_args" section of the
4329 toolchain definition is ignored.
4330
4331 When a target has a dependency on a target using different toolchain (see "gn
4332 help labels" for how to specify this), GN will start a build using that
4333 secondary toolchain to resolve the target. GN will load the build config file
4334 with the build arguments overridden as specified in the toolchain_args.
4335 Because the default toolchain is already known, calls to
4336 set_default_toolchain() are ignored.
4337
4338 To load a file in an alternate toolchain, GN does the following:
4339
4340 1. Loads the file with the toolchain definition in it (as determined by the
4341 toolchain label).
4342 2. Re-runs the master build configuration file, applying the arguments
4343 specified by the toolchain_args section of the toolchain definition.
4344 3. Loads the destination build file in the context of the configuration file
4345 in the previous step.
4346
4347 The toolchain configuration is two-way. In the default toolchain (i.e. the
4348 main build target) the configuration flows from the build config file to the
4349 toolchain. The build config file looks at the state of the build (OS type,
4350 CPU architecture, etc.) and decides which toolchain to use (via
4351 set_default_toolchain()). In secondary toolchains, the configuration flows
4352 from the toolchain to the build config file: the "toolchain_args" in the
4353 toolchain definition specifies the arguments to re-invoke the build.
4354```
4355
4356#### **Functions and variables**
4357
4358```
4359 tool()
Julie Hockette2a29402018-07-31 10:11:42 -07004360 The tool() function call specifies the commands to run for a given step. See
4361 "gn help tool".
Brett Wilson796ed472018-07-16 15:11:09 -07004362
Julie Hockette2a29402018-07-31 10:11:42 -07004363 toolchain_args [scope]
Brett Wilson796ed472018-07-16 15:11:09 -07004364 Overrides for build arguments to pass to the toolchain when invoking it.
4365 This is a variable of type "scope" where the variable names correspond to
4366 variables in declare_args() blocks.
4367
4368 When you specify a target using an alternate toolchain, the master build
4369 configuration file is re-interpreted in the context of that toolchain.
4370 toolchain_args allows you to control the arguments passed into this
4371 alternate invocation of the build.
4372
4373 Any default system arguments or arguments passed in via "gn args" will also
4374 be passed to the alternate invocation unless explicitly overridden by
4375 toolchain_args.
4376
4377 The toolchain_args will be ignored when the toolchain being defined is the
4378 default. In this case, it's expected you want the default argument values.
4379
4380 See also "gn help buildargs" for an overview of these arguments.
4381
Julie Hockette2a29402018-07-31 10:11:42 -07004382 propagates_configs [boolean, default=false]
4383 Determines whether public_configs and all_dependent_configs in this
4384 toolchain propagate to targets in other toolchains.
4385
4386 When false (the default), this toolchain will not propagate any configs to
4387 targets in other toolchains that depend on it targets inside this
4388 toolchain. This matches the most common usage of toolchains where they
4389 represent different architectures or compilers and the settings that apply
4390 to one won't necessarily apply to others.
4391
4392 When true, configs (public and all-dependent) will cross the boundary out
4393 of this toolchain as if the toolchain boundary wasn't there. This only
4394 affects one direction of dependencies: a toolchain can't control whether
4395 it accepts such configs, only whether it pushes them. The build is
4396 responsible for ensuring that any external targets depending on targets in
4397 this toolchain are compatible with the compiler flags, etc. that may be
4398 propagated.
4399
4400 deps [string list]
Brett Wilson796ed472018-07-16 15:11:09 -07004401 Dependencies of this toolchain. These dependencies will be resolved before
4402 any target in the toolchain is compiled. To avoid circular dependencies
4403 these must be targets defined in another toolchain.
4404
4405 This is expressed as a list of targets, and generally these targets will
4406 always specify a toolchain:
4407 deps = [ "//foo/bar:baz(//build/toolchain:bootstrap)" ]
4408
4409 This concept is somewhat inefficient to express in Ninja (it requires a lot
4410 of duplicate of rules) so should only be used when absolutely necessary.
4411```
4412
4413#### **Example of defining a toolchain**
4414
4415```
4416 toolchain("32") {
4417 tool("cc") {
4418 command = "gcc {{source}}"
4419 ...
4420 }
4421
4422 toolchain_args = {
4423 use_doom_melon = true # Doom melon always required for 32-bit builds.
4424 current_cpu = "x86"
4425 }
4426 }
4427
4428 toolchain("64") {
4429 tool("cc") {
4430 command = "gcc {{source}}"
4431 ...
4432 }
4433
4434 toolchain_args = {
4435 # use_doom_melon is not overridden here, it will take the default.
4436 current_cpu = "x64"
4437 }
4438 }
4439```
4440
4441#### **Example of cross-toolchain dependencies**
4442
4443```
4444 If a 64-bit target wants to depend on a 32-bit binary, it would specify a
4445 dependency using data_deps (data deps are like deps that are only needed at
4446 runtime and aren't linked, since you can't link a 32-bit and a 64-bit
4447 library).
4448
4449 executable("my_program") {
4450 ...
4451 if (target_cpu == "x64") {
4452 # The 64-bit build needs this 32-bit helper.
4453 data_deps = [ ":helper(//toolchains:32)" ]
4454 }
4455 }
4456
4457 if (target_cpu == "x86") {
4458 # Our helper library is only compiled in 32-bits.
4459 shared_library("helper") {
4460 ...
4461 }
4462 }
4463```
[email protected]449f3e42024-08-01 21:43:27 +08004464### **write_file**: Write a file to disk. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004465
4466```
Julie Hockett09171292018-07-31 14:35:10 -07004467 write_file(filename, data, output_conversion = "")
Brett Wilson796ed472018-07-16 15:11:09 -07004468
4469 If data is a list, the list will be written one-item-per-line with no quoting
4470 or brackets.
4471
4472 If the file exists and the contents are identical to that being written, the
4473 file will not be updated. This will prevent unnecessary rebuilds of targets
4474 that depend on this file.
4475
4476 One use for write_file is to write a list of inputs to an script that might
4477 be too long for the command line. However, it is preferable to use response
4478 files for this purpose. See "gn help response_file_contents".
Brett Wilson796ed472018-07-16 15:11:09 -07004479```
4480
4481#### **Arguments**
4482
4483```
4484 filename
4485 Filename to write. This must be within the output directory.
4486
4487 data
4488 The list or string to write.
Julie Hockett09171292018-07-31 14:35:10 -07004489
4490 output_conversion
Sylvain Defresne72d5a6e2021-06-15 17:01:32 +02004491 Controls how the output is written. See `gn help io_conversion`.
Brett Wilson796ed472018-07-16 15:11:09 -07004492```
4493## Built-in predefined variables
4494
[email protected]449f3e42024-08-01 21:43:27 +08004495### **current_cpu**: The processor architecture of the current toolchain. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004496
4497```
4498 The build configuration usually sets this value based on the value of
4499 "host_cpu" (see "gn help host_cpu") and then threads this through the
4500 toolchain definitions to ensure that it always reflects the appropriate
4501 value.
4502
Julie Hockette2a29402018-07-31 10:11:42 -07004503 This value is not used internally by GN for any purpose. It is set to the
Brett Wilson796ed472018-07-16 15:11:09 -07004504 empty string ("") by default but is declared so that it can be overridden on
4505 the command line if so desired.
4506
4507 See "gn help target_cpu" for a list of common values returned.
4508```
[email protected]449f3e42024-08-01 21:43:27 +08004509### **current_os**: The operating system of the current toolchain. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004510
4511```
4512 The build configuration usually sets this value based on the value of
4513 "target_os" (see "gn help target_os"), and then threads this through the
4514 toolchain definitions to ensure that it always reflects the appropriate
4515 value.
4516
Julie Hockette2a29402018-07-31 10:11:42 -07004517 This value is not used internally by GN for any purpose. It is set to the
Brett Wilson796ed472018-07-16 15:11:09 -07004518 empty string ("") by default but is declared so that it can be overridden on
4519 the command line if so desired.
4520
4521 See "gn help target_os" for a list of common values returned.
4522```
[email protected]449f3e42024-08-01 21:43:27 +08004523### **current_toolchain**: Label of the current toolchain. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004524
4525```
4526 A fully-qualified label representing the current toolchain. You can use this
4527 to make toolchain-related decisions in the build. See also
4528 "default_toolchain".
4529```
4530
4531#### **Example**
4532
4533```
4534 if (current_toolchain == "//build:64_bit_toolchain") {
4535 executable("output_thats_64_bit_only") {
4536 ...
4537```
[email protected]449f3e42024-08-01 21:43:27 +08004538### **default_toolchain**: [string] Label of the default toolchain. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004539
4540```
4541 A fully-qualified label representing the default toolchain, which may not
4542 necessarily be the current one (see "current_toolchain").
4543```
[email protected]449f3e42024-08-01 21:43:27 +08004544### **gn_version**: [number] The version of gn. [Back to Top](#gn-reference)
James Robinson61377e32020-02-13 15:20:07 -08004545
4546```
4547 Corresponds to the number printed by `gn --version`.
4548```
4549
4550#### **Example**
4551
4552```
4553 assert(gn_version >= 1700, "need GN version 1700 for the frobulate feature")
4554```
[email protected]449f3e42024-08-01 21:43:27 +08004555### **host_cpu**: The processor architecture that GN is running on. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004556
4557```
4558 This is value is exposed so that cross-compile toolchains can access the host
4559 architecture when needed.
4560
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01004561 The value should generally be considered read-only, but it can be overridden
Brett Wilson796ed472018-07-16 15:11:09 -07004562 in order to handle unusual cases where there might be multiple plausible
4563 values for the host architecture (e.g., if you can do either 32-bit or 64-bit
4564 builds). The value is not used internally by GN for any purpose.
4565```
4566
4567#### **Some possible values**
4568
4569```
4570 - "x64"
4571 - "x86"
4572```
[email protected]449f3e42024-08-01 21:43:27 +08004573### **host_os**: [string] The operating system that GN is running on. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004574
4575```
4576 This value is exposed so that cross-compiles can access the host build
4577 system's settings.
4578
4579 This value should generally be treated as read-only. It, however, is not used
4580 internally by GN for any purpose.
4581```
4582
4583#### **Some possible values**
4584
4585```
4586 - "linux"
4587 - "mac"
4588 - "win"
4589```
[email protected]449f3e42024-08-01 21:43:27 +08004590### **invoker**: [string] The invoking scope inside a template. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004591
4592```
4593 Inside a template invocation, this variable refers to the scope of the
4594 invoker of the template. Outside of template invocations, this variable is
4595 undefined.
4596
4597 All of the variables defined inside the template invocation are accessible as
4598 members of the "invoker" scope. This is the way that templates read values
4599 set by the callers.
4600
4601 This is often used with "defined" to see if a value is set on the invoking
4602 scope.
4603
4604 See "gn help template" for more examples.
4605```
4606
4607#### **Example**
4608
4609```
4610 template("my_template") {
4611 print(invoker.sources) # Prints [ "a.cc", "b.cc" ]
4612 print(defined(invoker.foo)) # Prints false.
4613 print(defined(invoker.bar)) # Prints true.
4614 }
4615
4616 my_template("doom_melon") {
4617 sources = [ "a.cc", "b.cc" ]
4618 bar = 123
4619 }
4620```
[email protected]449f3e42024-08-01 21:43:27 +08004621### **python_path**: Absolute path of Python. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004622
4623```
4624 Normally used in toolchain definitions if running some command requires
4625 Python. You will normally not need this when invoking scripts since GN
4626 automatically finds it for you.
4627```
[email protected]449f3e42024-08-01 21:43:27 +08004628### **root_build_dir**: [string] Directory where build commands are run. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004629
4630```
4631 This is the root build output directory which will be the current directory
4632 when executing all compilers and scripts.
4633
4634 Most often this is used with rebase_path (see "gn help rebase_path") to
4635 convert arguments to be relative to a script's current directory.
4636```
[email protected]449f3e42024-08-01 21:43:27 +08004637### **root_gen_dir**: Directory for the toolchain's generated files. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004638
4639```
4640 Absolute path to the root of the generated output directory tree for the
4641 current toolchain. An example would be "//out/Debug/gen" for the default
4642 toolchain, or "//out/Debug/arm/gen" for the "arm" toolchain.
4643
4644 This is primarily useful for setting up include paths for generated files. If
4645 you are passing this to a script, you will want to pass it through
4646 rebase_path() (see "gn help rebase_path") to convert it to be relative to the
4647 build directory.
4648
4649 See also "target_gen_dir" which is usually a better location for generated
4650 files. It will be inside the root generated dir.
4651```
[email protected]449f3e42024-08-01 21:43:27 +08004652### **root_out_dir**: [string] Root directory for toolchain output files. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004653
4654```
4655 Absolute path to the root of the output directory tree for the current
4656 toolchain. It will not have a trailing slash.
4657
4658 For the default toolchain this will be the same as the root_build_dir. An
4659 example would be "//out/Debug" for the default toolchain, or
4660 "//out/Debug/arm" for the "arm" toolchain.
4661
4662 This is primarily useful for setting up script calls. If you are passing this
4663 to a script, you will want to pass it through rebase_path() (see "gn help
4664 rebase_path") to convert it to be relative to the build directory.
4665
4666 See also "target_out_dir" which is usually a better location for output
4667 files. It will be inside the root output dir.
4668```
4669
4670#### **Example**
4671
4672```
4673 action("myscript") {
4674 # Pass the output dir to the script.
4675 args = [ "-o", rebase_path(root_out_dir, root_build_dir) ]
4676 }
4677```
[email protected]449f3e42024-08-01 21:43:27 +08004678### **target_cpu**: The desired cpu architecture for the build. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004679
4680```
4681 This value should be used to indicate the desired architecture for the
4682 primary objects of the build. It will match the cpu architecture of the
4683 default toolchain, but not necessarily the current toolchain.
4684
4685 In many cases, this is the same as "host_cpu", but in the case of
4686 cross-compiles, this can be set to something different. This value is
4687 different from "current_cpu" in that it does not change based on the current
4688 toolchain. When writing rules, "current_cpu" should be used rather than
4689 "target_cpu" most of the time.
4690
4691 This value is not used internally by GN for any purpose, so it may be set to
4692 whatever value is needed for the build. GN defaults this value to the empty
4693 string ("") and the configuration files should set it to an appropriate value
4694 (e.g., setting it to the value of "host_cpu") if it is not overridden on the
4695 command line or in the args.gn file.
4696```
4697
4698#### **Possible values**
4699
4700```
4701 - "x86"
4702 - "x64"
4703 - "arm"
4704 - "arm64"
4705 - "mipsel"
Tyler Mandry4a648092022-02-15 19:47:09 +00004706 - "mips64el"
4707 - "s390x"
4708 - "ppc64"
4709 - "riscv32"
4710 - "riscv64"
4711 - "e2k"
4712 - "loong64"
Brett Wilson796ed472018-07-16 15:11:09 -07004713```
[email protected]449f3e42024-08-01 21:43:27 +08004714### **target_gen_dir**: Directory for a target's generated files. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004715
4716```
4717 Absolute path to the target's generated file directory. This will be the
4718 "root_gen_dir" followed by the relative path to the current build file. If
4719 your file is in "//tools/doom_melon" then target_gen_dir would be
4720 "//out/Debug/gen/tools/doom_melon". It will not have a trailing slash.
4721
4722 This is primarily useful for setting up include paths for generated files. If
4723 you are passing this to a script, you will want to pass it through
4724 rebase_path() (see "gn help rebase_path") to convert it to be relative to the
4725 build directory.
4726
4727 See also "gn help root_gen_dir".
4728```
4729
4730#### **Example**
4731
4732```
4733 action("myscript") {
4734 # Pass the generated output dir to the script.
Nico Weberad9eab22020-11-15 22:20:28 -05004735 args = [ "-o", rebase_path(target_gen_dir, root_build_dir) ]
Brett Wilson796ed472018-07-16 15:11:09 -07004736 }
4737```
[email protected]449f3e42024-08-01 21:43:27 +08004738### **target_name**: [string] The name of the current target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004739
4740```
4741 Inside a target or template invocation, this variable refers to the name
4742 given to the target or template invocation. Outside of these, this variable
4743 is undefined.
4744
4745 This is most often used in template definitions to name targets defined in
4746 the template based on the name of the invocation. This is necessary both to
4747 ensure generated targets have unique names and to generate a target with the
4748 exact name of the invocation that other targets can depend on.
4749
4750 Be aware that this value will always reflect the innermost scope. So when
4751 defining a target inside a template, target_name will refer to the target
4752 rather than the template invocation. To get the name of the template
4753 invocation in this case, you should save target_name to a temporary variable
4754 outside of any target definitions.
4755
4756 See "gn help template" for more examples.
4757```
4758
4759#### **Example**
4760
4761```
4762 executable("doom_melon") {
4763 print(target_name) # Prints "doom_melon".
4764 }
4765
4766 template("my_template") {
4767 print(target_name) # Prints "space_ray" when invoked below.
4768
4769 executable(target_name + "_impl") {
4770 print(target_name) # Prints "space_ray_impl".
4771 }
4772 }
4773
4774 my_template("space_ray") {
4775 }
4776```
[email protected]449f3e42024-08-01 21:43:27 +08004777### **target_os**: The desired operating system for the build. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004778
4779```
4780 This value should be used to indicate the desired operating system for the
4781 primary object(s) of the build. It will match the OS of the default
4782 toolchain.
4783
4784 In many cases, this is the same as "host_os", but in the case of
4785 cross-compiles, it may be different. This variable differs from "current_os"
4786 in that it can be referenced from inside any toolchain and will always return
4787 the initial value.
4788
4789 This should be set to the most specific value possible. So, "android" or
4790 "chromeos" should be used instead of "linux" where applicable, even though
4791 Android and ChromeOS are both Linux variants. This can mean that one needs to
4792 write
4793
4794 if (target_os == "android" || target_os == "linux") {
4795 # ...
4796 }
4797
4798 and so forth.
4799
4800 This value is not used internally by GN for any purpose, so it may be set to
4801 whatever value is needed for the build. GN defaults this value to the empty
4802 string ("") and the configuration files should set it to an appropriate value
4803 (e.g., setting it to the value of "host_os") if it is not set via the command
4804 line or in the args.gn file.
4805```
4806
4807#### **Possible values**
4808
4809```
4810 - "android"
4811 - "chromeos"
4812 - "ios"
4813 - "linux"
4814 - "nacl"
4815 - "mac"
4816 - "win"
4817```
[email protected]449f3e42024-08-01 21:43:27 +08004818### **target_out_dir**: [string] Directory for target output files. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004819
4820```
4821 Absolute path to the target's generated file directory. If your current
4822 target is in "//tools/doom_melon" then this value might be
4823 "//out/Debug/obj/tools/doom_melon". It will not have a trailing slash.
4824
4825 This is primarily useful for setting up arguments for calling scripts. If you
4826 are passing this to a script, you will want to pass it through rebase_path()
4827 (see "gn help rebase_path") to convert it to be relative to the build
4828 directory.
4829
4830 See also "gn help root_out_dir".
4831```
4832
4833#### **Example**
4834
4835```
4836 action("myscript") {
4837 # Pass the output dir to the script.
Nico Weberad9eab22020-11-15 22:20:28 -05004838 args = [ "-o", rebase_path(target_out_dir, root_build_dir) ]
Brett Wilson796ed472018-07-16 15:11:09 -07004839 }
4840```
4841## Variables you set in targets
4842
[email protected]449f3e42024-08-01 21:43:27 +08004843### **aliased_deps**: [scope] Set of crate-dependency pairs. [Back to Top](#gn-reference)
Julie Hockettce1fa072019-05-07 17:44:37 -07004844
4845```
4846 Valid for `rust_library` targets and `executable`, `static_library`, and
4847 `shared_library` targets that contain Rust sources.
4848
4849 A scope, each key indicating the renamed crate and the corresponding value
4850 specifying the label of the dependency producing the relevant binary.
4851
4852 All dependencies listed in this field *must* be listed as deps of the target.
4853
4854 executable("foo") {
4855 sources = [ "main.rs" ]
4856 deps = [ "//bar" ]
4857 }
4858
4859 This target would compile the `foo` crate with the following `extern` flag:
4860 `rustc ...command... --extern bar=/obj/bar`
4861
4862 executable("foo") {
4863 sources = [ "main.rs" ]
4864 deps = [ ":bar" ]
4865 aliased_deps = {
4866 bar_renamed = ":bar"
4867 }
4868 }
4869
4870 With the addition of `aliased_deps`, above target would instead compile with:
4871 `rustc ...command... --extern bar_renamed=/obj/bar`
4872```
[email protected]449f3e42024-08-01 21:43:27 +08004873### **all_dependent_configs**: Configs to be forced on dependents. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004874
4875```
4876 A list of config labels.
4877
4878 All targets depending on this one, and recursively, all targets depending on
4879 those, will have the configs listed in this variable added to them. These
4880 configs will also apply to the current target.
4881
4882 This addition happens in a second phase once a target and all of its
4883 dependencies have been resolved. Therefore, a target will not see these
4884 force-added configs in their "configs" variable while the script is running,
4885 and they can not be removed. As a result, this capability should generally
4886 only be used to add defines and include directories necessary to compile a
4887 target's headers.
4888
4889 See also "public_configs".
4890```
4891
4892#### **Ordering of flags and values**
4893
4894```
4895 1. Those set on the current target (not in a config).
4896 2. Those set on the "configs" on the target in order that the
4897 configs appear in the list.
4898 3. Those set on the "all_dependent_configs" on the target in order
4899 that the configs appear in the list.
4900 4. Those set on the "public_configs" on the target in order that
4901 those configs appear in the list.
4902 5. all_dependent_configs pulled from dependencies, in the order of
4903 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01004904 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07004905 6. public_configs pulled from dependencies, in the order of the
4906 "deps" list. If a dependency is public, they will be applied
4907 recursively.
4908```
[email protected]449f3e42024-08-01 21:43:27 +08004909### **allow_circular_includes_from**: Permit includes from deps. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004910
4911```
4912 A list of target labels. Must be a subset of the target's "deps". These
4913 targets will be permitted to include headers from the current target despite
4914 the dependency going in the opposite direction.
4915
4916 When you use this, both targets must be included in a final binary for it to
4917 link. To keep linker errors from happening, it is good practice to have all
4918 external dependencies depend only on one of the two targets, and to set the
4919 visibility on the other to enforce this. Thus the targets will always be
4920 linked together in any output.
4921```
4922
4923#### **Details**
4924
4925```
4926 Normally, for a file in target A to include a file from target B, A must list
4927 B as a dependency. This invariant is enforced by the "gn check" command (and
4928 the --check flag to "gn gen" -- see "gn help check").
4929
4930 Sometimes, two targets might be the same unit for linking purposes (two
4931 source sets or static libraries that would always be linked together in a
4932 final executable or shared library) and they each include headers from the
4933 other: you want A to be able to include B's headers, and B to include A's
4934 headers. This is not an ideal situation but is sometimes unavoidable.
4935
4936 This list, if specified, lists which of the dependencies of the current
4937 target can include header files from the current target. That is, if A
4938 depends on B, B can only include headers from A if it is in A's
4939 allow_circular_includes_from list. Normally includes must follow the
4940 direction of dependencies, this flag allows them to go in the opposite
4941 direction.
4942```
4943
4944#### **Danger**
4945
4946```
4947 In the above example, A's headers are likely to include headers from A's
4948 dependencies. Those dependencies may have public_configs that apply flags,
4949 defines, and include paths that make those headers work properly.
4950
4951 With allow_circular_includes_from, B can include A's headers, and
4952 transitively from A's dependencies, without having the dependencies that
4953 would bring in the public_configs those headers need. The result may be
4954 errors or inconsistent builds.
4955
4956 So when you use allow_circular_includes_from, make sure that any compiler
4957 settings, flags, and include directories are the same between both targets
4958 (consider putting such things in a shared config they can both reference).
4959 Make sure the dependencies are also the same (you might consider a group to
4960 collect such dependencies they both depend on).
4961```
4962
4963#### **Example**
4964
4965```
4966 source_set("a") {
4967 deps = [ ":b", ":a_b_shared_deps" ]
4968 allow_circular_includes_from = [ ":b" ]
4969 ...
4970 }
4971
4972 source_set("b") {
4973 deps = [ ":a_b_shared_deps" ]
4974 # Sources here can include headers from a despite lack of deps.
4975 ...
4976 }
4977
4978 group("a_b_shared_deps") {
4979 public_deps = [ ":c" ]
4980 }
4981```
[email protected]449f3e42024-08-01 21:43:27 +08004982### **arflags**: Arguments passed to static_library archiver. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07004983
4984```
4985 A list of flags passed to the archive/lib command that creates static
4986 libraries.
4987
4988 arflags are NOT pushed to dependents, so applying arflags to source sets or
4989 any other target type will be a no-op. As with ldflags, you could put the
4990 arflags in a config and set that as a public or "all dependent" config, but
4991 that will likely not be what you want. If you have a chain of static
4992 libraries dependent on each other, this can cause the flags to propagate up
4993 to other static libraries. Due to the nature of how arflags are typically
4994 used, you will normally want to apply them directly on static_library targets
4995 themselves.
4996```
4997
4998#### **Ordering of flags and values**
4999
5000```
5001 1. Those set on the current target (not in a config).
5002 2. Those set on the "configs" on the target in order that the
5003 configs appear in the list.
5004 3. Those set on the "all_dependent_configs" on the target in order
5005 that the configs appear in the list.
5006 4. Those set on the "public_configs" on the target in order that
5007 those configs appear in the list.
5008 5. all_dependent_configs pulled from dependencies, in the order of
5009 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005010 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005011 6. public_configs pulled from dependencies, in the order of the
5012 "deps" list. If a dependency is public, they will be applied
5013 recursively.
5014```
[email protected]449f3e42024-08-01 21:43:27 +08005015### **args**: (target variable) Arguments passed to an action. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005016
5017```
5018 For action and action_foreach targets, args is the list of arguments to pass
5019 to the script. Typically you would use source expansion (see "gn help
5020 source_expansion") to insert the source file names.
5021
Adrian Taylorc0d4f8b2022-03-25 15:05:57 -07005022 Args can also expand the substitution patterns corresponding to config
5023 variables in the same way that compiler tools (see "gn help tool") do. These
5024 allow actions that run compiler or compiler-like tools to access the results
5025 of propagating configs through the build graph. For example:
5026
5027 args = [ "{{defines}}", "{{include_dirs}}", "{{rustenv}}", "--input-file",
5028 "{{source}}" ]
5029
Brett Wilson796ed472018-07-16 15:11:09 -07005030 See also "gn help action" and "gn help action_foreach".
5031```
[email protected]449f3e42024-08-01 21:43:27 +08005032### **asmflags**: Flags passed to the assembler. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005033
5034```
5035 A list of strings.
5036
5037 "asmflags" are passed to any invocation of a tool that takes an .asm or .S
5038 file as input.
5039```
5040
5041#### **Ordering of flags and values**
5042
5043```
5044 1. Those set on the current target (not in a config).
5045 2. Those set on the "configs" on the target in order that the
5046 configs appear in the list.
5047 3. Those set on the "all_dependent_configs" on the target in order
5048 that the configs appear in the list.
5049 4. Those set on the "public_configs" on the target in order that
5050 those configs appear in the list.
5051 5. all_dependent_configs pulled from dependencies, in the order of
5052 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005053 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005054 6. public_configs pulled from dependencies, in the order of the
5055 "deps" list. If a dependency is public, they will be applied
5056 recursively.
5057```
[email protected]449f3e42024-08-01 21:43:27 +08005058### **assert_no_deps**: Ensure no deps on these targets. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005059
5060```
5061 A list of label patterns.
5062
5063 This list is a list of patterns that must not match any of the transitive
5064 dependencies of the target. These include all public, private, and data
5065 dependencies, and cross shared library boundaries. This allows you to express
5066 that undesirable code isn't accidentally added to downstream dependencies in
5067 a way that might otherwise be difficult to notice.
5068
5069 Checking does not cross executable boundaries. If a target depends on an
5070 executable, it's assumed that the executable is a tool that is producing part
5071 of the build rather than something that is linked and distributed. This
5072 allows assert_no_deps to express what is distributed in the final target
5073 rather than depend on the internal build steps (which may include
5074 non-distributable code).
5075
5076 See "gn help label_pattern" for the format of the entries in the list. These
5077 patterns allow blacklisting individual targets or whole directory
5078 hierarchies.
5079
5080 Sometimes it is desirable to enforce that many targets have no dependencies
5081 on a target or set of targets. One efficient way to express this is to create
5082 a group with the assert_no_deps rule on it, and make that group depend on all
5083 targets you want to apply that assertion to.
5084```
5085
5086#### **Example**
5087
5088```
5089 executable("doom_melon") {
5090 deps = [ "//foo:bar" ]
5091 ...
5092 assert_no_deps = [
5093 "//evil/*", # Don't link any code from the evil directory.
5094 "//foo:test_support", # This target is also disallowed.
5095 ]
5096 }
5097```
[email protected]449f3e42024-08-01 21:43:27 +08005098### **bridge_header**: [string] Path to C/Objective-C compatibility header. [Back to Top](#gn-reference)
Sylvain Defresne89e64252020-08-07 13:01:06 +02005099
5100```
5101 Valid for binary targets that contain Swift sources.
5102
5103 Path to an header that includes C/Objective-C functions and types that
5104 needs to be made available to the Swift module.
5105```
[email protected]449f3e42024-08-01 21:43:27 +08005106### **bundle_contents_dir**: Expansion of {{bundle_contents_dir}} in [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005107```
5108 create_bundle.
5109
5110 A string corresponding to a path in $root_build_dir.
5111
5112 This string is used by the "create_bundle" target to expand the
5113 {{bundle_contents_dir}} of the "bundle_data" target it depends on. This must
5114 correspond to a path under "bundle_root_dir".
5115
5116 See "gn help bundle_root_dir" for examples.
5117```
[email protected]449f3e42024-08-01 21:43:27 +08005118### **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 -07005119
5120```
5121 A list of target labels.
5122
5123 This list contains target label patterns that should be filtered out when
5124 creating the bundle. Any target matching one of those label will be removed
5125 from the dependencies of the create_bundle target.
5126
5127 This is mostly useful when creating application extension bundle as the
5128 application extension has access to runtime resources from the application
5129 bundle and thus do not require a second copy.
5130
5131 See "gn help create_bundle" for more information.
5132```
5133
5134#### **Example**
5135
5136```
5137 create_bundle("today_extension") {
5138 deps = [
5139 "//base"
5140 ]
5141 bundle_root_dir = "$root_out_dir/today_extension.appex"
5142 bundle_deps_filter = [
5143 # The extension uses //base but does not use any function calling into
5144 # third_party/icu and thus does not need the icudtl.dat file.
5145 "//third_party/icu:icudata",
5146 ]
5147 }
5148```
[email protected]449f3e42024-08-01 21:43:27 +08005149### **bundle_executable_dir** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005150
Joe Armstrongb199e542019-03-21 09:40:08 +08005151```
Sylvain Defresned46f92f2019-04-03 16:14:29 +02005152 bundle_executable_dir: Expansion of {{bundle_executable_dir}} in
5153 create_bundle.
5154
Brett Wilson796ed472018-07-16 15:11:09 -07005155 A string corresponding to a path in $root_build_dir.
5156
5157 This string is used by the "create_bundle" target to expand the
5158 {{bundle_executable_dir}} of the "bundle_data" target it depends on. This
5159 must correspond to a path under "bundle_root_dir".
5160
5161 See "gn help bundle_root_dir" for examples.
5162```
[email protected]449f3e42024-08-01 21:43:27 +08005163### **bundle_resources_dir** [Back to Top](#gn-reference)
Joe Armstrongb199e542019-03-21 09:40:08 +08005164
Brett Wilson796ed472018-07-16 15:11:09 -07005165```
Sylvain Defresned46f92f2019-04-03 16:14:29 +02005166 bundle_resources_dir: Expansion of {{bundle_resources_dir}} in
5167 create_bundle.
Brett Wilson796ed472018-07-16 15:11:09 -07005168
5169 A string corresponding to a path in $root_build_dir.
5170
5171 This string is used by the "create_bundle" target to expand the
5172 {{bundle_resources_dir}} of the "bundle_data" target it depends on. This must
5173 correspond to a path under "bundle_root_dir".
5174
5175 See "gn help bundle_root_dir" for examples.
5176```
[email protected]449f3e42024-08-01 21:43:27 +08005177### **bundle_root_dir**: Expansion of {{bundle_root_dir}} in create_bundle. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005178
5179```
5180 A string corresponding to a path in root_build_dir.
5181
5182 This string is used by the "create_bundle" target to expand the
5183 {{bundle_root_dir}} of the "bundle_data" target it depends on. This must
5184 correspond to a path under root_build_dir.
5185```
5186
5187#### **Example**
5188
5189```
5190 bundle_data("info_plist") {
5191 sources = [ "Info.plist" ]
5192 outputs = [ "{{bundle_contents_dir}}/Info.plist" ]
5193 }
5194
5195 create_bundle("doom_melon.app") {
5196 deps = [ ":info_plist" ]
5197 bundle_root_dir = "${root_build_dir}/doom_melon.app"
5198 bundle_contents_dir = "${bundle_root_dir}/Contents"
5199 bundle_resources_dir = "${bundle_contents_dir}/Resources"
5200 bundle_executable_dir = "${bundle_contents_dir}/MacOS"
Brett Wilson796ed472018-07-16 15:11:09 -07005201 }
5202```
[email protected]449f3e42024-08-01 21:43:27 +08005203### **cflags***: Flags passed to the C compiler. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005204
5205```
5206 A list of strings.
5207
5208 "cflags" are passed to all invocations of the C, C++, Objective C, and
5209 Objective C++ compilers.
5210
5211 To target one of these variants individually, use "cflags_c", "cflags_cc",
5212 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5213 versions of cflags* will be appended on the compiler command line after
5214 "cflags".
5215
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005216 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5217 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005218```
5219
5220#### **Ordering of flags and values**
5221
5222```
5223 1. Those set on the current target (not in a config).
5224 2. Those set on the "configs" on the target in order that the
5225 configs appear in the list.
5226 3. Those set on the "all_dependent_configs" on the target in order
5227 that the configs appear in the list.
5228 4. Those set on the "public_configs" on the target in order that
5229 those configs appear in the list.
5230 5. all_dependent_configs pulled from dependencies, in the order of
5231 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005232 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005233 6. public_configs pulled from dependencies, in the order of the
5234 "deps" list. If a dependency is public, they will be applied
5235 recursively.
5236```
[email protected]449f3e42024-08-01 21:43:27 +08005237### **cflags***: Flags passed to the C compiler. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005238
5239```
5240 A list of strings.
5241
5242 "cflags" are passed to all invocations of the C, C++, Objective C, and
5243 Objective C++ compilers.
5244
5245 To target one of these variants individually, use "cflags_c", "cflags_cc",
5246 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5247 versions of cflags* will be appended on the compiler command line after
5248 "cflags".
5249
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005250 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5251 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005252```
5253
5254#### **Ordering of flags and values**
5255
5256```
5257 1. Those set on the current target (not in a config).
5258 2. Those set on the "configs" on the target in order that the
5259 configs appear in the list.
5260 3. Those set on the "all_dependent_configs" on the target in order
5261 that the configs appear in the list.
5262 4. Those set on the "public_configs" on the target in order that
5263 those configs appear in the list.
5264 5. all_dependent_configs pulled from dependencies, in the order of
5265 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005266 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005267 6. public_configs pulled from dependencies, in the order of the
5268 "deps" list. If a dependency is public, they will be applied
5269 recursively.
5270```
[email protected]449f3e42024-08-01 21:43:27 +08005271### **cflags***: Flags passed to the C compiler. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005272
5273```
5274 A list of strings.
5275
5276 "cflags" are passed to all invocations of the C, C++, Objective C, and
5277 Objective C++ compilers.
5278
5279 To target one of these variants individually, use "cflags_c", "cflags_cc",
5280 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5281 versions of cflags* will be appended on the compiler command line after
5282 "cflags".
5283
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005284 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5285 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005286```
5287
5288#### **Ordering of flags and values**
5289
5290```
5291 1. Those set on the current target (not in a config).
5292 2. Those set on the "configs" on the target in order that the
5293 configs appear in the list.
5294 3. Those set on the "all_dependent_configs" on the target in order
5295 that the configs appear in the list.
5296 4. Those set on the "public_configs" on the target in order that
5297 those configs appear in the list.
5298 5. all_dependent_configs pulled from dependencies, in the order of
5299 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005300 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005301 6. public_configs pulled from dependencies, in the order of the
5302 "deps" list. If a dependency is public, they will be applied
5303 recursively.
5304```
[email protected]449f3e42024-08-01 21:43:27 +08005305### **cflags***: Flags passed to the C compiler. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005306
5307```
5308 A list of strings.
5309
5310 "cflags" are passed to all invocations of the C, C++, Objective C, and
5311 Objective C++ compilers.
5312
5313 To target one of these variants individually, use "cflags_c", "cflags_cc",
5314 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5315 versions of cflags* will be appended on the compiler command line after
5316 "cflags".
5317
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005318 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5319 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005320```
5321
5322#### **Ordering of flags and values**
5323
5324```
5325 1. Those set on the current target (not in a config).
5326 2. Those set on the "configs" on the target in order that the
5327 configs appear in the list.
5328 3. Those set on the "all_dependent_configs" on the target in order
5329 that the configs appear in the list.
5330 4. Those set on the "public_configs" on the target in order that
5331 those configs appear in the list.
5332 5. all_dependent_configs pulled from dependencies, in the order of
5333 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005334 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005335 6. public_configs pulled from dependencies, in the order of the
5336 "deps" list. If a dependency is public, they will be applied
5337 recursively.
5338```
[email protected]449f3e42024-08-01 21:43:27 +08005339### **cflags***: Flags passed to the C compiler. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005340
5341```
5342 A list of strings.
5343
5344 "cflags" are passed to all invocations of the C, C++, Objective C, and
5345 Objective C++ compilers.
5346
5347 To target one of these variants individually, use "cflags_c", "cflags_cc",
5348 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
5349 versions of cflags* will be appended on the compiler command line after
5350 "cflags".
5351
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01005352 See also "asmflags" for flags for assembly-language files, "swiftflags" for
5353 swift files, and "rustflags" for Rust files.
Brett Wilson796ed472018-07-16 15:11:09 -07005354```
5355
5356#### **Ordering of flags and values**
5357
5358```
5359 1. Those set on the current target (not in a config).
5360 2. Those set on the "configs" on the target in order that the
5361 configs appear in the list.
5362 3. Those set on the "all_dependent_configs" on the target in order
5363 that the configs appear in the list.
5364 4. Those set on the "public_configs" on the target in order that
5365 those configs appear in the list.
5366 5. all_dependent_configs pulled from dependencies, in the order of
5367 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005368 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005369 6. public_configs pulled from dependencies, in the order of the
5370 "deps" list. If a dependency is public, they will be applied
5371 recursively.
5372```
[email protected]449f3e42024-08-01 21:43:27 +08005373### **check_includes**: [boolean] Controls whether a target's files are checked. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005374
5375```
5376 When true (the default), the "gn check" command (as well as "gn gen" with the
5377 --check flag) will check this target's sources and headers for proper
5378 dependencies.
5379
5380 When false, the files in this target will be skipped by default. This does
5381 not affect other targets that depend on the current target, it just skips
5382 checking the includes of the current target's files.
5383
5384 If there are a few conditionally included headers that trip up checking, you
5385 can exclude headers individually by annotating them with "nogncheck" (see "gn
5386 help nogncheck").
5387
5388 The topic "gn help check" has general information on how checking works and
5389 advice on how to pass a check in problematic cases.
5390```
5391
5392#### **Example**
5393
5394```
5395 source_set("busted_includes") {
5396 # This target's includes are messed up, exclude it from checking.
5397 check_includes = false
5398 ...
5399 }
5400```
[email protected]449f3e42024-08-01 21:43:27 +08005401### **code_signing_args**: [string list] [deprecated] Args for the post-processing script. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005402
5403```
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005404 For create_bundle targets, post_processing_args is the list of arguments to
5405 pass to the post-processing script. Typically you would use source expansion
5406 (see "gn help source_expansion") to insert the source file names.
Brett Wilson796ed472018-07-16 15:11:09 -07005407
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005408 Deprecated: this is an old name for the "post_processing_args" property of
5409 the "create_bundle" target. It is still supported to avoid breaking existing
5410 build rules, but a warning will be emitted when it is used.
5411
5412 See also "gn help create_bundle" and "gn help post_processing_args".
Brett Wilson796ed472018-07-16 15:11:09 -07005413```
[email protected]449f3e42024-08-01 21:43:27 +08005414### **code_signing_outputs**: [file list] [deprecated] Outputs of the post-processing step. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005415
5416```
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005417 Outputs from the post-processing step of a create_bundle target. Must refer to
Brett Wilson796ed472018-07-16 15:11:09 -07005418 files in the build directory.
5419
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005420 Deprecated: this is an old name for the "post_processing_outputs" property of
5421 the "create_bundle" target. It is still supported to avoid breaking existing
5422 build rules, but a warning will be emitted when it is used.
5423
5424 See also "gn help create_bundle" and "gn help post_processing_args".
Brett Wilson796ed472018-07-16 15:11:09 -07005425```
[email protected]449f3e42024-08-01 21:43:27 +08005426### **code_signing_script**: [file name] [deprecated] Script for the post-processing step." [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005427
5428```
5429 An absolute or buildfile-relative file name of a Python script to run for a
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005430 create_bundle target to perform the post-processing step.
Brett Wilson796ed472018-07-16 15:11:09 -07005431
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005432 Deprecated: this is an old name for the "post_processing_script" property of
5433 the "create_bundle" target. It is still supported to avoid breaking existing
5434 build rules, but a warning will be emitted when it is used.
5435
5436 See also "gn help create_bundle" and "gn help post_processing_args".
Brett Wilson796ed472018-07-16 15:11:09 -07005437```
[email protected]449f3e42024-08-01 21:43:27 +08005438### **code_signing_sources**: [file list] [deprecated] Sources for the post-processing step. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005439
5440```
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005441 A list of files used as input for the post-processing step of a create_bundle
Brett Wilson796ed472018-07-16 15:11:09 -07005442 target. Non-absolute paths will be resolved relative to the current build
5443 file.
5444
Sylvain Defresnef07499a2024-04-04 13:06:37 +02005445 Deprecated: this is an old name for the "post_processing_sources" property of
5446 the "create_bundle" target. It is still supported to avoid breaking existing
5447 build rules, but a warning will be emitted when it is used.
5448
5449 See also "gn help create_bundle" and "gn help post_processing_args".
Brett Wilson796ed472018-07-16 15:11:09 -07005450```
[email protected]449f3e42024-08-01 21:43:27 +08005451### **complete_static_lib**: [boolean] Links all deps into a static library. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005452
5453```
5454 A static library normally doesn't include code from dependencies, but instead
5455 forwards the static libraries and source sets in its deps up the dependency
5456 chain until a linkable target (an executable or shared library) is reached.
5457 The final linkable target only links each static library once, even if it
5458 appears more than once in its dependency graph.
5459
5460 In some cases the static library might be the final desired output. For
5461 example, you may be producing a static library for distribution to third
5462 parties. In this case, the static library should include code for all
5463 dependencies in one complete package. However, complete static libraries
5464 themselves are never linked into other complete static libraries. All
5465 complete static libraries are for distribution and linking them in would
5466 cause code duplication in this case. If the static library is not for
5467 distribution, it should not be complete.
5468
5469 GN treats non-complete static libraries as source sets when they are linked
5470 into complete static libraries. This is done because some tools like AR do
5471 not handle dependent static libraries properly. This makes it easier to write
5472 "alink" rules.
5473
5474 In rare cases it makes sense to list a header in more than one target if it
5475 could be considered conceptually a member of both. libraries.
5476```
5477
5478#### **Example**
5479
5480```
5481 static_library("foo") {
5482 complete_static_lib = true
5483 deps = [ "bar" ]
5484 }
5485```
[email protected]449f3e42024-08-01 21:43:27 +08005486### **configs**: Configs applying to this target or config. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005487
5488```
5489 A list of config labels.
5490```
5491
5492#### **Configs on a target**
5493
5494```
5495 When used on a target, the include_dirs, defines, etc. in each config are
5496 appended in the order they appear to the compile command for each file in the
5497 target. They will appear after the include_dirs, defines, etc. that the
5498 target sets directly.
5499
5500 Since configs apply after the values set on a target, directly setting a
5501 compiler flag will prepend it to the command line. If you want to append a
5502 flag instead, you can put that flag in a one-off config and append that
5503 config to the target's configs list.
5504
5505 The build configuration script will generally set up the default configs
5506 applying to a given target type (see "set_defaults"). When a target is being
5507 defined, it can add to or remove from this list.
5508```
5509
5510#### **Configs on a config**
5511
5512```
5513 It is possible to create composite configs by specifying configs on a config.
5514 One might do this to forward values, or to factor out blocks of settings from
5515 very large configs into more manageable named chunks.
5516
5517 In this case, the composite config is expanded to be the concatenation of its
5518 own values, and in order, the values from its sub-configs *before* anything
5519 else happens. This has some ramifications:
5520
5521 - A target has no visibility into a config's sub-configs. Target code only
5522 sees the name of the composite config. It can't remove sub-configs or opt
5523 in to only parts of it. The composite config may not even be defined
5524 before the target is.
5525
5526 - You can get duplication of values if a config is listed twice, say, on a
5527 target and in a sub-config that also applies. In other cases, the configs
5528 applying to a target are de-duped. It's expected that if a config is
5529 listed as a sub-config that it is only used in that context. (Note that
5530 it's possible to fix this and de-dupe, but it's not normally relevant and
5531 complicates the implementation.)
5532```
5533
5534#### **Ordering of flags and values**
5535
5536```
5537 1. Those set on the current target (not in a config).
5538 2. Those set on the "configs" on the target in order that the
5539 configs appear in the list.
5540 3. Those set on the "all_dependent_configs" on the target in order
5541 that the configs appear in the list.
5542 4. Those set on the "public_configs" on the target in order that
5543 those configs appear in the list.
5544 5. all_dependent_configs pulled from dependencies, in the order of
5545 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005546 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005547 6. public_configs pulled from dependencies, in the order of the
5548 "deps" list. If a dependency is public, they will be applied
5549 recursively.
5550```
5551
5552#### **Example**
5553
5554```
5555 # Configs on a target.
5556 source_set("foo") {
5557 # Don't use the default RTTI config that BUILDCONFIG applied to us.
5558 configs -= [ "//build:no_rtti" ]
5559
5560 # Add some of our own settings.
5561 configs += [ ":mysettings" ]
5562 }
5563
5564 # Create a default_optimization config that forwards to one of a set of more
5565 # specialized configs depending on build flags. This pattern is useful
5566 # because it allows a target to opt in to either a default set, or a more
5567 # specific set, while avoid duplicating the settings in two places.
5568 config("super_optimization") {
5569 cflags = [ ... ]
5570 }
5571 config("default_optimization") {
5572 if (optimize_everything) {
5573 configs = [ ":super_optimization" ]
5574 } else {
5575 configs = [ ":no_optimization" ]
5576 }
5577 }
5578```
[email protected]449f3e42024-08-01 21:43:27 +08005579### **contents**: Contents to write to file. [Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08005580
5581```
5582 The contents of the file for a generated_file target.
5583 See "gn help generated_file".
5584```
[email protected]449f3e42024-08-01 21:43:27 +08005585### **crate_name**: [string] The name for the compiled crate. [Back to Top](#gn-reference)
Julie Hockettce1fa072019-05-07 17:44:37 -07005586
5587```
5588 Valid for `rust_library` targets and `executable`, `static_library`,
5589 `shared_library`, and `source_set` targets that contain Rust sources.
5590
5591 If crate_name is not set, then this rule will use the target name.
5592```
[email protected]449f3e42024-08-01 21:43:27 +08005593### **crate_root**: [string] The root source file for a binary or library. [Back to Top](#gn-reference)
Julie Hockettce1fa072019-05-07 17:44:37 -07005594
5595```
5596 Valid for `rust_library` targets and `executable`, `static_library`,
5597 `shared_library`, and `source_set` targets that contain Rust sources.
5598
5599 This file is usually the `main.rs` or `lib.rs` for binaries and libraries,
5600 respectively.
5601
5602 If crate_root is not set, then this rule will look for a lib.rs file (or
5603 main.rs for executable) or a single file in sources, if sources contains
5604 only one file.
5605```
[email protected]449f3e42024-08-01 21:43:27 +08005606### **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 -07005607
5608```
5609 Valid for `rust_library` targets and `executable`, `static_library`,
5610 `shared_library`, and `source_set` targets that contain Rust sources.
5611
5612 Options for this field are "cdylib", "staticlib", "proc-macro", and "dylib".
5613 This field sets the `crate-type` attribute for the `rustc` tool on static
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005614 libraries, as well as the appropriate output extension in the
Julie Hockettce1fa072019-05-07 17:44:37 -07005615 `rust_output_extension` attribute. Since outputs must be explicit, the `lib`
5616 crate type (where the Rust compiler produces what it thinks is the
5617 appropriate library type) is not supported.
5618
5619 It should be noted that the "dylib" crate type in Rust is unstable in the set
5620 of symbols it exposes, and most usages today are potentially wrong and will
5621 be broken in the future.
5622
5623 Static libraries, rust libraries, and executables have this field set
5624 automatically.
5625```
[email protected]449f3e42024-08-01 21:43:27 +08005626### **data**: Runtime data file dependencies. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005627
5628```
5629 Lists files or directories required to run the given target. These are
5630 typically data files or directories of data files. The paths are interpreted
5631 as being relative to the current build file. Since these are runtime
5632 dependencies, they do not affect which targets are built or when. To declare
5633 input files to a script, use "inputs".
5634
5635 Appearing in the "data" section does not imply any special handling such as
5636 copying them to the output directory. This is just used for declaring runtime
5637 dependencies. Runtime dependencies can be queried using the "runtime_deps"
5638 category of "gn desc" or written during build generation via
5639 "--runtime-deps-list-file".
5640
5641 GN doesn't require data files to exist at build-time. So actions that produce
5642 files that are in turn runtime dependencies can list those generated files
5643 both in the "outputs" list as well as the "data" list.
5644
5645 By convention, directories are listed with a trailing slash:
5646 data = [ "test/data/" ]
5647 However, no verification is done on these so GN doesn't enforce this. The
5648 paths are just rebased and passed along when requested.
5649
5650 Note: On iOS and macOS, create_bundle targets will not be recursed into when
5651 gathering data. See "gn help create_bundle" for details.
5652
5653 See "gn help runtime_deps" for how these are used.
5654```
[email protected]449f3e42024-08-01 21:43:27 +08005655### **data_deps**: Non-linked dependencies. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005656
5657```
5658 A list of target labels.
5659
5660 Specifies dependencies of a target that are not actually linked into the
5661 current target. Such dependencies will be built and will be available at
5662 runtime.
5663
5664 This is normally used for things like plugins or helper programs that a
5665 target needs at runtime.
5666
5667 Note: On iOS and macOS, create_bundle targets will not be recursed into when
5668 gathering data_deps. See "gn help create_bundle" for details.
5669
5670 See also "gn help deps" and "gn help data".
5671```
5672
5673#### **Example**
5674
5675```
5676 executable("foo") {
5677 deps = [ "//base" ]
5678 data_deps = [ "//plugins:my_runtime_plugin" ]
5679 }
5680```
[email protected]449f3e42024-08-01 21:43:27 +08005681### **data_keys**: Keys from which to collect metadata. [Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08005682
5683```
5684 These keys are used to identify metadata to collect. If a walked target
5685 defines this key in its metadata, its value will be appended to the resulting
5686 collection.
5687
5688 See "gn help generated_file".
5689```
[email protected]449f3e42024-08-01 21:43:27 +08005690### **defines**: C preprocessor defines. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005691
5692```
5693 A list of strings
5694
5695 These strings will be passed to the C/C++ compiler as #defines. The strings
5696 may or may not include an "=" to assign a value.
5697```
5698
5699#### **Ordering of flags and values**
5700
5701```
5702 1. Those set on the current target (not in a config).
5703 2. Those set on the "configs" on the target in order that the
5704 configs appear in the list.
5705 3. Those set on the "all_dependent_configs" on the target in order
5706 that the configs appear in the list.
5707 4. Those set on the "public_configs" on the target in order that
5708 those configs appear in the list.
5709 5. all_dependent_configs pulled from dependencies, in the order of
5710 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005711 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005712 6. public_configs pulled from dependencies, in the order of the
5713 "deps" list. If a dependency is public, they will be applied
5714 recursively.
5715```
5716
5717#### **Example**
5718
5719```
5720 defines = [ "AWESOME_FEATURE", "LOG_LEVEL=3" ]
5721```
[email protected]449f3e42024-08-01 21:43:27 +08005722### **depfile**: [string] File name for input dependencies for actions. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005723
5724```
5725 If nonempty, this string specifies that the current action or action_foreach
5726 target will generate the given ".d" file containing the dependencies of the
5727 input. Empty or unset means that the script doesn't generate the files.
5728
5729 A depfile should be used only when a target depends on files that are not
5730 already specified by a target's inputs and sources. Likewise, depfiles should
5731 specify only those dependencies not already included in sources or inputs.
5732
5733 The .d file should go in the target output directory. If you have more than
5734 one source file that the script is being run over, you can use the output
5735 file expansions described in "gn help action_foreach" to name the .d file
Nico Weberad9eab22020-11-15 22:20:28 -05005736 according to the input.
Brett Wilson796ed472018-07-16 15:11:09 -07005737
5738 The format is that of a Makefile and all paths must be relative to the root
5739 build directory. Only one output may be listed and it must match the first
5740 output of the action.
5741
5742 Although depfiles are created by an action, they should not be listed in the
5743 action's "outputs" unless another target will use the file as an input.
5744```
5745
5746#### **Example**
5747
5748```
5749 action_foreach("myscript_target") {
5750 script = "myscript.py"
5751 sources = [ ... ]
5752
5753 # Locate the depfile in the output directory named like the
5754 # inputs but with a ".d" appended.
Hector Dearman84c84312023-01-29 11:50:02 +00005755 depfile = "$target_gen_dir/{{source_name_part}}.d"
Brett Wilson796ed472018-07-16 15:11:09 -07005756
5757 # Say our script uses "-o " to indicate the depfile.
Hector Dearman84c84312023-01-29 11:50:02 +00005758 args = [ "{{source}}", "-o", rebase_path(depfile, root_build_dir)]
Brett Wilson796ed472018-07-16 15:11:09 -07005759 }
5760```
[email protected]449f3e42024-08-01 21:43:27 +08005761### **deps**: Private linked dependencies. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005762
5763```
5764 A list of target labels.
5765
5766 Specifies private dependencies of a target. Private dependencies are
5767 propagated up the dependency tree and linked to dependent targets, but do not
5768 grant the ability to include headers from the dependency. Public configs are
5769 not forwarded.
5770```
5771
5772#### **Details of dependency propagation**
5773
5774```
5775 Source sets, shared libraries, and non-complete static libraries will be
5776 propagated up the dependency tree across groups, non-complete static
5777 libraries and source sets.
5778
5779 Executables, shared libraries, and complete static libraries will link all
5780 propagated targets and stop propagation. Actions and copy steps also stop
5781 propagation, allowing them to take a library as an input but not force
5782 dependents to link to it.
5783
5784 Propagation of all_dependent_configs and public_configs happens independently
5785 of target type. all_dependent_configs are always propagated across all types
5786 of targets, and public_configs are always propagated across public deps of
5787 all types of targets.
5788
danakj2a92efd2023-07-06 14:16:38 -04005789 For Rust targets, deps ensures that Rust code can refer to the dependency
5790 target. If the dependency is a C/C++ target, the path to that target will
5791 be made available to Rust for `#[link]` directives.
5792
Brett Wilson796ed472018-07-16 15:11:09 -07005793 Data dependencies are propagated differently. See "gn help data_deps" and
5794 "gn help runtime_deps".
5795
5796 See also "public_deps".
5797```
[email protected]449f3e42024-08-01 21:43:27 +08005798### **externs**: [scope] Set of Rust crate-dependency pairs. [Back to Top](#gn-reference)
Petr Hoseka1413862020-01-03 12:54:33 -08005799
5800```
5801 A list, each value being a scope indicating a pair of crate name and the path
5802 to the Rust library.
5803
5804 These libraries will be passed as `--extern crate_name=path` to compiler
5805 invocation containing the current target.
5806```
5807
5808#### **Examples**
5809
5810```
5811 executable("foo") {
5812 sources = [ "main.rs" ]
5813 externs = [{
5814 crate_name = "bar",
5815 path = "path/to/bar.rlib"
5816 }]
5817 }
5818
5819 This target would compile the `foo` crate with the following `extern` flag:
5820 `--extern bar=path/to/bar.rlib`.
5821```
[email protected]449f3e42024-08-01 21:43:27 +08005822### **framework_dirs**: [directory list] Additional framework search directories. [Back to Top](#gn-reference)
Sylvain Defresnea09ec162020-01-16 12:36:40 +01005823
5824```
5825 A list of source directories.
5826
5827 The directories in this list will be added to the framework search path for
5828 the files in the affected target.
5829```
5830
5831#### **Ordering of flags and values**
5832
5833```
5834 1. Those set on the current target (not in a config).
5835 2. Those set on the "configs" on the target in order that the
5836 configs appear in the list.
5837 3. Those set on the "all_dependent_configs" on the target in order
5838 that the configs appear in the list.
5839 4. Those set on the "public_configs" on the target in order that
5840 those configs appear in the list.
5841 5. all_dependent_configs pulled from dependencies, in the order of
5842 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005843 more than once, only the first occurrence will be used.
Sylvain Defresnea09ec162020-01-16 12:36:40 +01005844 6. public_configs pulled from dependencies, in the order of the
5845 "deps" list. If a dependency is public, they will be applied
5846 recursively.
5847```
5848
5849#### **Example**
5850
5851```
5852 framework_dirs = [ "src/include", "//third_party/foo" ]
5853```
[email protected]449f3e42024-08-01 21:43:27 +08005854### **frameworks**: [name list] Name of frameworks that must be linked. [Back to Top](#gn-reference)
Sylvain Defresnea09ec162020-01-16 12:36:40 +01005855
5856```
5857 A list of framework names.
5858
5859 The frameworks named in that list will be linked with any dynamic link
5860 type target.
5861```
5862
5863#### **Ordering of flags and values**
5864
5865```
5866 1. Those set on the current target (not in a config).
5867 2. Those set on the "configs" on the target in order that the
5868 configs appear in the list.
5869 3. Those set on the "all_dependent_configs" on the target in order
5870 that the configs appear in the list.
5871 4. Those set on the "public_configs" on the target in order that
5872 those configs appear in the list.
5873 5. all_dependent_configs pulled from dependencies, in the order of
5874 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005875 more than once, only the first occurrence will be used.
Sylvain Defresnea09ec162020-01-16 12:36:40 +01005876 6. public_configs pulled from dependencies, in the order of the
5877 "deps" list. If a dependency is public, they will be applied
5878 recursively.
5879```
5880
5881#### **Example**
5882
5883```
5884 frameworks = [ "Foundation.framework", "Foo.framework" ]
5885```
[email protected]449f3e42024-08-01 21:43:27 +08005886### **friend**: Allow targets to include private headers. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005887
5888```
5889 A list of label patterns (see "gn help label_pattern") that allow dependent
5890 targets to include private headers. Applies to all binary targets.
5891
5892 Normally if a target lists headers in the "public" list (see "gn help
5893 public"), other headers are implicitly marked as private. Private headers
5894 can not be included by other targets, even with a public dependency path.
5895 The "gn check" function performs this validation.
5896
5897 A friend declaration allows one or more targets to include private headers.
5898 This is useful for things like unit tests that are closely associated with a
5899 target and require internal knowledge without opening up all headers to be
5900 included by all dependents.
5901
5902 A friend target does not allow that target to include headers when no
5903 dependency exists. A public dependency path must still exist between two
5904 targets to include any headers from a destination target. The friend
5905 annotation merely allows the use of headers that would otherwise be
5906 prohibited because they are private.
5907
5908 The friend annotation is matched only against the target containing the file
5909 with the include directive. Friend annotations are not propagated across
5910 public or private dependencies. Friend annotations do not affect visibility.
5911```
5912
5913#### **Example**
5914
5915```
5916 static_library("lib") {
5917 # This target can include our private headers.
5918 friend = [ ":unit_tests" ]
5919
5920 public = [
5921 "public_api.h", # Normal public API for dependent targets.
5922 ]
5923
5924 # Private API and sources.
5925 sources = [
5926 "a_source_file.cc",
5927
5928 # Normal targets that depend on this one won't be able to include this
5929 # because this target defines a list of "public" headers. Without the
5930 # "public" list, all headers are implicitly public.
5931 "private_api.h",
5932 ]
5933 }
5934
5935 executable("unit_tests") {
5936 sources = [
5937 # This can include "private_api.h" from the :lib target because it
5938 # depends on that target and because of the friend annotation.
5939 "my_test.cc",
5940 ]
5941
5942 deps = [
5943 ":lib", # Required for the include to be allowed.
5944 ]
5945 }
5946```
[email protected]449f3e42024-08-01 21:43:27 +08005947### **gen_deps**: Declares targets that should generate when this one does. [Back to Top](#gn-reference)
Tyler Mandry4a648092022-02-15 19:47:09 +00005948
5949```
5950 A list of target labels.
5951
5952 Not all GN targets that get evaluated are actually turned into ninja targets
5953 (see "gn help execution"). If this target is generated, then any targets in
Ricardo Ribalda85bd0a62023-11-11 16:30:19 +00005954 the "gen_deps" list will also be generated, regardless of the usual criteria.
Tyler Mandry4a648092022-02-15 19:47:09 +00005955
5956 Since "gen_deps" are not build time dependencies, there can be cycles between
5957 "deps" and "gen_deps" or within "gen_deps" itself.
5958```
[email protected]449f3e42024-08-01 21:43:27 +08005959### **include_dirs**: Additional include directories. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005960
5961```
5962 A list of source directories.
5963
5964 The directories in this list will be added to the include path for the files
5965 in the affected target.
5966```
5967
5968#### **Ordering of flags and values**
5969
5970```
5971 1. Those set on the current target (not in a config).
5972 2. Those set on the "configs" on the target in order that the
5973 configs appear in the list.
5974 3. Those set on the "all_dependent_configs" on the target in order
5975 that the configs appear in the list.
5976 4. Those set on the "public_configs" on the target in order that
5977 those configs appear in the list.
5978 5. all_dependent_configs pulled from dependencies, in the order of
5979 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01005980 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07005981 6. public_configs pulled from dependencies, in the order of the
5982 "deps" list. If a dependency is public, they will be applied
5983 recursively.
5984```
5985
5986#### **Example**
5987
5988```
5989 include_dirs = [ "src/include", "//third_party/foo" ]
5990```
[email protected]449f3e42024-08-01 21:43:27 +08005991### **inputs**: Additional compile-time dependencies. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07005992
5993```
5994 Inputs are compile-time dependencies of the current target. This means that
5995 all inputs must be available before compiling any of the sources or executing
5996 any actions.
5997
5998 Inputs are typically only used for action and action_foreach targets.
5999```
6000
6001#### **Inputs for actions**
6002
6003```
6004 For action and action_foreach targets, inputs should be the inputs to script
6005 that don't vary. These should be all .py files that the script uses via
6006 imports (the main script itself will be an implicit dependency of the action
6007 so need not be listed).
6008
6009 For action targets, inputs and sources are treated the same, but from a style
6010 perspective, it's recommended to follow the same rule as action_foreach and
6011 put helper files in the inputs, and the data used by the script (if any) in
6012 sources.
6013
6014 Note that another way to declare input dependencies from an action is to have
6015 the action write a depfile (see "gn help depfile"). This allows the script to
6016 dynamically write input dependencies, that might not be known until actually
6017 executing the script. This is more efficient than doing processing while
6018 running GN to determine the inputs, and is easier to keep in-sync than
6019 hardcoding the list.
6020```
6021
6022#### **Script input gotchas**
6023
6024```
6025 It may be tempting to write a script that enumerates all files in a directory
6026 as inputs. Don't do this! Even if you specify all the files in the inputs or
6027 sources in the GN target (or worse, enumerate the files in an exec_script
6028 call when running GN, which will be slow), the dependencies will be broken.
6029
6030 The problem happens if a file is ever removed because the inputs are not
6031 listed on the command line to the script. Because the script hasn't changed
6032 and all inputs are up to date, the script will not re-run and you will get a
6033 stale build. Instead, either list all inputs on the command line to the
6034 script, or if there are many, create a separate list file that the script
6035 reads. As long as this file is listed in the inputs, the build will detect
6036 when it has changed in any way and the action will re-run.
6037```
6038
6039#### **Inputs for binary targets**
6040
6041```
Julie Hockette2a29402018-07-31 10:11:42 -07006042 Any input dependencies will be resolved before compiling any sources or
6043 linking the target. Normally, all actions that a target depends on will be run
6044 before any files in a target are compiled. So if you depend on generated
6045 headers, you do not typically need to list them in the inputs section.
Brett Wilson796ed472018-07-16 15:11:09 -07006046
6047 Inputs for binary targets will be treated as implicit dependencies, meaning
6048 that changes in any of the inputs will force all sources in the target to be
6049 recompiled. If an input only applies to a subset of source files, you may
6050 want to split those into a separate target to avoid unnecessary recompiles.
6051```
6052
6053#### **Example**
6054
6055```
6056 action("myscript") {
6057 script = "domything.py"
6058 inputs = [ "input.data" ]
6059 }
6060```
[email protected]449f3e42024-08-01 21:43:27 +08006061### **ldflags**: Flags passed to the linker. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006062
6063```
6064 A list of strings.
6065
6066 These flags are passed on the command-line to the linker and generally
6067 specify various linking options. Most targets will not need these and will
6068 use "libs" and "lib_dirs" instead.
6069
6070 ldflags are NOT pushed to dependents, so applying ldflags to source sets or
6071 static libraries will be a no-op. If you want to apply ldflags to dependent
6072 targets, put them in a config and set it in the all_dependent_configs or
6073 public_configs.
6074```
6075
6076#### **Ordering of flags and values**
6077
6078```
6079 1. Those set on the current target (not in a config).
6080 2. Those set on the "configs" on the target in order that the
6081 configs appear in the list.
6082 3. Those set on the "all_dependent_configs" on the target in order
6083 that the configs appear in the list.
6084 4. Those set on the "public_configs" on the target in order that
6085 those configs appear in the list.
6086 5. all_dependent_configs pulled from dependencies, in the order of
6087 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006088 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07006089 6. public_configs pulled from dependencies, in the order of the
6090 "deps" list. If a dependency is public, they will be applied
6091 recursively.
6092```
[email protected]449f3e42024-08-01 21:43:27 +08006093### **lib_dirs**: Additional library directories. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006094
6095```
6096 A list of directories.
6097
6098 Specifies additional directories passed to the linker for searching for the
6099 required libraries. If an item is not an absolute path, it will be treated as
6100 being relative to the current build file.
6101
6102 libs and lib_dirs work differently than other flags in two respects.
Joe Armstrong23d22bc2019-06-28 15:31:03 +08006103 First, they are inherited across static library boundaries until a
Brett Wilson796ed472018-07-16 15:11:09 -07006104 shared library or executable target is reached. Second, they are
6105 uniquified so each one is only passed once (the first instance of it
6106 will be the one used).
6107```
6108
6109#### **Ordering of flags and values**
6110
6111```
6112 1. Those set on the current target (not in a config).
6113 2. Those set on the "configs" on the target in order that the
6114 configs appear in the list.
6115 3. Those set on the "all_dependent_configs" on the target in order
6116 that the configs appear in the list.
6117 4. Those set on the "public_configs" on the target in order that
6118 those configs appear in the list.
6119 5. all_dependent_configs pulled from dependencies, in the order of
6120 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006121 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07006122 6. public_configs pulled from dependencies, in the order of the
6123 "deps" list. If a dependency is public, they will be applied
6124 recursively.
6125
6126 For "libs" and "lib_dirs" only, the values propagated from
6127 dependencies (as described above) are applied last assuming they
6128 are not already in the list.
6129```
6130
6131#### **Example**
6132
6133```
6134 lib_dirs = [ "/usr/lib/foo", "lib/doom_melon" ]
6135```
[email protected]449f3e42024-08-01 21:43:27 +08006136### **libs**: Additional libraries to link. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006137
6138```
6139 A list of library names or library paths.
6140
6141 These libraries will be linked into the final binary (executable or shared
6142 library) containing the current target.
6143
6144 libs and lib_dirs work differently than other flags in two respects.
Joe Armstrong23d22bc2019-06-28 15:31:03 +08006145 First, they are inherited across static library boundaries until a
Brett Wilson796ed472018-07-16 15:11:09 -07006146 shared library or executable target is reached. Second, they are
6147 uniquified so each one is only passed once (the first instance of it
6148 will be the one used).
6149```
6150
6151#### **Types of libs**
6152
6153```
6154 There are several different things that can be expressed in libs:
6155
6156 File paths
6157 Values containing '/' will be treated as references to files in the
6158 checkout. They will be rebased to be relative to the build directory and
6159 specified in the "libs" for linker tools. This facility should be used
6160 for libraries that are checked in to the version control. For libraries
6161 that are generated by the build, use normal GN deps to link them.
6162
6163 System libraries
6164 Values not containing '/' will be treated as system library names. These
6165 will be passed unmodified to the linker and prefixed with the
6166 "lib_switch" attribute of the linker tool. Generally you would set the
6167 "lib_dirs" so the given library is found. Your BUILD.gn file should not
6168 specify the switch (like "-l"): this will be encoded in the "lib_switch"
6169 of the tool.
Brett Wilson796ed472018-07-16 15:11:09 -07006170```
6171
6172#### **Ordering of flags and values**
6173
6174```
6175 1. Those set on the current target (not in a config).
6176 2. Those set on the "configs" on the target in order that the
6177 configs appear in the list.
6178 3. Those set on the "all_dependent_configs" on the target in order
6179 that the configs appear in the list.
6180 4. Those set on the "public_configs" on the target in order that
6181 those configs appear in the list.
6182 5. all_dependent_configs pulled from dependencies, in the order of
6183 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006184 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07006185 6. public_configs pulled from dependencies, in the order of the
6186 "deps" list. If a dependency is public, they will be applied
6187 recursively.
6188
6189 For "libs" and "lib_dirs" only, the values propagated from
6190 dependencies (as described above) are applied last assuming they
6191 are not already in the list.
6192```
6193
6194#### **Examples**
6195
6196```
6197 On Windows:
6198 libs = [ "ctl3d.lib" ]
6199
6200 On Linux:
6201 libs = [ "ld" ]
6202```
[email protected]449f3e42024-08-01 21:43:27 +08006203### **metadata**: Metadata of this target. [Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08006204
6205```
6206 Metadata is a collection of keys and values relating to a particular target.
Julie Hockettd69a9c32019-01-23 14:36:18 -08006207 Values must be lists, allowing for sane and predictable collection behavior.
6208 Generally, these keys will include three types of lists: lists of ordinary
6209 strings, lists of filenames intended to be rebased according to their
6210 particular source directory, and lists of target labels intended to be used
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006211 as barriers to the walk. Verification of these categories occurs at walk time,
Julie Hockettd69a9c32019-01-23 14:36:18 -08006212 not creation time (since it is not clear until the walk which values are
6213 intended for which purpose).
6214```
Nate Fischer8ed01d32019-01-08 17:32:01 -08006215
Julie Hockettd69a9c32019-01-23 14:36:18 -08006216#### **Example**
Nate Fischer8ed01d32019-01-08 17:32:01 -08006217
Julie Hockettd69a9c32019-01-23 14:36:18 -08006218```
Nate Fischer8ed01d32019-01-08 17:32:01 -08006219 group("doom_melon") {
6220 metadata = {
6221 # These keys are not built in to GN but are interpreted when consuming
6222 # metadata.
6223 my_barrier = []
6224 my_files = [ "a.txt", "b.txt" ]
6225 }
6226 }
6227```
[email protected]449f3e42024-08-01 21:43:27 +08006228### **mnemonic**: [string] Prefix displayed when ninja runs this action. [Back to Top](#gn-reference)
Joseph Ryanad1e5ce2023-04-26 13:48:01 -07006229
6230```
6231 Tools in GN can set their ninja "description" which is displayed when
6232 building a target. These are commonly set with the format "CXX $output"
6233 or "LINK $label". By default, all GN actions will have the description
6234 "ACTION $label". Setting a mnemonic will override the "ACTION" prefix
6235 with another string, but the label will still be unconditionally displayed.
6236
6237 Whitespace is not allowed within a mnemonic.
6238```
[email protected]449f3e42024-08-01 21:43:27 +08006239### **module_name**: [string] The name for the compiled module. [Back to Top](#gn-reference)
Sylvain Defresne89e64252020-08-07 13:01:06 +02006240
6241```
6242 Valid for binary targets that contain Swift sources.
6243
6244 If module_name is not set, then this rule will use the target name.
6245```
[email protected]449f3e42024-08-01 21:43:27 +08006246### **output_conversion**: Data format for generated_file targets. [Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08006247
6248```
6249 Controls how the "contents" of a generated_file target is formatted.
Sylvain Defresne72d5a6e2021-06-15 17:01:32 +02006250 See `gn help io_conversion`.
Nate Fischer8ed01d32019-01-08 17:32:01 -08006251```
[email protected]449f3e42024-08-01 21:43:27 +08006252### **output_dir**: [directory] Directory to put output file in. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006253
6254```
6255 For library and executable targets, overrides the directory for the final
6256 output. This must be in the root_build_dir or a child thereof.
6257
6258 This should generally be in the root_out_dir or a subdirectory thereof (the
6259 root_out_dir will be the same as the root_build_dir for the default
6260 toolchain, and will be a subdirectory for other toolchains). Not putting the
6261 output in a subdirectory of root_out_dir can result in collisions between
6262 different toolchains, so you will need to take steps to ensure that your
6263 target is only present in one toolchain.
6264
6265 Normally the toolchain specifies the output directory for libraries and
6266 executables (see "gn help tool"). You will have to consult that for the
6267 default location. The default location will be used if output_dir is
6268 undefined or empty.
6269```
6270
6271#### **Example**
6272
6273```
6274 shared_library("doom_melon") {
6275 output_dir = "$root_out_dir/plugin_libs"
6276 ...
6277 }
6278```
[email protected]449f3e42024-08-01 21:43:27 +08006279### **output_extension**: Value to use for the output's file extension. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006280
6281```
6282 Normally the file extension for a target is based on the target type and the
6283 operating system, but in rare cases you will need to override the name (for
6284 example to use "libfreetype.so.6" instead of libfreetype.so on Linux).
6285
6286 This value should not include a leading dot. If undefined, the default
6287 specified on the tool will be used. If set to the empty string, no output
6288 extension will be used.
6289
6290 The output_extension will be used to set the "{{output_extension}}" expansion
6291 which the linker tool will generally use to specify the output file name. See
6292 "gn help tool".
6293```
6294
6295#### **Example**
6296
6297```
6298 shared_library("freetype") {
6299 if (is_linux) {
6300 # Call the output "libfreetype.so.6"
6301 output_extension = "so.6"
6302 }
6303 ...
6304 }
6305
6306 # On Windows, generate a "mysettings.cpl" control panel applet. Control panel
6307 # applets are actually special shared libraries.
6308 if (is_win) {
6309 shared_library("mysettings") {
6310 output_extension = "cpl"
6311 ...
6312 }
6313 }
6314```
[email protected]449f3e42024-08-01 21:43:27 +08006315### **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 -07006316
6317```
6318 Normally the output name of a target will be based on the target name, so the
6319 target "//foo/bar:bar_unittests" will generate an output file such as
6320 "bar_unittests.exe" (using Windows as an example).
6321
6322 Sometimes you will want an alternate name to avoid collisions or if the
6323 internal name isn't appropriate for public distribution.
6324
6325 The output name should have no extension or prefixes, these will be added
6326 using the default system rules. For example, on Linux an output name of "foo"
6327 will produce a shared library "libfoo.so". There is no way to override the
6328 output prefix of a linker tool on a per- target basis. If you need more
6329 flexibility, create a copy target to produce the file you want.
6330
6331 This variable is valid for all binary output target types.
6332```
6333
6334#### **Example**
6335
6336```
6337 static_library("doom_melon") {
6338 output_name = "fluffy_bunny"
6339 }
6340```
[email protected]449f3e42024-08-01 21:43:27 +08006341### **output_prefix_override**: Don't use prefix for output name. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006342
6343```
6344 A boolean that overrides the output prefix for a target. Defaults to false.
6345
6346 Some systems use prefixes for the names of the final target output file. The
6347 normal example is "libfoo.so" on Linux for a target named "foo".
6348
6349 The output prefix for a given target type is specified on the linker tool
6350 (see "gn help tool"). Sometimes this prefix is undesired.
6351
6352 See also "gn help output_extension".
6353```
6354
6355#### **Example**
6356
6357```
6358 shared_library("doom_melon") {
6359 # Normally this will produce "libdoom_melon.so" on Linux. Setting this flag
6360 # will produce "doom_melon.so".
6361 output_prefix_override = true
6362 ...
6363 }
6364```
[email protected]449f3e42024-08-01 21:43:27 +08006365### **outputs**: Output files for actions and copy targets. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006366
6367```
6368 Outputs is valid for "copy", "action", and "action_foreach" target types and
6369 indicates the resulting files. Outputs must always refer to files in the
6370 build directory.
6371
6372 copy
6373 Copy targets should have exactly one entry in the outputs list. If there is
6374 exactly one source, this can be a literal file name or a source expansion.
6375 If there is more than one source, this must contain a source expansion to
6376 map a single input name to a single output name. See "gn help copy".
6377
6378 action_foreach
6379 Action_foreach targets must always use source expansions to map input files
6380 to output files. There can be more than one output, which means that each
6381 invocation of the script will produce a set of files (presumably based on
6382 the name of the input file). See "gn help action_foreach".
6383
6384 action
6385 Action targets (excluding action_foreach) must list literal output file(s)
6386 with no source expansions. See "gn help action".
6387```
[email protected]449f3e42024-08-01 21:43:27 +08006388### **partial_info_plist**: [filename] Path plist from asset catalog compiler. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006389
6390```
6391 Valid for create_bundle target, corresponds to the path for the partial
6392 Info.plist created by the asset catalog compiler that needs to be merged
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006393 with the application Info.plist (usually done by the post-processing script).
Brett Wilson796ed472018-07-16 15:11:09 -07006394
6395 The file will be generated regardless of whether the asset compiler has
6396 been invoked or not. See "gn help create_bundle".
6397```
[email protected]449f3e42024-08-01 21:43:27 +08006398### **pool**: Label of the pool used by binary targets actions. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006399
6400```
Petr Hosek7a6231e2022-10-22 23:14:18 +00006401 A fully-qualified label representing the pool that will be used for binary
6402 targets and actions. Pools are defined using the pool() {...} declaration.
Brett Wilson796ed472018-07-16 15:11:09 -07006403```
6404
6405#### **Example**
6406
6407```
Petr Hosek7a6231e2022-10-22 23:14:18 +00006408 executable("binary") {
6409 pool = "//build:custom_pool"
6410 ...
6411 }
6412
Brett Wilson796ed472018-07-16 15:11:09 -07006413 action("action") {
6414 pool = "//build:custom_pool"
6415 ...
6416 }
6417```
[email protected]449f3e42024-08-01 21:43:27 +08006418### **post_processing_args**: [string list] Args for the post-processing script. [Back to Top](#gn-reference)
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006419
6420```
6421 For create_bundle targets, post_processing_args is the list of arguments to
6422 pass to the post-processing script. Typically you would use source expansion
6423 (see "gn help source_expansion") to insert the source file names.
6424
6425 See also "gn help create_bundle".
6426```
[email protected]449f3e42024-08-01 21:43:27 +08006427### **post_processing_outputs**: [file list] Outputs of the post-processing step. [Back to Top](#gn-reference)
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006428
6429```
6430 Outputs from the post-processing step of a create_bundle target. Must refer to
6431 files in the build directory.
6432
6433 See also "gn help create_bundle".
6434```
[email protected]449f3e42024-08-01 21:43:27 +08006435### **post_processing_script**: [file name] Script for the post-processing step." [Back to Top](#gn-reference)
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006436
6437```
6438 An absolute or buildfile-relative file name of a Python script to run for a
6439 create_bundle target to perform the post-processing step.
6440
6441 See also "gn help create_bundle".
6442```
[email protected]449f3e42024-08-01 21:43:27 +08006443### **post_processing_sources**: [file list] Sources for the post-processing step. [Back to Top](#gn-reference)
Sylvain Defresnef07499a2024-04-04 13:06:37 +02006444
6445```
6446 A list of files used as input for the post-processing step of a create_bundle
6447 target. Non-absolute paths will be resolved relative to the current build
6448 file.
6449
6450 See also "gn help create_bundle".
6451```
[email protected]449f3e42024-08-01 21:43:27 +08006452### **precompiled_header**: [string] Header file to precompile. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006453
6454```
6455 Precompiled headers will be used when a target specifies this value, or a
6456 config applying to this target specifies this value. In addition, the tool
6457 corresponding to the source files must also specify precompiled headers (see
6458 "gn help tool"). The tool will also specify what type of precompiled headers
6459 to use, by setting precompiled_header_type to either "gcc" or "msvc".
6460
6461 The precompiled header/source variables can be specified on a target or a
6462 config, but must be the same for all configs applying to a given target since
6463 a target can only have one precompiled header.
6464
6465 If you use both C and C++ sources, the precompiled header and source file
6466 will be compiled once per language. You will want to make sure to wrap C++
6467 includes in __cplusplus #ifdefs so the file will compile in C mode.
6468```
6469
6470#### **GCC precompiled headers**
6471
6472```
6473 When using GCC-style precompiled headers, "precompiled_source" contains the
6474 path of a .h file that is precompiled and then included by all source files
6475 in targets that set "precompiled_source".
6476
6477 The value of "precompiled_header" is not used with GCC-style precompiled
6478 headers.
6479```
6480
6481#### **MSVC precompiled headers**
6482
6483```
6484 When using MSVC-style precompiled headers, the "precompiled_header" value is
6485 a string corresponding to the header. This is NOT a path to a file that GN
6486 recognises, but rather the exact string that appears in quotes after
6487 an #include line in source code. The compiler will match this string against
6488 includes or forced includes (/FI).
6489
6490 MSVC also requires a source file to compile the header with. This must be
6491 specified by the "precompiled_source" value. In contrast to the header value,
6492 this IS a GN-style file name, and tells GN which source file to compile to
6493 make the .pch file used for subsequent compiles.
6494
6495 For example, if the toolchain specifies MSVC headers:
6496
6497 toolchain("vc_x64") {
6498 ...
6499 tool("cxx") {
6500 precompiled_header_type = "msvc"
6501 ...
6502
6503 You might make a config like this:
6504
6505 config("use_precompiled_headers") {
6506 precompiled_header = "build/precompile.h"
6507 precompiled_source = "//build/precompile.cc"
6508
6509 # Either your source files should #include "build/precompile.h"
6510 # first, or you can do this to force-include the header.
6511 cflags = [ "/FI$precompiled_header" ]
6512 }
6513
6514 And then define a target that uses the config:
6515
6516 executable("doom_melon") {
6517 configs += [ ":use_precompiled_headers" ]
6518 ...
6519```
[email protected]449f3e42024-08-01 21:43:27 +08006520### **precompiled_header_type**: [string] "gcc" or "msvc". [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006521
6522```
6523 See "gn help precompiled_header".
6524```
[email protected]449f3e42024-08-01 21:43:27 +08006525### **precompiled_source**: [file name] Source file to precompile. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006526
6527```
6528 The source file that goes along with the precompiled_header when using
6529 "msvc"-style precompiled headers. It will be implicitly added to the sources
6530 of the target. See "gn help precompiled_header".
6531```
[email protected]449f3e42024-08-01 21:43:27 +08006532### **product_type**: [string] Product type for the bundle. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006533
6534```
Sylvain Defresnee5aee7b2023-06-08 10:08:10 -04006535 Valid for "create_bundle" and "bundle_data" targets.
Brett Wilson796ed472018-07-16 15:11:09 -07006536
Sylvain Defresnee5aee7b2023-06-08 10:08:10 -04006537 Correspond to the type of the bundle. Used by transparent "create_bundle"
6538 target to control whether a "bundle_data" needs to be propagated or not.
6539
6540 When generating Xcode project, the product_type is propagated and only
6541 "create_bundle" with a non-empty product_type will have a corresponding
6542 target in the project.
Brett Wilson796ed472018-07-16 15:11:09 -07006543```
[email protected]449f3e42024-08-01 21:43:27 +08006544### **public**: Declare public header files for a target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006545
6546```
6547 A list of files that other targets can include. These permissions are checked
6548 via the "check" command (see "gn help check").
6549
6550 If no public files are declared, other targets (assuming they have visibility
6551 to depend on this target) can include any file in the sources list. If this
6552 variable is defined on a target, dependent targets may only include files on
6553 this whitelist unless that target is marked as a friend (see "gn help
6554 friend").
6555
6556 Header file permissions are also subject to visibility. A target must be
6557 visible to another target to include any files from it at all and the public
6558 headers indicate which subset of those files are permitted. See "gn help
6559 visibility" for more.
6560
6561 Public files are inherited through the dependency tree. So if there is a
6562 dependency A -> B -> C, then A can include C's public headers. However, the
6563 same is NOT true of visibility, so unless A is in C's visibility list, the
6564 include will be rejected.
6565
6566 GN only knows about files declared in the "sources" and "public" sections of
6567 targets. If a file is included that is not known to the build, it will be
6568 allowed.
6569
6570 It is common for test targets to need to include private headers for their
6571 associated code. In this case, list the test target in the "friend" list of
6572 the target that owns the private header to allow the inclusion. See
6573 "gn help friend" for more.
Julie Hockette2a29402018-07-31 10:11:42 -07006574
6575 When a binary target has no explicit or implicit public headers (a "public"
6576 list is defined but is empty), GN assumes that the target can not propagate
6577 any compile-time dependencies up the dependency tree. In this case, the build
6578 can be parallelized more efficiently.
6579 Say there are dependencies:
6580 A (shared library) -> B (shared library) -> C (action).
6581 Normally C must complete before any source files in A can compile (because
6582 there might be generated includes). But when B explicitly declares no public
6583 headers, C can execute in parallel with A's compile steps. C must still be
6584 complete before any dependents link.
Brett Wilson796ed472018-07-16 15:11:09 -07006585```
6586
6587#### **Examples**
6588
6589```
6590 These exact files are public:
6591 public = [ "foo.h", "bar.h" ]
6592
6593 No files are public (no targets may include headers from this one):
Julie Hockette2a29402018-07-31 10:11:42 -07006594 # This allows starting compilation in dependent targets earlier.
Brett Wilson796ed472018-07-16 15:11:09 -07006595 public = []
6596```
[email protected]449f3e42024-08-01 21:43:27 +08006597### **public_configs**: Configs to be applied on dependents. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006598
6599```
6600 A list of config labels.
6601
6602 Targets directly depending on this one will have the configs listed in this
6603 variable added to them. These configs will also apply to the current target.
Julie Hockette2a29402018-07-31 10:11:42 -07006604 Generally, public configs are used to apply defines and include directories
6605 necessary to compile this target's header files.
Brett Wilson796ed472018-07-16 15:11:09 -07006606
Julie Hockette2a29402018-07-31 10:11:42 -07006607 See also "gn help all_dependent_configs".
6608```
6609
6610#### **Propagation of public configs**
6611
6612```
6613 Public configs are applied to all targets that depend directly on this one.
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006614 These dependent targets can further push this target's public configs
Julie Hockette2a29402018-07-31 10:11:42 -07006615 higher in the dependency tree by depending on it via public_deps (see "gn
6616 help public_deps").
6617
6618 static_library("toplevel") {
6619 # This target will get "my_config" applied to it. However, since this
6620 # target uses "deps" and not "public_deps", targets that depend on this
6621 # one won't get it.
6622 deps = [ ":intermediate" ]
6623 }
6624
6625 static_library("intermediate") {
6626 # Depending on "lower" in any way will apply "my_config" to this target.
6627 # Additionall, since this target depends on "lower" via public_deps,
6628 # targets that depend on this one will also get "my_config".
6629 public_deps = [ ":lower" ]
6630 }
6631
6632 static_library("lower") {
6633 # This will get applied to all targets that depend on this one.
6634 public_configs = [ ":my_config" ]
6635 }
6636
6637 Public config propagation happens in a second phase once a target and all of
6638 its dependencies have been resolved. Therefore, a target will not see these
Brett Wilson796ed472018-07-16 15:11:09 -07006639 force-added configs in their "configs" variable while the script is running,
6640 and they can not be removed. As a result, this capability should generally
Julie Hockette2a29402018-07-31 10:11:42 -07006641 only be used to add defines and include directories rather than setting
6642 complicated flags that some targets may not want.
Brett Wilson796ed472018-07-16 15:11:09 -07006643
Julie Hockette2a29402018-07-31 10:11:42 -07006644 Public configs may or may not be propagated across toolchain boundaries
6645 depending on the value of the propagates_configs flag (see "gn help
6646 toolchain") on the toolchain of the target declaring the public_config.
6647```
6648
6649#### **Avoiding applying public configs to this target**
6650
6651```
6652 If you want the config to apply to targets that depend on this one, but NOT
6653 this one, define an extra layer of indirection using a group:
6654
6655 # External targets depend on this group.
6656 group("my_target") {
6657 # Config to apply to all targets that depend on this one.
6658 public_configs = [ ":external_settings" ]
6659 deps = [ ":internal_target" ]
6660 }
6661
6662 # Internal target to actually compile the sources.
6663 static_library("internal_target") {
6664 # Force all external targets to depend on the group instead of directly
6665 # on this so the "external_settings" config will get applied.
6666 visibility = [ ":my_target" ]
6667 ...
6668 }
Brett Wilson796ed472018-07-16 15:11:09 -07006669```
6670
6671#### **Ordering of flags and values**
6672
6673```
6674 1. Those set on the current target (not in a config).
6675 2. Those set on the "configs" on the target in order that the
6676 configs appear in the list.
6677 3. Those set on the "all_dependent_configs" on the target in order
6678 that the configs appear in the list.
6679 4. Those set on the "public_configs" on the target in order that
6680 those configs appear in the list.
6681 5. all_dependent_configs pulled from dependencies, in the order of
6682 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006683 more than once, only the first occurrence will be used.
Brett Wilson796ed472018-07-16 15:11:09 -07006684 6. public_configs pulled from dependencies, in the order of the
6685 "deps" list. If a dependency is public, they will be applied
6686 recursively.
6687```
[email protected]449f3e42024-08-01 21:43:27 +08006688### **public_deps**: Declare public dependencies. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006689
6690```
6691 Public dependencies are like private dependencies (see "gn help deps") but
6692 additionally express that the current target exposes the listed deps as part
6693 of its public API.
6694
6695 This has several ramifications:
6696
6697 - public_configs that are part of the dependency are forwarded to direct
6698 dependents.
6699
6700 - Public headers in the dependency are usable by dependents (includes do
6701 not require a direct dependency or visibility).
6702
6703 - If the current target is a shared library, other shared libraries that it
6704 publicly depends on (directly or indirectly) are propagated up the
6705 dependency tree to dependents for linking.
Julie Hockette2a29402018-07-31 10:11:42 -07006706
6707 See also "gn help public_configs".
Brett Wilson796ed472018-07-16 15:11:09 -07006708```
6709
6710#### **Discussion**
6711
6712```
6713 Say you have three targets: A -> B -> C. C's visibility may allow B to depend
6714 on it but not A. Normally, this would prevent A from including any headers
6715 from C, and C's public_configs would apply only to B.
6716
6717 If B lists C in its public_deps instead of regular deps, A will now inherit
6718 C's public_configs and the ability to include C's public headers.
6719
6720 Generally if you are writing a target B and you include C's headers as part
6721 of B's public headers, or targets depending on B should consider B and C to
6722 be part of a unit, you should use public_deps instead of deps.
6723```
6724
6725#### **Example**
6726
6727```
6728 # This target can include files from "c" but not from
6729 # "super_secret_implementation_details".
6730 executable("a") {
6731 deps = [ ":b" ]
6732 }
6733
6734 shared_library("b") {
6735 deps = [ ":super_secret_implementation_details" ]
6736 public_deps = [ ":c" ]
6737 }
6738```
[email protected]449f3e42024-08-01 21:43:27 +08006739### **rebase**: Rebase collected metadata as files. [Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08006740
6741```
6742 A boolean that triggers a rebase of collected metadata strings based on their
6743 declared file. Defaults to false.
6744
6745 Metadata generally declares files as strings relative to the local build file.
6746 However, this data is often used in other contexts, and so setting this flag
6747 will force the metadata collection to be rebased according to the local build
6748 file's location and thus allow the filename to be used anywhere.
6749
6750 Setting this flag will raise an error if any target's specified metadata is
6751 not a string value.
6752
6753 See also "gn help generated_file".
6754```
[email protected]449f3e42024-08-01 21:43:27 +08006755### **response_file_contents**: Contents of a response file for actions. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006756
6757```
6758 Sometimes the arguments passed to a script can be too long for the system's
6759 command-line capabilities. This is especially the case on Windows where the
6760 maximum command-line length is less than 8K. A response file allows you to
6761 pass an unlimited amount of data to a script in a temporary file for an
6762 action or action_foreach target.
6763
6764 If the response_file_contents variable is defined and non-empty, the list
6765 will be treated as script args (including possibly substitution patterns)
6766 that will be written to a temporary file at build time. The name of the
6767 temporary file will be substituted for "{{response_file_name}}" in the script
6768 args.
6769
6770 The response file contents will always be quoted and escaped according to
6771 Unix shell rules. To parse the response file, the Python script should use
6772 "shlex.split(file_contents)".
6773```
6774
6775#### **Example**
6776
6777```
6778 action("process_lots_of_files") {
6779 script = "process.py",
6780 inputs = [ ... huge list of files ... ]
6781
6782 # Write all the inputs to a response file for the script. Also,
6783 # make the paths relative to the script working directory.
6784 response_file_contents = rebase_path(inputs, root_build_dir)
6785
6786 # The script expects the name of the response file in --file-list.
6787 args = [
6788 "--enable-foo",
6789 "--file-list={{response_file_name}}",
6790 ]
6791 }
6792```
[email protected]449f3e42024-08-01 21:43:27 +08006793### **rustflags**: Flags passed to the Rust compiler. [Back to Top](#gn-reference)
Max Ihlenfeldt5110a7f2024-01-22 11:56:47 +01006794
6795```
6796 A list of strings.
6797
6798 "rustflags" are passed to all invocations of the Rust compiler.
6799```
[email protected]449f3e42024-08-01 21:43:27 +08006800### **script**: Script file for actions. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006801
6802```
6803 An absolute or buildfile-relative file name of a Python script to run for a
6804 action and action_foreach targets (see "gn help action" and "gn help
6805 action_foreach").
6806```
[email protected]449f3e42024-08-01 21:43:27 +08006807### **sources**: Source files for a target [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006808
6809```
6810 A list of files. Non-absolute paths will be resolved relative to the current
6811 build file.
6812```
6813
6814#### **Sources for binary targets**
6815
6816```
6817 For binary targets (source sets, executables, and libraries), the known file
6818 types will be compiled with the associated tools. Unknown file types and
6819 headers will be skipped. However, you should still list all C/C+ header files
6820 so GN knows about the existence of those files for the purposes of include
6821 checking.
6822
6823 As a special case, a file ending in ".def" will be treated as a Windows
6824 module definition file. It will be appended to the link line with a
6825 preceding "/DEF:" string. There must be at most one .def file in a target
6826 and they do not cross dependency boundaries (so specifying a .def file in a
6827 static library or source set will have no effect on the executable or shared
6828 library they're linked into).
Julie Hockettce1fa072019-05-07 17:44:37 -07006829
6830 For Rust targets that do not specify a crate_root, then the crate_root will
6831 look for a lib.rs file (or main.rs for executable) or a single file in
6832 sources, if sources contains only one file.
Brett Wilson796ed472018-07-16 15:11:09 -07006833```
6834
6835#### **Sources for non-binary targets**
6836
6837```
6838 action_foreach
6839 The sources are the set of files that the script will be executed over. The
6840 script will run once per file.
6841
6842 action
6843 The sources will be treated the same as inputs. See "gn help inputs" for
6844 more information and usage advice.
6845
6846 copy
6847 The source are the source files to copy.
6848```
[email protected]449f3e42024-08-01 21:43:27 +08006849### **swiftflags**: Flags passed to the swift compiler. [Back to Top](#gn-reference)
Sylvain Defresne89e64252020-08-07 13:01:06 +02006850
6851```
6852 A list of strings.
6853
6854 "swiftflags" are passed to any invocation of a tool that takes an .swift
6855 file as input.
6856```
6857
6858#### **Ordering of flags and values**
6859
6860```
6861 1. Those set on the current target (not in a config).
6862 2. Those set on the "configs" on the target in order that the
6863 configs appear in the list.
6864 3. Those set on the "all_dependent_configs" on the target in order
6865 that the configs appear in the list.
6866 4. Those set on the "public_configs" on the target in order that
6867 those configs appear in the list.
6868 5. all_dependent_configs pulled from dependencies, in the order of
6869 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01006870 more than once, only the first occurrence will be used.
Sylvain Defresne89e64252020-08-07 13:01:06 +02006871 6. public_configs pulled from dependencies, in the order of the
6872 "deps" list. If a dependency is public, they will be applied
6873 recursively.
6874```
[email protected]449f3e42024-08-01 21:43:27 +08006875### **testonly**: Declares a target must only be used for testing. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006876
6877```
6878 Boolean. Defaults to false.
6879
6880 When a target is marked "testonly = true", it must only be depended on by
6881 other test-only targets. Otherwise, GN will issue an error that the
6882 depenedency is not allowed.
6883
6884 This feature is intended to prevent accidentally shipping test code in a
6885 final product.
6886```
6887
6888#### **Example**
6889
6890```
6891 source_set("test_support") {
6892 testonly = true
6893 ...
6894 }
6895```
[email protected]449f3e42024-08-01 21:43:27 +08006896### **transparent**: [bool] True if the bundle is transparent. [Back to Top](#gn-reference)
Sylvain Defresnee5aee7b2023-06-08 10:08:10 -04006897
6898```
6899 A boolean.
6900
6901 Valid for "create_bundle" target. If true, the "create_bundle" target will
6902 not package the "bundle_data" deps but will forward them to all targets that
6903 depends on it (unless the "bundle_data" target sets "product_type" to the
6904 same value as the "create_bundle" target).
6905```
[email protected]449f3e42024-08-01 21:43:27 +08006906### **visibility**: A list of labels that can depend on a target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07006907
6908```
6909 A list of labels and label patterns that define which targets can depend on
6910 the current one. These permissions are checked via the "check" command (see
6911 "gn help check").
6912
6913 If visibility is not defined, it defaults to public ("*").
6914
6915 If visibility is defined, only the targets with labels that match it can
6916 depend on the current target. The empty list means no targets can depend on
6917 the current target.
6918
6919 Tip: Often you will want the same visibility for all targets in a BUILD file.
6920 In this case you can just put the definition at the top, outside of any
6921 target, and the targets will inherit that scope and see the definition.
6922```
6923
6924#### **Patterns**
6925
6926```
6927 See "gn help label_pattern" for more details on what types of patterns are
6928 supported. If a toolchain is specified, only targets in that toolchain will
6929 be matched. If a toolchain is not specified on a pattern, targets in all
6930 toolchains will be matched.
6931```
6932
6933#### **Examples**
6934
6935```
6936 Only targets in the current buildfile ("private"):
6937 visibility = [ ":*" ]
6938
6939 No targets (used for targets that should be leaf nodes):
6940 visibility = []
6941
6942 Any target ("public", the default):
6943 visibility = [ "*" ]
6944
6945 All targets in the current directory and any subdirectory:
6946 visibility = [ "./*" ]
6947
6948 Any target in "//bar/BUILD.gn":
6949 visibility = [ "//bar:*" ]
6950
6951 Any target in "//bar/" or any subdirectory thereof:
6952 visibility = [ "//bar/*" ]
6953
6954 Just these specific targets:
6955 visibility = [ ":mything", "//foo:something_else" ]
6956
6957 Any target in the current directory and any subdirectory thereof, plus
Petr Hosek7a6231e2022-10-22 23:14:18 +00006958 any targets in "//bar/" and any subdirectory thereof.
Brett Wilson796ed472018-07-16 15:11:09 -07006959 visibility = [ "./*", "//bar/*" ]
6960```
[email protected]449f3e42024-08-01 21:43:27 +08006961### **walk_keys**: Key(s) for managing the metadata collection walk. [Back to Top](#gn-reference)
Nate Fischer8ed01d32019-01-08 17:32:01 -08006962
6963```
Julie Hockett152c5142019-07-12 09:53:43 -06006964 Defaults to [""].
Nate Fischer8ed01d32019-01-08 17:32:01 -08006965
6966 These keys are used to control the next step in a collection walk, acting as
6967 barriers. If a specified key is defined in a target's metadata, the walk will
6968 use the targets listed in that value to determine which targets are walked.
6969
Julie Hockett152c5142019-07-12 09:53:43 -06006970 If no walk_keys are specified for a generated_file target (i.e. "[""]"), the
Nate Fischer8ed01d32019-01-08 17:32:01 -08006971 walk will touch all deps and data_deps of the specified target recursively.
6972
6973 See "gn help generated_file".
6974```
[email protected]449f3e42024-08-01 21:43:27 +08006975### **weak_frameworks**: [name list] Name of frameworks that must be weak linked. [Back to Top](#gn-reference)
Robert Sesekd0a6f072020-05-15 11:21:22 -04006976
6977```
6978 A list of framework names.
6979
6980 The frameworks named in that list will be weak linked with any dynamic link
6981 type target. Weak linking instructs the dynamic loader to attempt to load
6982 the framework, but if it is not able to do so, it leaves any imported symbols
6983 unresolved. This is typically used when a framework is present in a new
6984 version of an SDK but not on older versions of the OS that the software runs
6985 on.
6986```
6987
6988#### **Ordering of flags and values**
6989
6990```
6991 1. Those set on the current target (not in a config).
6992 2. Those set on the "configs" on the target in order that the
6993 configs appear in the list.
6994 3. Those set on the "all_dependent_configs" on the target in order
6995 that the configs appear in the list.
6996 4. Those set on the "public_configs" on the target in order that
6997 those configs appear in the list.
6998 5. all_dependent_configs pulled from dependencies, in the order of
6999 the "deps" list. This is done recursively. If a config appears
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01007000 more than once, only the first occurrence will be used.
Robert Sesekd0a6f072020-05-15 11:21:22 -04007001 6. public_configs pulled from dependencies, in the order of the
7002 "deps" list. If a dependency is public, they will be applied
7003 recursively.
7004```
7005
7006#### **Example**
7007
7008```
7009 weak_frameworks = [ "OnlyOnNewerOSes.framework" ]
7010```
[email protected]449f3e42024-08-01 21:43:27 +08007011### **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 -07007012
7013```
7014 Does not synchronously write the file, but rather schedules it to be written
7015 at the end of generation.
7016
7017 If the file exists and the contents are identical to that being written, the
7018 file will not be updated. This will prevent unnecessary rebuilds of targets
7019 that depend on this file.
7020
7021 Path must be within the output directory.
7022
7023 See "gn help runtime_deps" for how the runtime dependencies are computed.
7024
7025 The format of this file will list one file per line with no escaping. The
7026 files will be relative to the root_build_dir. The first line of the file will
7027 be the main output file of the target itself. The file contents will be the
7028 same as requesting the runtime deps be written on the command line (see "gn
7029 help --runtime-deps-list-file").
7030```
[email protected]449f3e42024-08-01 21:43:27 +08007031### **xcasset_compiler_flags**: Flags passed to xcassets compiler. [Back to Top](#gn-reference)
Harley Li0a9affb2020-06-03 10:38:42 -04007032
7033```
7034 A list of strings.
7035
7036 Valid for create_bundle target. Those flags are directly passed to
7037 xcassets compiler, corresponding to {{xcasset_compiler_flags}} substitution
7038 in compile_xcassets tool.
7039```
[email protected]449f3e42024-08-01 21:43:27 +08007040### **xcode_extra_attributes**: [scope] Extra attributes for Xcode projects. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007041
7042```
7043 The value defined in this scope will be copied to the EXTRA_ATTRIBUTES
7044 property of the generated Xcode project. They are only meaningful when
7045 generating with --ide=xcode.
7046
7047 See "gn help create_bundle" for more information.
7048```
[email protected]449f3e42024-08-01 21:43:27 +08007049### **xcode_test_application_name**: Name for Xcode test target. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007050
7051```
7052 Each unit and ui test target must have a test application target, and this
7053 value is used to specify the relationship. Only meaningful to Xcode (used as
7054 part of the Xcode project generation).
7055
7056 See "gn help create_bundle" for more information.
7057```
7058
Julie Hockette2a29402018-07-31 10:11:42 -07007059#### **Example**
Brett Wilson796ed472018-07-16 15:11:09 -07007060
7061```
7062 create_bundle("chrome_xctest") {
7063 test_application_name = "chrome"
7064 ...
7065 }
7066```
7067## Other help topics
7068
[email protected]449f3e42024-08-01 21:43:27 +08007069### **Build Arguments Overview** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007070
7071```
7072 Build arguments are variables passed in from outside of the build that build
7073 files can query to determine how the build works.
7074```
7075
7076#### **How build arguments are set**
7077
7078```
7079 First, system default arguments are set based on the current system. The
7080 built-in arguments are:
7081 - host_cpu
7082 - host_os
7083 - current_cpu
7084 - current_os
7085 - target_cpu
7086 - target_os
7087
7088 Next, project-specific overrides are applied. These are specified inside
7089 the default_args variable of //.gn. See "gn help dotfile" for more.
7090
7091 If specified, arguments from the --args command line flag are used. If that
7092 flag is not specified, args from previous builds in the build directory will
7093 be used (this is in the file args.gn in the build directory).
7094
7095 Last, for targets being compiled with a non-default toolchain, the toolchain
7096 overrides are applied. These are specified in the toolchain_args section of a
7097 toolchain definition. The use-case for this is that a toolchain may be
7098 building code for a different platform, and that it may want to always
7099 specify Posix, for example. See "gn help toolchain" for more.
7100
7101 If you specify an override for a build argument that never appears in a
7102 "declare_args" call, a nonfatal error will be displayed.
7103```
7104
7105#### **Examples**
7106
7107```
7108 gn args out/FooBar
7109 Create the directory out/FooBar and open an editor. You would type
7110 something like this into that file:
7111 enable_doom_melon=false
7112 os="android"
7113
7114 gn gen out/FooBar --args="enable_doom_melon=true os=\"android\""
7115 This will overwrite the build directory with the given arguments. (Note
7116 that the quotes inside the args command will usually need to be escaped
7117 for your shell to pass through strings values.)
7118```
7119
7120#### **How build arguments are used**
7121
7122```
7123 If you want to use an argument, you use declare_args() and specify default
7124 values. These default values will apply if none of the steps listed in the
7125 "How build arguments are set" section above apply to the given argument, but
7126 the defaults will not override any of these.
7127
7128 Often, the root build config file will declare global arguments that will be
7129 passed to all buildfiles. Individual build files can also specify arguments
7130 that apply only to those files. It is also useful to specify build args in an
7131 "import"-ed file if you want such arguments to apply to multiple buildfiles.
7132```
[email protected]449f3e42024-08-01 21:43:27 +08007133### **.gn file** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007134
7135```
7136 When gn starts, it will search the current directory and parent directories
7137 for a file called ".gn". This indicates the source root. You can override
7138 this detection by using the --root command-line argument
7139
7140 The .gn file in the source root will be executed. The syntax is the same as a
7141 buildfile, but with very limited build setup-specific meaning.
7142
7143 If you specify --root, by default GN will look for the file .gn in that
7144 directory. If you want to specify a different file, you can additionally pass
7145 --dotfile:
7146
7147 gn gen out/Debug --root=/home/build --dotfile=/home/my_gn_file.gn
7148```
7149
7150#### **Variables**
7151
7152```
7153 arg_file_template [optional]
7154 Path to a file containing the text that should be used as the default
7155 args.gn content when you run `gn args`.
7156
7157 buildconfig [required]
7158 Path to the build config file. This file will be used to set up the
7159 build file execution environment for each toolchain.
7160
7161 check_targets [optional]
7162 A list of labels and label patterns that should be checked when running
Erik Staab5d109d72020-06-29 22:53:23 -07007163 "gn check" or "gn gen --check". If neither check_targets or
7164 no_check_targets (see below) is specified, all targets will be checked.
7165 It is an error to specify both check_targets and no_check_targets. If it
7166 is the empty list, no targets will be checked. To bypass this list,
7167 request an explicit check of targets, like "//*".
7168
7169 The format of this list is identical to that of "visibility" so see "gn
7170 help visibility" for examples.
7171
7172 no_check_targets [optional]
7173 A list of labels and label patterns that should *not* be checked when
7174 running "gn check" or "gn gen --check". All other targets will be checked.
7175 If neither check_targets (see above) or no_check_targets is specified, all
7176 targets will be checked. It is an error to specify both check_targets and
7177 no_check_targets.
Brett Wilson796ed472018-07-16 15:11:09 -07007178
7179 The format of this list is identical to that of "visibility" so see "gn
7180 help visibility" for examples.
7181
James Robinson49f59032020-01-08 14:05:51 -08007182 check_system_includes [optional]
7183 Boolean to control whether system style includes are checked by default
7184 when running "gn check" or "gn gen --check". System style includes are
7185 includes that use angle brackets <> instead of double quotes "". If this
7186 setting is omitted or set to false, these includes will be ignored by
7187 default. They can be checked explicitly by running
7188 "gn check --check-system" or "gn gen --check=system"
7189
Brett Wilson796ed472018-07-16 15:11:09 -07007190 exec_script_whitelist [optional]
7191 A list of .gn/.gni files (not labels) that have permission to call the
7192 exec_script function. If this list is defined, calls to exec_script will
7193 be checked against this list and GN will fail if the current file isn't
7194 in the list.
7195
7196 This is to allow the use of exec_script to be restricted since is easy to
7197 use inappropriately. Wildcards are not supported. Files in the
7198 secondary_source tree (if defined) should be referenced by ignoring the
7199 secondary tree and naming them as if they are in the main tree.
7200
7201 If unspecified, the ability to call exec_script is unrestricted.
7202
7203 Example:
7204 exec_script_whitelist = [
7205 "//base/BUILD.gn",
7206 "//build/my_config.gni",
7207 ]
7208
Brett Wilson1da84bb2022-09-14 15:35:29 -07007209 export_compile_commands [optional]
7210 A list of label patterns for which to generate a Clang compilation
7211 database (see "gn help label_pattern" for the string format).
7212
7213 When specified, GN will generate a compile_commands.json file in the root
7214 of the build directory containing information on how to compile each
7215 source file reachable from any label matching any pattern in the list.
7216 This is used for Clang-based tooling and some editor integration. See
7217 https://clang.llvm.org/docs/JSONCompilationDatabase.html
7218
7219 The switch --add-export-compile-commands to "gn gen" (see "gn help gen")
7220 appends to this value which provides a per-user way to customize it.
7221
7222 The deprecated switch --export-compile-commands to "gn gen" (see "gn help
7223 gen") adds to the export target list using a different format.
7224
7225 Example:
7226 export_compile_commands = [
7227 "//base/*",
7228 "//tools:doom_melon",
7229 ]
7230
Brett Wilson796ed472018-07-16 15:11:09 -07007231 root [optional]
7232 Label of the root build target. The GN build will start by loading the
7233 build file containing this target name. This defaults to "//:" which will
Harley Li0a9affb2020-06-03 10:38:42 -04007234 cause the file //BUILD.gn to be loaded. Note that build_file_extension
7235 applies to the default case as well.
Brett Wilson796ed472018-07-16 15:11:09 -07007236
Nico Weberad9eab22020-11-15 22:20:28 -05007237 The command-line switch --root-target will override this value (see "gn
7238 help --root-target").
7239
David 'Digit' Turnerb8562a42023-10-23 18:05:37 +02007240 root_patterns [optional]
7241 A list of label pattern strings. When not defined or empty, the GN build
7242 graph will contain all targets from any BUILD.gn evaluated in the default
7243 toolchain context, and their transitive dependencies.
7244
7245 When set to a non empty list, only the targets in the default toolchain
7246 matching these patterns, and their transitive dependencies, will be defined
7247 instead.
7248
7249 The command-line switch --root-pattern will override this value (see
7250 "gn help --root-pattern")
7251
Brett Wilson796ed472018-07-16 15:11:09 -07007252 script_executable [optional]
Brett Wilsond0f8bc92022-04-22 14:01:40 -07007253 By default, GN runs the scripts used in action targets and exec_script
7254 calls using the Python interpreter found in PATH. This value specifies the
7255 Python executable or other interpreter to use instead.
James Robinson61377e32020-02-13 15:20:07 -08007256
Brett Wilsond0f8bc92022-04-22 14:01:40 -07007257 If set to the empty string, the scripts will be executed directly.
7258
7259 The command-line switch --script-executable will override this value (see
7260 "gn help --script-executable")
Brett Wilson796ed472018-07-16 15:11:09 -07007261
7262 secondary_source [optional]
7263 Label of an alternate directory tree to find input files. When searching
7264 for a BUILD.gn file (or the build config file discussed above), the file
7265 will first be looked for in the source root. If it's not found, the
7266 secondary source root will be checked (which would contain a parallel
7267 directory hierarchy).
7268
7269 This behavior is intended to be used when BUILD.gn files can't be checked
7270 in to certain source directories for whatever reason.
7271
7272 The secondary source root must be inside the main source tree.
7273
7274 default_args [optional]
7275 Scope containing the default overrides for declared arguments. These
7276 overrides take precedence over the default values specified in the
Ricardo Ribalda09c9e5e2021-01-25 19:07:20 +01007277 declare_args() block, but can be overridden using --args or the
Brett Wilson796ed472018-07-16 15:11:09 -07007278 args.gn file.
7279
7280 This is intended to be used when subprojects declare arguments with
7281 default values that need to be changed for whatever reason.
Harley Li0a9affb2020-06-03 10:38:42 -04007282
7283 build_file_extension [optional]
7284 If set to a non-empty string, this is added to the name of all build files
7285 to load.
7286 GN will look for build files named "BUILD.$build_file_extension.gn".
7287 This is intended to be used during migrations or other situations where
7288 there are two independent GN builds in the same directories.
Petr Hosek317fdc12020-05-28 10:23:42 -07007289
7290 ninja_required_version [optional]
7291 When set specifies the minimum required version of Ninja. The default
7292 required version is 1.7.2. Specifying a higher version might enable the
7293 use of some of newer features that can make the build more efficient.
Brett Wilson796ed472018-07-16 15:11:09 -07007294```
7295
7296#### **Example .gn file contents**
7297
7298```
7299 buildconfig = "//build/config/BUILDCONFIG.gn"
7300
7301 check_targets = [
7302 "//doom_melon/*", # Check everything in this subtree.
7303 "//tools:mind_controlling_ant", # Check this specific target.
7304 ]
7305
7306 root = "//:root"
7307
7308 secondary_source = "//build/config/temporary_buildfiles/"
7309
7310 default_args = {
7311 # Default to release builds for this project.
7312 is_debug = false
7313 is_component_build = false
7314 }
7315```
[email protected]449f3e42024-08-01 21:43:27 +08007316### **Build graph and execution overview** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007317
7318#### **Overall build flow**
7319
7320```
7321 1. Look for ".gn" file (see "gn help dotfile") in the current directory and
7322 walk up the directory tree until one is found. Set this directory to be
7323 the "source root" and interpret this file to find the name of the build
7324 config file.
7325
7326 2. Execute the build config file identified by .gn to set up the global
7327 variables and default toolchain name. Any arguments, variables, defaults,
7328 etc. set up in this file will be visible to all files in the build.
7329
7330 3. Load the //BUILD.gn (in the source root directory).
7331
7332 4. Recursively evaluate rules and load BUILD.gn in other directories as
7333 necessary to resolve dependencies. If a BUILD file isn't found in the
7334 specified location, GN will look in the corresponding location inside
7335 the secondary_source defined in the dotfile (see "gn help dotfile").
7336
7337 5. When a target's dependencies are resolved, write out the `.ninja`
7338 file to disk.
7339
7340 6. When all targets are resolved, write out the root build.ninja file.
Harley Li0a9affb2020-06-03 10:38:42 -04007341
7342 Note that the BUILD.gn file name may be modulated by .gn arguments such as
7343 build_file_extension.
Brett Wilson796ed472018-07-16 15:11:09 -07007344```
7345
7346#### **Executing target definitions and templates**
7347
7348```
7349 Build files are loaded in parallel. This means it is impossible to
7350 interrogate a target from GN code for any information not derivable from its
7351 label (see "gn help label"). The exception is the get_target_outputs()
7352 function which requires the target being interrogated to have been defined
7353 previously in the same file.
7354
7355 Targets are declared by their type and given a name:
7356
7357 static_library("my_static_library") {
7358 ... target parameter definitions ...
7359 }
7360
7361 There is also a generic "target" function for programmatically defined types
7362 (see "gn help target"). You can define new types using templates (see "gn
7363 help template"). A template defines some custom code that expands to one or
7364 more other targets.
7365
7366 Before executing the code inside the target's { }, the target defaults are
7367 applied (see "gn help set_defaults"). It will inject implicit variable
7368 definitions that can be overridden by the target code as necessary. Typically
7369 this mechanism is used to inject a default set of configs that define the
7370 global compiler and linker flags.
7371```
7372
7373#### **Which targets are built**
7374
7375```
7376 All targets encountered in the default toolchain (see "gn help toolchain")
7377 will have build rules generated for them, even if no other targets reference
7378 them. Their dependencies must resolve and they will be added to the implicit
7379 "all" rule (see "gn help ninja_rules").
7380
7381 Targets in non-default toolchains will only be generated when they are
7382 required (directly or transitively) to build a target in the default
7383 toolchain.
7384
Tyler Mandry4a648092022-02-15 19:47:09 +00007385 Some targets might be associated but without a formal build dependency (for
7386 example, related tools or optional variants). A target that is marked as
7387 "generated" can propagate its generated state to an associated target using
7388 "gen_deps". This will make the referenced dependency have Ninja rules
7389 generated in the same cases the source target has but without a build-time
7390 dependency and even in non-default toolchains.
7391
Brett Wilson796ed472018-07-16 15:11:09 -07007392 See also "gn help ninja_rules".
7393```
7394
7395#### **Dependencies**
7396
7397```
7398 The only difference between "public_deps" and "deps" except for pushing
7399 configs around the build tree and allowing includes for the purposes of "gn
7400 check".
7401
7402 A target's "data_deps" are guaranteed to be built whenever the target is
7403 built, but the ordering is not defined. The meaning of this is dependencies
7404 required at runtime. Currently data deps will be complete before the target
7405 is linked, but this is not semantically guaranteed and this is undesirable
7406 from a build performance perspective. Since we hope to change this in the
7407 future, do not rely on this behavior.
7408```
[email protected]449f3e42024-08-01 21:43:27 +08007409### **Language and grammar for GN build files** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007410
7411#### **Tokens**
7412
7413```
7414 GN build files are read as sequences of tokens. While splitting the file
7415 into tokens, the next token is the longest sequence of characters that form a
7416 valid token.
7417```
7418
7419#### **White space and comments**
7420
7421```
7422 White space is comprised of spaces (U+0020), horizontal tabs (U+0009),
7423 carriage returns (U+000D), and newlines (U+000A).
7424
7425 Comments start at the character "#" and stop at the next newline.
7426
7427 White space and comments are ignored except that they may separate tokens
7428 that would otherwise combine into a single token.
7429```
7430
7431#### **Identifiers**
7432
7433```
7434 Identifiers name variables and functions.
7435
7436 identifier = letter { letter | digit } .
7437 letter = "A" ... "Z" | "a" ... "z" | "_" .
7438 digit = "0" ... "9" .
7439```
7440
7441#### **Keywords**
7442
7443```
7444 The following keywords are reserved and may not be used as identifiers:
7445
7446 else false if true
7447```
7448
7449#### **Integer literals**
7450
7451```
7452 An integer literal represents a decimal integer value.
7453
7454 integer = [ "-" ] digit { digit } .
7455
7456 Leading zeros and negative zero are disallowed.
7457```
7458
7459#### **String literals**
7460
7461```
7462 A string literal represents a string value consisting of the quoted
7463 characters with possible escape sequences and variable expansions.
7464
7465 string = `"` { char | escape | expansion } `"` .
7466 escape = `\` ( "$" | `"` | char ) .
Nico Weberad9eab22020-11-15 22:20:28 -05007467 BracketExpansion = "{" ( identifier | ArrayAccess | ScopeAccess ) "}" .
Brett Wilson796ed472018-07-16 15:11:09 -07007468 Hex = "0x" [0-9A-Fa-f][0-9A-Fa-f]
7469 expansion = "$" ( identifier | BracketExpansion | Hex ) .
Nico Weberad9eab22020-11-15 22:20:28 -05007470 char = /* any character except "$", `"`, or newline */ .
Brett Wilson796ed472018-07-16 15:11:09 -07007471
7472 After a backslash, certain sequences represent special characters:
7473
7474 \" U+0022 quotation mark
7475 \$ U+0024 dollar sign
7476 \\ U+005C backslash
7477
7478 All other backslashes represent themselves.
7479
7480 To insert an arbitrary byte value, use $0xFF. For example, to insert a
7481 newline character: "Line one$0x0ALine two".
7482
7483 An expansion will evaluate the variable following the '$' and insert a
7484 stringified version of it into the result. For example, to concat two path
7485 components with a slash separating them:
7486 "$var_one/$var_two"
7487 Use the "${var_one}" format to be explicitly deliniate the variable for
7488 otherwise-ambiguous cases.
7489```
7490
7491#### **Punctuation**
7492
7493```
7494 The following character sequences represent punctuation:
7495
7496 + += == != ( )
7497 - -= < <= [ ]
7498 ! = > >= { }
7499 && || . ,
7500```
7501
7502#### **Grammar**
7503
7504```
7505 The input tokens form a syntax tree following a context-free grammar:
7506
7507 File = StatementList .
7508
7509 Statement = Assignment | Call | Condition .
7510 LValue = identifier | ArrayAccess | ScopeAccess .
7511 Assignment = LValue AssignOp Expr .
7512 Call = identifier "(" [ ExprList ] ")" [ Block ] .
7513 Condition = "if" "(" Expr ")" Block
7514 [ "else" ( Condition | Block ) ] .
7515 Block = "{" StatementList "}" .
7516 StatementList = { Statement } .
7517
7518 ArrayAccess = identifier "[" Expr "]" .
7519 ScopeAccess = identifier "." identifier .
7520 Expr = UnaryExpr | Expr BinaryOp Expr .
7521 UnaryExpr = PrimaryExpr | UnaryOp UnaryExpr .
7522 PrimaryExpr = identifier | integer | string | Call
7523 | ArrayAccess | ScopeAccess | Block
7524 | "(" Expr ")"
7525 | "[" [ ExprList [ "," ] ] "]" .
7526 ExprList = Expr { "," Expr } .
7527
7528 AssignOp = "=" | "+=" | "-=" .
7529 UnaryOp = "!" .
7530 BinaryOp = "+" | "-" // highest priority
7531 | "<" | "<=" | ">" | ">="
7532 | "==" | "!="
7533 | "&&"
7534 | "||" . // lowest priority
7535
7536 All binary operators are left-associative.
7537```
7538
7539#### **Types**
7540
7541```
7542 The GN language is dynamically typed. The following types are used:
7543
7544 - Boolean: Uses the keywords "true" and "false". There is no implicit
7545 conversion between booleans and integers.
7546
7547 - Integers: All numbers in GN are signed 64-bit integers.
7548
7549 - Strings: Strings are 8-bit with no enforced encoding. When a string is
7550 used to interact with other systems with particular encodings (like the
7551 Windows and Mac filesystems) it is assumed to be UTF-8. See "String
7552 literals" above for more.
7553
7554 - Lists: Lists are arbitrary-length ordered lists of values. See "Lists"
7555 below for more.
7556
7557 - Scopes: Scopes are like dictionaries that use variable names for keys. See
7558 "Scopes" below for more.
7559```
7560
7561#### **Lists**
7562
7563```
7564 Lists are created with [] and using commas to separate items:
7565
7566 mylist = [ 0, 1, 2, "some string" ]
7567
7568 A comma after the last item is optional. Lists are dereferenced using 0-based
7569 indexing:
7570
7571 mylist[0] += 1
7572 var = mylist[2]
7573
7574 Lists can be concatenated using the '+' and '+=' operators. Bare values can
7575 not be concatenated with lists, to add a single item, it must be put into a
7576 list of length one.
7577
7578 Items can be removed from lists using the '-' and '-=' operators. This will
7579 remove all occurrences of every item in the right-hand list from the
7580 left-hand list. It is an error to remove an item not in the list. This is to
7581 prevent common typos and to detect dead code that is removing things that no
7582 longer apply.
7583
7584 It is an error to use '=' to replace a nonempty list with another nonempty
7585 list. This is to prevent accidentally overwriting data when in most cases
7586 '+=' was intended. To overwrite a list on purpose, first assign it to the
7587 empty list:
7588
7589 mylist = []
7590 mylist = otherlist
Brett Wilson796ed472018-07-16 15:11:09 -07007591```
7592
7593#### **Scopes**
7594
7595```
7596 All execution happens in the context of a scope which holds the current state
7597 (like variables). With the exception of loops and conditions, '{' introduces
Tyler Mandry4a648092022-02-15 19:47:09 +00007598 a new scope.
Brett Wilson796ed472018-07-16 15:11:09 -07007599
Tyler Mandry4a648092022-02-15 19:47:09 +00007600 Most scopes have a parent reference to the old scope. Variable reads
7601 recursively search all parent scopes until the variable is found or there are
7602 no more scopes. Variable writes always go into the current scope. This means
7603 that after the closing '}' (again excepting loops and conditions), all local
7604 variables will be restored to the previous values. This also means that "foo
7605 = foo" can do useful work by copying a variable into the current scope that
7606 was defined in a containing scope.
Brett Wilson796ed472018-07-16 15:11:09 -07007607
Tyler Mandry4a648092022-02-15 19:47:09 +00007608 Scopes can be assigned to variables. Examples of such scopes are the
7609 implicitly-created "invoker" when invoking a template (which refers to the
7610 variables set by the invoking code), scopes created by functions like
7611 exec_script, and scopes explicitly created like
Brett Wilson796ed472018-07-16 15:11:09 -07007612
7613 empty_scope = {}
7614 myvalues = {
7615 foo = 21
7616 bar = "something"
7617 }
7618
Tyler Mandry4a648092022-02-15 19:47:09 +00007619 In the case of explicitly created scopes and scopes created by functions like
7620 exec_script, there is no reference to the parent scope. Such scopes are fully
7621 self-contained and do not "inherit" values from their defining scope.
7622
7623 Inside an explicit scope definition can be any GN code including conditionals
7624 and function calls. After the close of the scope, it will contain all
7625 variables explicitly set by the code contained inside it. After this, the
7626 values can be read, modified, or added to:
Brett Wilson796ed472018-07-16 15:11:09 -07007627
7628 myvalues.foo += 2
7629 empty_scope.new_thing = [ 1, 2, 3 ]
Nate Fischer8ed01d32019-01-08 17:32:01 -08007630
7631 Scope equality is defined as single-level scopes identical within the current
7632 scope. That is, all values in the first scope must be present and identical
7633 within the second, and vice versa. Note that this means inherited scopes are
7634 always unequal by definition.
Brett Wilson796ed472018-07-16 15:11:09 -07007635```
[email protected]449f3e42024-08-01 21:43:27 +08007636### **Input and output conversion** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007637
7638```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007639 Input and output conversions are arguments to file and process functions
7640 that specify how to convert data to or from external formats. The possible
7641 values for parameters specifying conversions are:
7642
Brett Wilson796ed472018-07-16 15:11:09 -07007643 "" (the default)
Julie Hockett09171292018-07-31 14:35:10 -07007644 input: Discard the result and return None.
7645
7646 output: If value is a list, then "list lines"; otherwise "value".
Brett Wilson796ed472018-07-16 15:11:09 -07007647
7648 "list lines"
Julie Hockett09171292018-07-31 14:35:10 -07007649 input:
7650 Return the file contents as a list, with a string for each line. The
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007651 newlines will not be present in the result. The last line may or may
7652 not end in a newline.
Brett Wilson796ed472018-07-16 15:11:09 -07007653
Julie Hockett09171292018-07-31 14:35:10 -07007654 After splitting, each individual line will be trimmed of whitespace on
7655 both ends.
7656
7657 output:
7658 Renders the value contents as a list, with a string for each line. The
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007659 newlines will not be present in the result. The last line will end in
7660 with a newline.
Brett Wilson796ed472018-07-16 15:11:09 -07007661
7662 "scope"
Julie Hockett09171292018-07-31 14:35:10 -07007663 input:
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007664 Execute the block as GN code and return a scope with the resulting
7665 values in it. If the input was:
Julie Hockett09171292018-07-31 14:35:10 -07007666 a = [ "hello.cc", "world.cc" ]
7667 b = 26
7668 and you read the result into a variable named "val", then you could
7669 access contents the "." operator on "val":
7670 sources = val.a
7671 some_count = val.b
7672
7673 output:
7674 Renders the value contents as a GN code block, reversing the input
7675 result above.
Brett Wilson796ed472018-07-16 15:11:09 -07007676
7677 "string"
Julie Hockett09171292018-07-31 14:35:10 -07007678 input: Return the file contents into a single string.
7679
7680 output:
7681 Render the value contents into a single string. The output is:
7682 a string renders with quotes, e.g. "str"
7683 an integer renders as a stringified integer, e.g. "6"
7684 a boolean renders as the associated string, e.g. "true"
7685 a list renders as a representation of its contents, e.g. "[\"str\", 6]"
7686 a scope renders as a GN code block of its values. If the Value was:
7687 Value val;
7688 val.a = [ "hello.cc", "world.cc" ];
7689 val.b = 26
7690 the resulting output would be:
7691 "{
7692 a = [ \"hello.cc\", \"world.cc\" ]
7693 b = 26
7694 }"
Brett Wilson796ed472018-07-16 15:11:09 -07007695
7696 "value"
Julie Hockett09171292018-07-31 14:35:10 -07007697 input:
7698 Parse the input as if it was a literal rvalue in a buildfile. Examples of
7699 typical program output using this mode:
7700 [ "foo", "bar" ] (result will be a list)
7701 or
7702 "foo bar" (result will be a string)
7703 or
7704 5 (result will be an integer)
Brett Wilson796ed472018-07-16 15:11:09 -07007705
Julie Hockett09171292018-07-31 14:35:10 -07007706 Note that if the input is empty, the result will be a null value which
7707 will produce an error if assigned to a variable.
7708
7709 output:
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08007710 Render the value contents as a literal rvalue. Strings render with
7711 escaped quotes.
Brett Wilson796ed472018-07-16 15:11:09 -07007712
7713 "json"
Julie Hockett09171292018-07-31 14:35:10 -07007714 input: Parse the input as a JSON and convert it to equivalent GN rvalue.
7715
7716 output: Convert the Value to equivalent JSON value.
7717
7718 The data type mapping is:
Brett Wilson796ed472018-07-16 15:11:09 -07007719 a string in JSON maps to string in GN
7720 an integer in JSON maps to integer in GN
7721 a float in JSON is unsupported and will result in an error
7722 an object in JSON maps to scope in GN
7723 an array in JSON maps to list in GN
7724 a boolean in JSON maps to boolean in GN
7725 a null in JSON is unsupported and will result in an error
7726
Julie Hockett09171292018-07-31 14:35:10 -07007727 Nota that the input dictionary keys have to be valid GN identifiers
7728 otherwise they will produce an error.
Brett Wilson796ed472018-07-16 15:11:09 -07007729
Julie Hockett09171292018-07-31 14:35:10 -07007730 "trim ..." (input only)
Brett Wilson796ed472018-07-16 15:11:09 -07007731 Prefixing any of the other transformations with the word "trim" will
7732 result in whitespace being trimmed from the beginning and end of the
7733 result before processing.
7734
7735 Examples: "trim string" or "trim list lines"
7736
7737 Note that "trim value" is useless because the value parser skips
7738 whitespace anyway.
7739```
[email protected]449f3e42024-08-01 21:43:27 +08007740### **File patterns** [Back to Top](#gn-reference)
Sylvain Defresneaff489a2020-03-11 18:27:43 +01007741
7742```
7743 File patterns are VERY limited regular expressions. They must match the
7744 entire input string to be counted as a match. In regular expression parlance,
7745 there is an implicit "^...$" surrounding your input. If you want to match a
7746 substring, you need to use wildcards at the beginning and end.
7747
7748 There are only two special tokens understood by the pattern matcher.
7749 Everything else is a literal.
7750
7751 - "*" Matches zero or more of any character. It does not depend on the
7752 preceding character (in regular expression parlance it is equivalent to
7753 ".*").
7754
7755 - "\b" Matches a path boundary. This will match the beginning or end of a
7756 string, or a slash.
7757```
7758
7759#### **Pattern examples**
7760
7761```
7762 "*asdf*"
7763 Matches a string containing "asdf" anywhere.
7764
7765 "asdf"
7766 Matches only the exact string "asdf".
7767
7768 "*.cc"
7769 Matches strings ending in the literal ".cc".
7770
7771 "\bwin/*"
7772 Matches "win/foo" and "foo/win/bar.cc" but not "iwin/foo".
7773```
[email protected]449f3e42024-08-01 21:43:27 +08007774### **Label patterns** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007775
7776```
7777 A label pattern is a way of expressing one or more labels in a portion of the
7778 source tree. They are not general regular expressions.
7779
7780 They can take the following forms only:
7781
7782 - Explicit (no wildcard):
7783 "//foo/bar:baz"
7784 ":baz"
7785
7786 - Wildcard target names:
7787 "//foo/bar:*" (all targets in the //foo/bar/BUILD.gn file)
7788 ":*" (all targets in the current build file)
7789
7790 - Wildcard directory names ("*" is only supported at the end)
7791 "*" (all targets)
7792 "//foo/bar/*" (all targets in any subdir of //foo/bar)
7793 "./*" (all targets in the current build file or sub dirs)
7794
Julie Hockette2a29402018-07-31 10:11:42 -07007795 Any of the above forms can additionally take an explicit toolchain
7796 in parenthesis at the end of the label pattern. In this case, the
7797 toolchain must be fully qualified (no wildcards are supported in the
7798 toolchain name).
Brett Wilson796ed472018-07-16 15:11:09 -07007799
Julie Hockette2a29402018-07-31 10:11:42 -07007800 "//foo:bar(//build/toolchain:mac)"
Brett Wilson796ed472018-07-16 15:11:09 -07007801 An explicit target in an explicit toolchain.
7802
7803 ":*(//build/toolchain/linux:32bit)"
7804 All targets in the current build file using the 32-bit Linux toolchain.
7805
7806 "//foo/*(//build/toolchain:win)"
7807 All targets in //foo and any subdirectory using the Windows
7808 toolchain.
7809```
[email protected]449f3e42024-08-01 21:43:27 +08007810### **About labels** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07007811
7812```
7813 Everything that can participate in the dependency graph (targets, configs,
7814 and toolchains) are identified by labels. A common label looks like:
7815
7816 //base/test:test_support
7817
7818 This consists of a source-root-absolute path, a colon, and a name. This means
7819 to look for the thing named "test_support" in "base/test/BUILD.gn".
7820
7821 You can also specify system absolute paths if necessary. Typically such
7822 paths would be specified via a build arg so the developer can specify where
7823 the component is on their system.
7824
7825 /usr/local/foo:bar (Posix)
7826 /C:/Program Files/MyLibs:bar (Windows)
7827```
7828
7829#### **Toolchains**
7830
7831```
7832 A canonical label includes the label of the toolchain being used. Normally,
7833 the toolchain label is implicitly inherited from the current execution
7834 context, but you can override this to specify cross-toolchain dependencies:
7835
7836 //base/test:test_support(//build/toolchain/win:msvc)
7837
7838 Here GN will look for the toolchain definition called "msvc" in the file
7839 "//build/toolchain/win" to know how to compile this target.
7840```
7841
7842#### **Relative labels**
7843
7844```
7845 If you want to refer to something in the same buildfile, you can omit
7846 the path name and just start with a colon. This format is recommended for
7847 all same-file references.
7848
7849 :base
7850
7851 Labels can be specified as being relative to the current directory.
7852 Stylistically, we prefer to use absolute paths for all non-file-local
7853 references unless a build file needs to be run in different contexts (like a
7854 project needs to be both standalone and pulled into other projects in
7855 difference places in the directory hierarchy).
7856
7857 source/plugin:myplugin
7858 ../net:url_request
7859```
7860
7861#### **Implicit names**
7862
7863```
7864 If a name is unspecified, it will inherit the directory name. Stylistically,
7865 we prefer to omit the colon and name when possible:
7866
7867 //net -> //net:net
7868 //tools/gn -> //tools/gn:gn
7869```
[email protected]449f3e42024-08-01 21:43:27 +08007870### **Metadata Collection** [Back to Top](#gn-reference)
Julie Hockett152c5142019-07-12 09:53:43 -06007871
7872```
7873 Metadata is information attached to targets throughout the dependency tree. GN
7874 allows for the collection of this data into files written during the generation
Keir Mierle45611e32019-11-12 11:18:00 -08007875 step, enabling users to expose and aggregate this data based on the dependency
Julie Hockett152c5142019-07-12 09:53:43 -06007876 tree.
7877```
7878
7879#### **generated_file targets**
7880
7881```
7882 Similar to the write_file() function, the generated_file target type
7883 creates a file in the specified location with the specified content. The
Keir Mierle45611e32019-11-12 11:18:00 -08007884 primary difference between write_file() and this target type is that the
Julie Hockett152c5142019-07-12 09:53:43 -06007885 write_file function does the file write at parse time, while the
7886 generated_file target type writes at target resolution time. See
7887 "gn help generated_file" for more detail.
7888
Keir Mierle45611e32019-11-12 11:18:00 -08007889 When written at target resolution time, generated_file enables GN to
Julie Hockett152c5142019-07-12 09:53:43 -06007890 collect and write aggregated metadata from dependents.
7891
Keir Mierle45611e32019-11-12 11:18:00 -08007892 A generated_file target can declare either 'contents' to write statically
7893 known contents to a file or 'data_keys' to aggregate metadata and write the
7894 result to a file. It can also specify 'walk_keys' (to restrict the metadata
Julie Hockett152c5142019-07-12 09:53:43 -06007895 collection), 'output_conversion', and 'rebase'.
7896```
7897
7898#### **Collection and Aggregation**
7899
7900```
7901 Targets can declare a 'metadata' variable containing a scope, and this
Keir Mierle45611e32019-11-12 11:18:00 -08007902 metadata may be collected and written out to a file specified by
7903 generated_file aggregation targets. The 'metadata' scope must contain
7904 only list values since the aggregation step collects a list of these values.
Julie Hockett152c5142019-07-12 09:53:43 -06007905
7906 During the target resolution, generated_file targets will walk their
7907 dependencies recursively, collecting metadata based on the specified
7908 'data_keys'. 'data_keys' is specified as a list of strings, used by the walk
7909 to identify which variables in dependencies' 'metadata' scopes to collect.
7910
Keir Mierle45611e32019-11-12 11:18:00 -08007911 The walk begins with the listed dependencies of the 'generated_file' target.
7912 The 'metadata' scope for each dependency is inspected for matching elements
7913 of the 'generated_file' target's 'data_keys' list. If a match is found, the
7914 data from the dependent's matching key list is appended to the aggregate walk
7915 list. Note that this means that if more than one walk key is specified, the
7916 data in all of them will be aggregated into one list. From there, the walk
7917 will then recurse into the dependencies of each target it encounters,
7918 collecting the specified metadata for each.
Julie Hockett152c5142019-07-12 09:53:43 -06007919
7920 For example:
7921
7922 group("a") {
7923 metadata = {
7924 doom_melon = [ "enable" ]
7925 my_files = [ "foo.cpp" ]
7926 my_extra_files = [ "bar.cpp" ]
7927 }
7928
7929 deps = [ ":b" ]
7930 }
7931
7932 group("b") {
7933 metadata = {
7934 my_files = [ "baz.cpp" ]
7935 }
7936 }
7937
7938 generated_file("metadata") {
7939 outputs = [ "$root_build_dir/my_files.json" ]
7940 data_keys = [ "my_files", "my_extra_files" ]
7941
7942 deps = [ ":a" ]
7943 }
7944
7945 The above will produce the following file data:
7946
7947 foo.cpp
7948 bar.cpp
7949 baz.cpp
7950
Keir Mierle45611e32019-11-12 11:18:00 -08007951 The dependency walk can be limited by using the 'walk_keys'. This is a list of
Julie Hockett152c5142019-07-12 09:53:43 -06007952 labels that should be included in the walk. All labels specified here should
7953 also be in one of the deps lists. These keys act as barriers, where the walk
Keir Mierle45611e32019-11-12 11:18:00 -08007954 will only recurse into the targets listed. An empty list in all specified
Julie Hockett152c5142019-07-12 09:53:43 -06007955 barriers will end that portion of the walk.
7956
7957 group("a") {
7958 metadata = {
7959 my_files = [ "foo.cpp" ]
Sylvain Defresne3028c6a2020-07-20 11:28:59 +02007960 my_files_barrier = [ ":b" ]
Julie Hockett152c5142019-07-12 09:53:43 -06007961 }
7962
7963 deps = [ ":b", ":c" ]
7964 }
7965
7966 group("b") {
7967 metadata = {
7968 my_files = [ "bar.cpp" ]
7969 }
7970 }
7971
7972 group("c") {
7973 metadata = {
7974 my_files = [ "doom_melon.cpp" ]
7975 }
7976 }
7977
7978 generated_file("metadata") {
7979 outputs = [ "$root_build_dir/my_files.json" ]
Sylvain Defresne3028c6a2020-07-20 11:28:59 +02007980 data_keys = [ "my_files" ]
7981 walk_keys = [ "my_files_barrier" ]
Julie Hockett152c5142019-07-12 09:53:43 -06007982
7983 deps = [ ":a" ]
7984 }
7985
7986 The above will produce the following file data (note that `doom_melon.cpp` is
7987 not included):
7988
7989 foo.cpp
7990 bar.cpp
7991
7992 A common example of this sort of barrier is in builds that have host tools
7993 built as part of the tree, but do not want the metadata from those host tools
7994 to be collected with the target-side code.
7995```
7996
7997#### **Common Uses**
7998
7999```
8000 Metadata can be used to collect information about the different targets in the
8001 build, and so a common use is to provide post-build tooling with a set of data
8002 necessary to do aggregation tasks. For example, if each test target specifies
8003 the output location of its binary to run in a metadata field, that can be
8004 collected into a single file listing the locations of all tests in the
8005 dependency tree. A local build tool (or continuous integration infrastructure)
8006 can then use that file to know which tests exist, and where, and run them
8007 accordingly.
8008
8009 Another use is in image creation, where a post-build image tool needs to know
8010 various pieces of information about the components it should include in order
8011 to put together the correct image.
8012```
[email protected]449f3e42024-08-01 21:43:27 +08008013### **Ninja build rules** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008014
8015#### **The "all" and "default" rules**
8016
8017```
8018 All generated targets (see "gn help execution") will be added to an implicit
8019 build rule called "all" so "ninja all" will always compile everything. The
8020 default rule will be used by Ninja if no specific target is specified (just
8021 typing "ninja"). If there is a target named "default" in the root build file,
8022 it will be the default build rule, otherwise the implicit "all" rule will be
8023 used.
8024```
8025
8026#### **Phony rules**
8027
8028```
8029 GN generates Ninja "phony" rules for targets in the default toolchain. The
8030 phony rules can collide with each other and with the names of generated files
8031 so are generated with the following priority:
8032
8033 1. Actual files generated by the build always take precedence.
8034
8035 2. Targets in the toplevel //BUILD.gn file.
8036
8037 3. Targets in toplevel directories matching the names of the directories.
8038 So "ninja foo" can be used to compile "//foo:foo". This only applies to
8039 the first level of directories since usually these are the most
8040 important (so this won't apply to "//foo/bar:bar").
8041
8042 4. The short names of executables if there is only one executable with that
8043 short name. Use "ninja doom_melon" to compile the
8044 "//tools/fruit:doom_melon" executable.
8045
Sylvain Defresne5e19d2f2022-12-12 18:20:36 +01008046 Note that for Apple platforms, create_bundle targets with a product_type
8047 of "com.apple.product-type.application" are considered as executable
8048 for this rule (as they define application bundles).
8049
Brett Wilson796ed472018-07-16 15:11:09 -07008050 5. The short names of all targets if there is only one target with that
8051 short name.
8052
8053 6. Full label name with no leading slashes. So you can use
8054 "ninja tools/fruit:doom_melon" to build "//tools/fruit:doom_melon".
8055
8056 7. Labels with an implicit name part (when the short names match the
8057 directory). So you can use "ninja foo/bar" to compile "//foo/bar:bar".
8058
8059 These "phony" rules are provided only for running Ninja since this matches
8060 people's historical expectations for building. For consistency with the rest
8061 of the program, GN introspection commands accept explicit labels.
8062
8063 To explicitly compile a target in a non-default toolchain, you must give
8064 Ninja the exact name of the output file relative to the build directory.
8065```
[email protected]449f3e42024-08-01 21:43:27 +08008066### **nogncheck**: Skip an include line from checking. [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008067
8068```
8069 GN's header checker helps validate that the includes match the build
8070 dependency graph. Sometimes an include might be conditional or otherwise
8071 problematic, but you want to specifically allow it. In this case, it can be
8072 whitelisted.
8073
8074 Include lines containing the substring "nogncheck" will be excluded from
8075 header checking. The most common case is a conditional include:
8076
8077 #if defined(ENABLE_DOOM_MELON)
8078 #include "tools/doom_melon/doom_melon.h" // nogncheck
8079 #endif
8080
8081 If the build file has a conditional dependency on the corresponding target
8082 that matches the conditional include, everything will always link correctly:
8083
8084 source_set("mytarget") {
8085 ...
8086 if (enable_doom_melon) {
8087 defines = [ "ENABLE_DOOM_MELON" ]
8088 deps += [ "//tools/doom_melon" ]
8089 }
8090
8091 But GN's header checker does not understand preprocessor directives, won't
8092 know it matches the build dependencies, and will flag this include as
8093 incorrect when the condition is false.
8094```
8095
8096#### **More information**
8097
8098```
8099 The topic "gn help check" has general information on how checking works and
8100 advice on fixing problems. Targets can also opt-out of checking, see
8101 "gn help check_includes".
8102```
[email protected]449f3e42024-08-01 21:43:27 +08008103### **Runtime dependencies** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008104
8105```
8106 Runtime dependencies of a target are exposed via the "runtime_deps" category
8107 of "gn desc" (see "gn help desc") or they can be written at build generation
8108 time via write_runtime_deps(), or --runtime-deps-list-file (see "gn help
8109 --runtime-deps-list-file").
8110
8111 To a first approximation, the runtime dependencies of a target are the set of
8112 "data" files, data directories, and the shared libraries from all transitive
8113 dependencies. Executables, shared libraries, and loadable modules are
8114 considered runtime dependencies of themselves.
8115```
8116
8117#### **Executables**
8118
8119```
8120 Executable targets and those executable targets' transitive dependencies are
8121 not considered unless that executable is listed in "data_deps". Otherwise, GN
8122 assumes that the executable (and everything it requires) is a build-time
8123 dependency only.
8124```
8125
8126#### **Actions and copies**
8127
8128```
8129 Action and copy targets that are listed as "data_deps" will have all of their
8130 outputs and data files considered as runtime dependencies. Action and copy
8131 targets that are "deps" or "public_deps" will have only their data files
8132 considered as runtime dependencies. These targets can list an output file in
8133 both the "outputs" and "data" lists to force an output file as a runtime
8134 dependency in all cases.
8135
8136 The different rules for deps and data_deps are to express build-time (deps)
8137 vs. run-time (data_deps) outputs. If GN counted all build-time copy steps as
8138 data dependencies, there would be a lot of extra stuff, and if GN counted all
8139 run-time dependencies as regular deps, the build's parallelism would be
8140 unnecessarily constrained.
8141
8142 This rule can sometimes lead to unintuitive results. For example, given the
8143 three targets:
8144 A --[data_deps]--> B --[deps]--> ACTION
8145 GN would say that A does not have runtime deps on the result of the ACTION,
8146 which is often correct. But the purpose of the B target might be to collect
8147 many actions into one logic unit, and the "data"-ness of A's dependency is
8148 lost. Solutions:
8149
8150 - List the outputs of the action in its data section (if the results of
8151 that action are always runtime files).
8152 - Have B list the action in data_deps (if the outputs of the actions are
8153 always runtime files).
8154 - Have B list the action in both deps and data deps (if the outputs might be
8155 used in both contexts and you don't care about unnecessary entries in the
8156 list of files required at runtime).
8157 - Split B into run-time and build-time versions with the appropriate "deps"
8158 for each.
8159```
8160
8161#### **Static libraries and source sets**
8162
8163```
8164 The results of static_library or source_set targets are not considered
8165 runtime dependencies since these are assumed to be intermediate targets only.
8166 If you need to list a static library as a runtime dependency, you can
8167 manually compute the .a/.lib file name for the current platform and list it
8168 in the "data" list of a target (possibly on the static library target
8169 itself).
8170```
8171
8172#### **Multiple outputs**
8173
8174```
8175 Linker tools can specify which of their outputs should be considered when
8176 computing the runtime deps by setting runtime_outputs. If this is unset on
8177 the tool, the default will be the first output only.
8178```
[email protected]449f3e42024-08-01 21:43:27 +08008179### **How Source Expansion Works** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008180
8181```
8182 Source expansion is used for the action_foreach and copy target types to map
8183 source file names to output file names or arguments.
8184
8185 To perform source expansion in the outputs, GN maps every entry in the
8186 sources to every entry in the outputs list, producing the cross product of
8187 all combinations, expanding placeholders (see below).
8188
8189 Source expansion in the args works similarly, but performing the placeholder
8190 substitution produces a different set of arguments for each invocation of the
8191 script.
8192
8193 If no placeholders are found, the outputs or args list will be treated as a
8194 static list of literal file names that do not depend on the sources.
8195
8196 See "gn help copy" and "gn help action_foreach" for more on how this is
8197 applied.
8198```
8199
8200#### **Placeholders**
8201
8202```
8203 This section discusses only placeholders for actions. There are other
8204 placeholders used in the definition of tools. See "gn help tool" for those.
8205
8206 {{source}}
8207 The name of the source file including directory (*). This will generally
8208 be used for specifying inputs to a script in the "args" variable.
8209 "//foo/bar/baz.txt" => "../../foo/bar/baz.txt"
8210
8211 {{source_file_part}}
8212 The file part of the source including the extension.
8213 "//foo/bar/baz.txt" => "baz.txt"
8214
8215 {{source_name_part}}
8216 The filename part of the source file with no directory or extension. This
8217 will generally be used for specifying a transformation from a source file
8218 to a destination file with the same name but different extension.
8219 "//foo/bar/baz.txt" => "baz"
8220
8221 {{source_dir}}
8222 The directory (*) containing the source file with no trailing slash.
8223 "//foo/bar/baz.txt" => "../../foo/bar"
8224
8225 {{source_root_relative_dir}}
8226 The path to the source file's directory relative to the source root, with
8227 no leading "//" or trailing slashes. If the path is system-absolute,
8228 (beginning in a single slash) this will just return the path with no
8229 trailing slash. This value will always be the same, regardless of whether
8230 it appears in the "outputs" or "args" section.
8231 "//foo/bar/baz.txt" => "foo/bar"
8232
8233 {{source_gen_dir}}
8234 The generated file directory (*) corresponding to the source file's path.
8235 This will be different than the target's generated file directory if the
8236 source file is in a different directory than the BUILD.gn file.
8237 "//foo/bar/baz.txt" => "gen/foo/bar"
8238
8239 {{source_out_dir}}
8240 The object file directory (*) corresponding to the source file's path,
8241 relative to the build directory. this us be different than the target's
8242 out directory if the source file is in a different directory than the
8243 build.gn file.
8244 "//foo/bar/baz.txt" => "obj/foo/bar"
8245
8246 {{source_target_relative}}
8247 The path to the source file relative to the target's directory. This will
8248 generally be used for replicating the source directory layout in the
Robert Sesek252674d2019-05-10 14:08:52 -04008249 output directory. This can only be used in actions and bundle_data
8250 targets. It is an error to use in process_file_template where there is no
8251 "target".
Brett Wilson796ed472018-07-16 15:11:09 -07008252 "//foo/bar/baz.txt" => "baz.txt"
8253```
8254
8255#### **(*) Note on directories**
8256
8257```
8258 Paths containing directories (except the source_root_relative_dir) will be
8259 different depending on what context the expansion is evaluated in. Generally
8260 it should "just work" but it means you can't concatenate strings containing
8261 these values with reasonable results.
8262
8263 Details: source expansions can be used in the "outputs" variable, the "args"
8264 variable, and in calls to "process_file_template". The "args" are passed to a
8265 script which is run from the build directory, so these directories will
8266 relative to the build directory for the script to find. In the other cases,
8267 the directories will be source- absolute (begin with a "//") because the
8268 results of those expansions will be handled by GN internally.
8269```
8270
8271#### **Examples**
8272
8273```
8274 Non-varying outputs:
8275 action("hardcoded_outputs") {
8276 sources = [ "input1.idl", "input2.idl" ]
8277 outputs = [ "$target_out_dir/output1.dat",
8278 "$target_out_dir/output2.dat" ]
8279 }
8280 The outputs in this case will be the two literal files given.
8281
8282 Varying outputs:
8283 action_foreach("varying_outputs") {
8284 sources = [ "input1.idl", "input2.idl" ]
8285 outputs = [ "{{source_gen_dir}}/{{source_name_part}}.h",
8286 "{{source_gen_dir}}/{{source_name_part}}.cc" ]
8287 }
8288 Performing source expansion will result in the following output names:
8289 //out/Debug/obj/mydirectory/input1.h
8290 //out/Debug/obj/mydirectory/input1.cc
8291 //out/Debug/obj/mydirectory/input2.h
8292 //out/Debug/obj/mydirectory/input2.cc
8293```
[email protected]449f3e42024-08-01 21:43:27 +08008294### **Available global switches** [Back to Top](#gn-reference)
Brett Wilson796ed472018-07-16 15:11:09 -07008295
8296```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08008297 Do "gn help --the_switch_you_want_help_on" for more. Individual commands may
8298 take command-specific switches not listed here. See the help on your specific
8299 command for more.
8300```
8301```
8302 * --args: Specifies build arguments overrides.
8303 * --color: Force colored output.
8304 * --dotfile: Override the name of the ".gn" file.
8305 * --fail-on-unused-args: Treat unused build args as fatal errors.
8306 * --markdown: Write help output in the Markdown format.
RJ Ascani6966efb2020-10-19 16:50:11 -07008307 * --ninja-executable: Set the Ninja executable.
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08008308 * --nocolor: Force non-colored output.
8309 * -q: Quiet mode. Don't print output on success.
8310 * --root: Explicitly specify source root.
Nico Weberad9eab22020-11-15 22:20:28 -05008311 * --root-target: Override the root target.
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08008312 * --runtime-deps-list-file: Save runtime dependencies for targets in file.
8313 * --script-executable: Set the executable used to execute scripts.
8314 * --threads: Specify number of worker threads.
8315 * --time: Outputs a summary of how long everything took.
8316 * --tracelog: Writes a Chrome-compatible trace log to the given file.
8317 * -v: Verbose logging.
8318 * --version: Prints the GN version number and exits.
Brett Wilson796ed472018-07-16 15:11:09 -07008319```
8320