blob: 5e3c198e07004fb84f1933b5f6d172f5cdb43524 [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)
12 * [desc: Show lots of insightful information about a target or config.](#cmd_desc)
Julie Hockettd69a9c32019-01-23 14:36:18 -080013 * [format: Format .gn files.](#cmd_format)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080014 * [gen: Generate ninja files.](#cmd_gen)
15 * [help: Does what you think.](#cmd_help)
16 * [ls: List matching targets.](#cmd_ls)
17 * [meta: List target metadata collection results.](#cmd_meta)
18 * [path: Find paths between two targets.](#cmd_path)
19 * [refs: Find stuff referencing a target or file.](#cmd_refs)
Brett Wilson796ed472018-07-16 15:11:09 -070020* [Target declarations](#targets)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080021 * [action: Declare a target that runs a script a single time.](#func_action)
22 * [action_foreach: Declare a target that runs a script over a set of files.](#func_action_foreach)
23 * [bundle_data: [iOS/macOS] Declare a target without output.](#func_bundle_data)
24 * [copy: Declare a target that copies files.](#func_copy)
25 * [create_bundle: [iOS/macOS] Build an iOS or macOS bundle.](#func_create_bundle)
26 * [executable: Declare an executable target.](#func_executable)
27 * [generated_file: Declare a generated_file target.](#func_generated_file)
28 * [group: Declare a named group of targets.](#func_group)
29 * [loadable_module: Declare a loadable module target.](#func_loadable_module)
30 * [shared_library: Declare a shared library target.](#func_shared_library)
31 * [source_set: Declare a source set target.](#func_source_set)
32 * [static_library: Declare a static library target.](#func_static_library)
33 * [target: Declare an target with the given programmatic type.](#func_target)
Brett Wilson796ed472018-07-16 15:11:09 -070034* [Buildfile functions](#functions)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080035 * [assert: Assert an expression is true at generation time.](#func_assert)
36 * [config: Defines a configuration object.](#func_config)
37 * [declare_args: Declare build arguments.](#func_declare_args)
38 * [defined: Returns whether an identifier is defined.](#func_defined)
39 * [exec_script: Synchronously run a script and return the output.](#func_exec_script)
40 * [foreach: Iterate over a list.](#func_foreach)
41 * [forward_variables_from: Copies variables from a different scope.](#func_forward_variables_from)
42 * [get_label_info: Get an attribute from a target's label.](#func_get_label_info)
43 * [get_path_info: Extract parts of a file or directory name.](#func_get_path_info)
44 * [get_target_outputs: [file list] Get the list of outputs from a target.](#func_get_target_outputs)
45 * [getenv: Get an environment variable.](#func_getenv)
46 * [import: Import a file into the current scope.](#func_import)
47 * [not_needed: Mark variables from scope as not needed.](#func_not_needed)
48 * [pool: Defines a pool object.](#func_pool)
49 * [print: Prints to the console.](#func_print)
50 * [process_file_template: Do template expansion over a list of files.](#func_process_file_template)
51 * [read_file: Read a file into a variable.](#func_read_file)
52 * [rebase_path: Rebase a file or directory to another location.](#func_rebase_path)
53 * [set_default_toolchain: Sets the default toolchain name.](#func_set_default_toolchain)
54 * [set_defaults: Set default values for a target type.](#func_set_defaults)
55 * [set_sources_assignment_filter: Set a pattern to filter source files.](#func_set_sources_assignment_filter)
56 * [split_list: Splits a list into N different sub-lists.](#func_split_list)
57 * [string_replace: Replaces substring in the given string.](#func_string_replace)
58 * [template: Define a template rule.](#func_template)
59 * [tool: Specify arguments to a toolchain tool.](#func_tool)
60 * [toolchain: Defines a toolchain.](#func_toolchain)
61 * [write_file: Write a file to disk.](#func_write_file)
Brett Wilson796ed472018-07-16 15:11:09 -070062* [Built-in predefined variables](#predefined_variables)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080063 * [current_cpu: [string] The processor architecture of the current toolchain.](#var_current_cpu)
64 * [current_os: [string] The operating system of the current toolchain.](#var_current_os)
65 * [current_toolchain: [string] Label of the current toolchain.](#var_current_toolchain)
66 * [default_toolchain: [string] Label of the default toolchain.](#var_default_toolchain)
67 * [host_cpu: [string] The processor architecture that GN is running on.](#var_host_cpu)
68 * [host_os: [string] The operating system that GN is running on.](#var_host_os)
69 * [invoker: [string] The invoking scope inside a template.](#var_invoker)
70 * [python_path: [string] Absolute path of Python.](#var_python_path)
71 * [root_build_dir: [string] Directory where build commands are run.](#var_root_build_dir)
72 * [root_gen_dir: [string] Directory for the toolchain's generated files.](#var_root_gen_dir)
73 * [root_out_dir: [string] Root directory for toolchain output files.](#var_root_out_dir)
74 * [target_cpu: [string] The desired cpu architecture for the build.](#var_target_cpu)
75 * [target_gen_dir: [string] Directory for a target's generated files.](#var_target_gen_dir)
76 * [target_name: [string] The name of the current target.](#var_target_name)
77 * [target_os: [string] The desired operating system for the build.](#var_target_os)
78 * [target_out_dir: [string] Directory for target output files.](#var_target_out_dir)
Brett Wilson796ed472018-07-16 15:11:09 -070079* [Variables you set in targets](#target_variables)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080080 * [all_dependent_configs: [label list] Configs to be forced on dependents.](#var_all_dependent_configs)
81 * [allow_circular_includes_from: [label list] Permit includes from deps.](#var_allow_circular_includes_from)
82 * [arflags: [string list] Arguments passed to static_library archiver.](#var_arflags)
83 * [args: [string list] Arguments passed to an action.](#var_args)
84 * [asmflags: [string list] Flags passed to the assembler.](#var_asmflags)
85 * [assert_no_deps: [label pattern list] Ensure no deps on these targets.](#var_assert_no_deps)
86 * [bundle_contents_dir: Expansion of {{bundle_contents_dir}} in create_bundle.](#var_bundle_contents_dir)
87 * [bundle_deps_filter: [label list] A list of labels that are filtered out.](#var_bundle_deps_filter)
88 * [bundle_executable_dir: Expansion of {{bundle_executable_dir}} in create_bundle](#var_bundle_executable_dir)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -080089 * [bundle_resources_dir: Expansion of {{bundle_resources_dir}} in create_bundle.](#var_bundle_resources_dir)
90 * [bundle_root_dir: Expansion of {{bundle_root_dir}} in create_bundle.](#var_bundle_root_dir)
91 * [cflags: [string list] Flags passed to all C compiler variants.](#var_cflags)
92 * [cflags_c: [string list] Flags passed to the C compiler.](#var_cflags_c)
93 * [cflags_cc: [string list] Flags passed to the C++ compiler.](#var_cflags_cc)
94 * [cflags_objc: [string list] Flags passed to the Objective C compiler.](#var_cflags_objc)
95 * [cflags_objcc: [string list] Flags passed to the Objective C++ compiler.](#var_cflags_objcc)
96 * [check_includes: [boolean] Controls whether a target's files are checked.](#var_check_includes)
97 * [code_signing_args: [string list] Arguments passed to code signing script.](#var_code_signing_args)
98 * [code_signing_outputs: [file list] Output files for code signing step.](#var_code_signing_outputs)
99 * [code_signing_script: [file name] Script for code signing.](#var_code_signing_script)
100 * [code_signing_sources: [file list] Sources for code signing step.](#var_code_signing_sources)
101 * [complete_static_lib: [boolean] Links all deps into a static library.](#var_complete_static_lib)
102 * [configs: [label list] Configs applying to this target or config.](#var_configs)
103 * [contents: Contents to write to file.](#var_contents)
104 * [data: [file list] Runtime data file dependencies.](#var_data)
105 * [data_deps: [label list] Non-linked dependencies.](#var_data_deps)
106 * [data_keys: [string list] Keys from which to collect metadata.](#var_data_keys)
107 * [defines: [string list] C preprocessor defines.](#var_defines)
108 * [depfile: [string] File name for input dependencies for actions.](#var_depfile)
109 * [deps: [label list] Private linked dependencies.](#var_deps)
110 * [friend: [label pattern list] Allow targets to include private headers.](#var_friend)
111 * [include_dirs: [directory list] Additional include directories.](#var_include_dirs)
112 * [inputs: [file list] Additional compile-time dependencies.](#var_inputs)
113 * [ldflags: [string list] Flags passed to the linker.](#var_ldflags)
114 * [lib_dirs: [directory list] Additional library directories.](#var_lib_dirs)
115 * [libs: [string list] Additional libraries to link.](#var_libs)
116 * [metadata: [scope] Metadata of this target.](#var_metadata)
117 * [output_conversion: Data format for generated_file targets.](#var_output_conversion)
118 * [output_dir: [directory] Directory to put output file in.](#var_output_dir)
119 * [output_extension: [string] Value to use for the output's file extension.](#var_output_extension)
120 * [output_name: [string] Name for the output file other than the default.](#var_output_name)
121 * [output_prefix_override: [boolean] Don't use prefix for output name.](#var_output_prefix_override)
122 * [outputs: [file list] Output files for actions and copy targets.](#var_outputs)
123 * [partial_info_plist: [filename] Path plist from asset catalog compiler.](#var_partial_info_plist)
124 * [pool: [string] Label of the pool used by the action.](#var_pool)
125 * [precompiled_header: [string] Header file to precompile.](#var_precompiled_header)
126 * [precompiled_header_type: [string] "gcc" or "msvc".](#var_precompiled_header_type)
127 * [precompiled_source: [file name] Source file to precompile.](#var_precompiled_source)
128 * [product_type: [string] Product type for Xcode projects.](#var_product_type)
129 * [public: [file list] Declare public header files for a target.](#var_public)
130 * [public_configs: [label list] Configs applied to dependents.](#var_public_configs)
131 * [public_deps: [label list] Declare public dependencies.](#var_public_deps)
132 * [rebase: [boolean] Rebase collected metadata as files.](#var_rebase)
133 * [response_file_contents: [string list] Contents of .rsp file for actions.](#var_response_file_contents)
134 * [script: [file name] Script file for actions.](#var_script)
135 * [sources: [file list] Source files for a target.](#var_sources)
136 * [testonly: [boolean] Declares a target must only be used for testing.](#var_testonly)
137 * [visibility: [label list] A list of labels that can depend on a target.](#var_visibility)
138 * [walk_keys: [string list] Key(s) for managing the metadata collection walk.](#var_walk_keys)
139 * [write_runtime_deps: Writes the target's runtime_deps to the given path.](#var_write_runtime_deps)
140 * [xcode_extra_attributes: [scope] Extra attributes for Xcode projects.](#var_xcode_extra_attributes)
141 * [xcode_test_application_name: [string] Name for Xcode test target.](#var_xcode_test_application_name)
Brett Wilson796ed472018-07-16 15:11:09 -0700142* [Other help topics](#other)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800143 * all: Print all the help at once
Brett Wilson796ed472018-07-16 15:11:09 -0700144 * [buildargs: How build arguments work.](#buildargs)
145 * [dotfile: Info about the toplevel .gn file.](#dotfile)
146 * [execution: Build graph and execution overview.](#execution)
147 * [grammar: Language and grammar for GN build files.](#grammar)
Julie Hockett81ee1962019-05-13 11:24:42 -0700148 * [input_conversion: Processing input from exec_script and read_file.](#io_conversion)
Brett Wilson796ed472018-07-16 15:11:09 -0700149 * [label_pattern: Matching more than one label.](#label_pattern)
150 * [labels: About labels.](#labels)
151 * [ninja_rules: How Ninja build rules are named.](#ninja_rules)
152 * [nogncheck: Annotating includes for checking.](#nogncheck)
Julie Hockett81ee1962019-05-13 11:24:42 -0700153 * [output_conversion: Specifies how to transform a value to output.](#io_conversion)
Brett Wilson796ed472018-07-16 15:11:09 -0700154 * [runtime_deps: How runtime dependency computation works.](#runtime_deps)
155 * [source_expansion: Map sources to outputs for scripts.](#source_expansion)
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800156 * [switches: Show available command-line switches.](#switch_list)
Brett Wilson796ed472018-07-16 15:11:09 -0700157
158## Commands
159
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800160### **gn analyze <out_dir> <input_path> <output_path>**
Brett Wilson796ed472018-07-16 15:11:09 -0700161
162```
163 Analyze which targets are affected by a list of files.
164
165 This command takes three arguments:
166
167 out_dir is the path to the build directory.
168
169 input_path is a path to a file containing a JSON object with three fields:
170
171 - "files": A list of the filenames to check.
172
173 - "test_targets": A list of the labels for targets that are needed to run
174 the tests we wish to run.
175
176 - "additional_compile_targets": A list of the labels for targets that we
177 wish to rebuild, but aren't necessarily needed for testing. The important
178 difference between this field and "test_targets" is that if an item in
179 the additional_compile_targets list refers to a group, then any
180 dependencies of that group will be returned if they are out of date, but
181 the group itself does not need to be. If the dependencies themselves are
182 groups, the same filtering is repeated. This filtering can be used to
183 avoid rebuilding dependencies of a group that are unaffected by the input
184 files. The list may also contain the string "all" to refer to a
185 pseudo-group that contains every root target in the build graph.
186
187 This filtering behavior is also known as "pruning" the list of compile
188 targets.
189
190 output_path is a path indicating where the results of the command are to be
191 written. The results will be a file containing a JSON object with one or more
192 of following fields:
193
194 - "compile_targets": A list of the labels derived from the input
195 compile_targets list that are affected by the input files. Due to the way
196 the filtering works for compile targets as described above, this list may
197 contain targets that do not appear in the input list.
198
199 - "test_targets": A list of the labels from the input test_targets list that
200 are affected by the input files. This list will be a proper subset of the
201 input list.
202
203 - "invalid_targets": A list of any names from the input that do not exist in
204 the build graph. If this list is non-empty, the "error" field will also be
205 set to "Invalid targets".
206
207 - "status": A string containing one of three values:
208
209 - "Found dependency"
210 - "No dependency"
211 - "Found dependency (all) "
212
213 In the first case, the lists returned in compile_targets and test_targets
214 should be passed to ninja to build. In the second case, nothing was
215 affected and no build is necessary. In the third case, GN could not
216 determine the correct answer and returned the input as the output in order
217 to be safe.
218
219 - "error": This will only be present if an error occurred, and will contain
220 a string describing the error. This includes cases where the input file is
221 not in the right format, or contains invalid targets.
222
223 The command returns 1 if it is unable to read the input file or write the
224 output file, or if there is something wrong with the build such that gen
225 would also fail, and 0 otherwise. In particular, it returns 0 even if the
226 "error" key is non-empty and a non-fatal error occurred. In other words, it
227 tries really hard to always write something to the output JSON and convey
228 errors that way rather than via return codes.
229```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800230### **gn args**: (command-line tool)
Brett Wilson796ed472018-07-16 15:11:09 -0700231
232```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800233 Display or configure arguments declared by the build.
234
235 gn args [--list] [--short] [--args] [--overrides-only]
236
Brett Wilson796ed472018-07-16 15:11:09 -0700237 See also "gn help buildargs" for a more high-level overview of how
238 build arguments work.
239```
240
241#### **Usage**
242
243```
244 gn args
245 Open the arguments for the given build directory in an editor. If the
246 given build directory doesn't exist, it will be created and an empty args
247 file will be opened in the editor. You would type something like this
248 into that file:
249 enable_doom_melon=false
250 os="android"
251
252 To find your editor on Posix, GN will search the environment variables in
253 order: GN_EDITOR, VISUAL, and EDITOR. On Windows GN will open the command
254 associated with .txt files.
255
256 Note: you can edit the build args manually by editing the file "args.gn"
257 in the build directory and then running "gn gen ".
258
259 gn args --list[=] [--short] [--overrides-only] [--json]
260 Lists all build arguments available in the current configuration, or, if
261 an exact_arg is specified for the list flag, just that one build
262 argument.
263
264 The output will list the declaration location, current value for the
265 build, default value (if different than the current value), and comment
266 preceding the declaration.
267
268 If --short is specified, only the names and current values will be
269 printed.
270
271 If --overrides-only is specified, only the names and current values of
272 arguments that have been overridden (i.e. non-default arguments) will
273 be printed. Overrides come from the /args.gn file and //.gn
274
275 If --json is specified, the output will be emitted in json format.
276 JSON schema for output:
277 [
278 {
279 "name": variable_name,
280 "current": {
281 "value": overridden_value,
282 "file": file_name,
283 "line": line_no
284 },
285 "default": {
286 "value": default_value,
287 "file": file_name,
288 "line": line_no
289 },
290 "comment": comment_string
291 },
292 ...
293 ]
294```
295
296#### **Examples**
297
298```
299 gn args out/Debug
300 Opens an editor with the args for out/Debug.
301
302 gn args out/Debug --list --short
303 Prints all arguments with their default values for the out/Debug
304 build.
305
306 gn args out/Debug --list --short --overrides-only
307 Prints overridden arguments for the out/Debug build.
308
309 gn args out/Debug --list=target_cpu
310 Prints information about the "target_cpu" argument for the "
311 "out/Debug
312 build.
313
314 gn args --list --args="os=\"android\" enable_doom_melon=true"
315 Prints all arguments with the default values for a build with the
316 given arguments set (which may affect the values of other
317 arguments).
318```
Joe Armstrong39413942019-03-15 10:34:03 +0800319### **gn check <out_dir> [<label_pattern>] [\--force] [\--check-generated]**
Brett Wilson796ed472018-07-16 15:11:09 -0700320
321```
322 GN's include header checker validates that the includes for C-like source
323 files match the build dependency graph.
324
325 "gn check" is the same thing as "gn gen" with the "--check" flag except that
326 this command does not write out any build files. It's intended to be an easy
327 way to manually trigger include file checking.
328
329 The can take exact labels or patterns that match more than
330 one (although not general regular expressions). If specified, only those
331 matching targets will be checked. See "gn help label_pattern" for details.
332```
333
334#### **Command-specific switches**
335
336```
337 --force
338 Ignores specifications of "check_includes = false" and checks all
339 target's files that match the target label.
Joe Armstrong39413942019-03-15 10:34:03 +0800340
341 --check-generated
342 Generated files are normally not checked since they do not exist
343 until after a build. With this flag, those generated files that
344 can be found on disk are also checked.
Brett Wilson796ed472018-07-16 15:11:09 -0700345```
346
347#### **What gets checked**
348
349```
Nate Fischer8ed01d32019-01-08 17:32:01 -0800350 The .gn file may specify a list of targets to be checked in the list
351 check_targets (see "gn help dotfile"). If a label pattern is specified
352 on the command line, check_targets is not used.
Brett Wilson796ed472018-07-16 15:11:09 -0700353
354 Targets can opt-out from checking with "check_includes = false" (see
355 "gn help check_includes").
356
357 For targets being checked:
358
359 - GN opens all C-like source files in the targets to be checked and scans
360 the top for includes.
361
Joe Armstrong39413942019-03-15 10:34:03 +0800362 - Generated files (that might not exist yet) are ignored unless
363 the --check-generated flag is provided.
364
Brett Wilson796ed472018-07-16 15:11:09 -0700365 - Includes with a "nogncheck" annotation are skipped (see
366 "gn help nogncheck").
367
368 - Only includes using "quotes" are checked. are assumed to be
369 system includes.
370
371 - Include paths are assumed to be relative to any of the "include_dirs" for
372 the target (including the implicit current dir).
373
374 - GN does not run the preprocessor so will not understand conditional
375 includes.
376
377 - Only includes matching known files in the build are checked: includes
378 matching unknown paths are ignored.
379
380 For an include to be valid:
381
382 - The included file must be in the current target, or there must be a path
383 following only public dependencies to a target with the file in it
384 ("gn path" is a good way to diagnose problems).
385
386 - There can be multiple targets with an included file: only one needs to be
387 valid for the include to be allowed.
388
389 - If there are only "sources" in a target, all are considered to be public
390 and can be included by other targets with a valid public dependency path.
391
392 - If a target lists files as "public", only those files are able to be
393 included by other targets. Anything in the sources will be considered
394 private and will not be includable regardless of dependency paths.
395
396 - Outputs from actions are treated like public sources on that target.
397
398 - A target can include headers from a target that depends on it if the
399 other target is annotated accordingly. See "gn help
400 allow_circular_includes_from".
401```
402
403#### **Advice on fixing problems**
404
405```
406 If you have a third party project that is difficult to fix or doesn't care
407 about include checks it's generally best to exclude that target from checking
408 altogether via "check_includes = false".
409
410 If you have conditional includes, make sure the build conditions and the
411 preprocessor conditions match, and annotate the line with "nogncheck" (see
412 "gn help nogncheck" for an example).
413
414 If two targets are hopelessly intertwined, use the
415 "allow_circular_includes_from" annotation. Ideally each should have identical
416 dependencies so configs inherited from those dependencies are consistent (see
417 "gn help allow_circular_includes_from").
418
419 If you have a standalone header file or files that need to be shared between
420 a few targets, you can consider making a source_set listing only those
421 headers as public sources. With only header files, the source set will be a
422 no-op from a build perspective, but will give a central place to refer to
423 those headers. That source set's files will still need to pass "gn check" in
424 isolation.
425
426 In rare cases it makes sense to list a header in more than one target if it
427 could be considered conceptually a member of both.
428```
429
430#### **Examples**
431
432```
433 gn check out/Debug
434 Check everything.
435
436 gn check out/Default //foo:bar
437 Check only the files in the //foo:bar target.
438
439 gn check out/Default "//foo/*
440 Check only the files in targets in the //foo directory tree.
441```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800442### **gn clean <out_dir>**
Brett Wilson796ed472018-07-16 15:11:09 -0700443
444```
445 Deletes the contents of the output directory except for args.gn and
446 creates a Ninja build environment sufficient to regenerate the build.
447```
Joe Armstrongb199e542019-03-21 09:40:08 +0800448### **gn desc**
Brett Wilson796ed472018-07-16 15:11:09 -0700449
450```
Joe Armstrongb199e542019-03-21 09:40:08 +0800451 gn desc
452 [--format=json]
453
Julie Hockette2a29402018-07-31 10:11:42 -0700454 Displays information about a given target or config. The build parameters
455 will be taken for the build in the given .
Brett Wilson796ed472018-07-16 15:11:09 -0700456
457 The
458 pattern (see "gn help label_pattern"). A label pattern will only match
459 targets.
460```
461
Nico Weber75eb3c72018-08-28 16:01:52 -0400462#### **Possibilities for <what to show>**
Brett Wilson796ed472018-07-16 15:11:09 -0700463
464```
465 (If unspecified an overall summary will be displayed.)
466
467 all_dependent_configs
468 allow_circular_includes_from
469 arflags [--blame]
470 args
471 cflags [--blame]
Julie Hockette2a29402018-07-31 10:11:42 -0700472 cflags_c [--blame]
Brett Wilson796ed472018-07-16 15:11:09 -0700473 cflags_cc [--blame]
Brett Wilson796ed472018-07-16 15:11:09 -0700474 check_includes
475 configs [--tree] (see below)
Nate Fischer8ed01d32019-01-08 17:32:01 -0800476 data_keys
Brett Wilson796ed472018-07-16 15:11:09 -0700477 defines [--blame]
478 depfile
479 deps [--all] [--tree] (see below)
480 include_dirs [--blame]
481 inputs
482 ldflags [--blame]
483 lib_dirs
484 libs
Nate Fischer8ed01d32019-01-08 17:32:01 -0800485 metadata
486 output_conversion
Brett Wilson796ed472018-07-16 15:11:09 -0700487 outputs
488 public_configs
489 public
Nate Fischer8ed01d32019-01-08 17:32:01 -0800490 rebase
Brett Wilson796ed472018-07-16 15:11:09 -0700491 script
492 sources
493 testonly
494 visibility
Nate Fischer8ed01d32019-01-08 17:32:01 -0800495 walk_keys
Brett Wilson796ed472018-07-16 15:11:09 -0700496
497 runtime_deps
498 Compute all runtime deps for the given target. This is a computed list
499 and does not correspond to any GN variable, unlike most other values
500 here.
501
502 The output is a list of file names relative to the build directory. See
503 "gn help runtime_deps" for how this is computed. This also works with
504 "--blame" to see the source of the dependency.
505```
506
507#### **Shared flags**
508```
509 --all-toolchains
510 Normally only inputs in the default toolchain will be included.
511 This switch will turn on matching all toolchains.
512
513 For example, a file is in a target might be compiled twice:
514 once in the default toolchain and once in a secondary one. Without
515 this flag, only the default toolchain one will be matched by
516 wildcards. With this flag, both will be matched.
517
518 --format=json
519 Format the output as JSON instead of text.
520```
521
522#### **Target flags**
523
524```
525 --blame
526 Used with any value specified on a config, this will name the config that
Julie Hockette2a29402018-07-31 10:11:42 -0700527 causes that target to get the flag. This doesn't currently work for libs
Brett Wilson796ed472018-07-16 15:11:09 -0700528 and lib_dirs because those are inherited and are more complicated to
529 figure out the blame (patches welcome).
530```
531
532#### **Configs**
533
534```
535 The "configs" section will list all configs that apply. For targets this will
536 include configs specified in the "configs" variable of the target, and also
537 configs pushed onto this target via public or "all dependent" configs.
538
539 Configs can have child configs. Specifying --tree will show the hierarchy.
540```
541
542#### **Printing outputs**
543
544```
545 The "outputs" section will list all outputs that apply, including the outputs
546 computed from the tool definition (eg for "executable", "static_library", ...
547 targets).
548```
549
550#### **Printing deps**
551
552```
553 Deps will include all public, private, and data deps (TODO this could be
554 clarified and enhanced) sorted in order applying. The following may be used:
555
556 --all
557 Collects all recursive dependencies and prints a sorted flat list. Also
558 usable with --tree (see below).
559 --as=(buildfile|label|output)
560 How to print targets.
561
562 buildfile
563 Prints the build files where the given target was declared as
564 file names.
565 label (default)
566 Prints the label of the target.
567 output
568 Prints the first output file for the target relative to the
569 root build directory.
570
571 --testonly=(true|false)
572 Restrict outputs to targets with the testonly flag set
573 accordingly. When unspecified, the target's testonly flags are
574 ignored.
575
576 --tree
577 Print a dependency tree. By default, duplicates will be elided with "..."
578 but when --all and -tree are used together, no eliding will be performed.
579
580 The "deps", "public_deps", and "data_deps" will all be included in the
581 tree.
582
583 Tree output can not be used with the filtering or output flags: --as,
584 --type, --testonly.
585 --type=(action|copy|executable|group|loadable_module|shared_library|
586 source_set|static_library)
587 Restrict outputs to targets matching the given type. If
588 unspecified, no filtering will be performed.
589```
590
591#### **Note**
592
593```
594 This command will show the full name of directories and source files, but
595 when directories and source paths are written to the build file, they will be
596 adjusted to be relative to the build directory. So the values for paths
597 displayed by this command won't match (but should mean the same thing).
598```
599
600#### **Examples**
601
602```
603 gn desc out/Debug //base:base
604 Summarizes the given target.
605
606 gn desc out/Foo :base_unittests deps --tree
607 Shows a dependency tree of the "base_unittests" project in
608 the current directory.
609
610 gn desc out/Debug //base defines --blame
611 Shows defines set for the //base:base target, annotated by where
612 each one was set from.
613```
Julie Hockettd69a9c32019-01-23 14:36:18 -0800614### **gn format [\--dump-tree] (\--stdin | <list of build_files...>)**
Brett Wilson796ed472018-07-16 15:11:09 -0700615
616```
617 Formats .gn file to a standard format.
618
619 The contents of some lists ('sources', 'deps', etc.) will be sorted to a
620 canonical order. To suppress this, you can add a comment of the form "#
621 NOSORT" immediately preceding the assignment. e.g.
622
623 # NOSORT
624 sources = [
625 "z.cc",
626 "a.cc",
627 ]
628```
629
630#### **Arguments**
631
632```
633 --dry-run
634 Does not change or output anything, but sets the process exit code based
635 on whether output would be different than what's on disk. This is useful
636 for presubmit/lint-type checks.
637 - Exit code 0: successful format, matches on disk.
638 - Exit code 1: general failure (parse error, etc.)
639 - Exit code 2: successful format, but differs from on disk.
640
Julie Hockettd69a9c32019-01-23 14:36:18 -0800641 --dump-tree[=( text | json )]
642 Dumps the parse tree to stdout and does not update the file or print
643 formatted output. If no format is specified, text format will be used.
Brett Wilson796ed472018-07-16 15:11:09 -0700644
645 --stdin
646 Read input from stdin and write to stdout rather than update a file
647 in-place.
648```
649
650#### **Examples**
651```
Julie Hockettd69a9c32019-01-23 14:36:18 -0800652 gn format //some/BUILD.gn //some/other/BUILD.gn //and/another/BUILD.gn
Brett Wilson796ed472018-07-16 15:11:09 -0700653 gn format some\\BUILD.gn
654 gn format /abspath/some/BUILD.gn
655 gn format --stdin
656```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800657### **gn gen [\--check] [<ide options>] <out_dir>**
Brett Wilson796ed472018-07-16 15:11:09 -0700658
659```
660 Generates ninja files from the current tree and puts them in the given output
661 directory.
662
663 The output directory can be a source-repo-absolute path name such as:
664 //out/foo
665 Or it can be a directory relative to the current directory such as:
666 out/foo
667
668 "gn gen --check" is the same as running "gn check". See "gn help check"
669 for documentation on that mode.
670
671 See "gn help switches" for the common command-line switches.
672```
673
674#### **IDE options**
675
676```
677 GN optionally generates files for IDE. Possibilities for
678
679 --ide=
680 Generate files for an IDE. Currently supported values:
681 "eclipse" - Eclipse CDT settings file.
682 "vs" - Visual Studio project/solution files.
683 (default Visual Studio version: 2017)
684 "vs2013" - Visual Studio 2013 project/solution files.
685 "vs2015" - Visual Studio 2015 project/solution files.
686 "vs2017" - Visual Studio 2017 project/solution files.
Sylvain Defresned46f92f2019-04-03 16:14:29 +0200687 "vs2019" - Visual Studio 2019 project/solution files.
Brett Wilson796ed472018-07-16 15:11:09 -0700688 "xcode" - Xcode workspace/solution files.
689 "qtcreator" - QtCreator project files.
690 "json" - JSON file containing target information
691
692 --filters=
693 Semicolon-separated list of label patterns used to limit the set of
694 generated projects (see "gn help label_pattern"). Only matching targets
695 and their dependencies will be included in the solution. Only used for
696 Visual Studio, Xcode and JSON.
697```
698
699#### **Visual Studio Flags**
700
701```
702 --sln=
703 Override default sln file name ("all"). Solution file is written to the
704 root build directory.
705
706 --no-deps
707 Don't include targets dependencies to the solution. Changes the way how
708 --filters option works. Only directly matching targets are included.
709
710 --winsdk=
711 Use the specified Windows 10 SDK version to generate project files.
712 As an example, "10.0.15063.0" can be specified to use Creators Update SDK
713 instead of the default one.
714
715 --ninja-extra-args=
716 This string is passed without any quoting to the ninja invocation
717 command-line. Can be used to configure ninja flags, like "-j".
718```
719
720#### **Xcode Flags**
721
722```
723 --workspace=
724 Override defaut workspace file name ("all"). The workspace file is
725 written to the root build directory.
726
727 --ninja-extra-args=
728 This string is passed without any quoting to the ninja invocation
729 command-line. Can be used to configure ninja flags, like "-j".
730
731 --root-target=
732 Name of the target corresponding to "All" target in Xcode. If unset,
733 "All" invokes ninja without any target and builds everything.
734```
735
736#### **QtCreator Flags**
737
738```
739 --root-target=
740 Name of the root target for which the QtCreator project will be generated
741 to contain files of it and its dependencies. If unset, the whole build
742 graph will be emitted.
743```
744
745#### **Eclipse IDE Support**
746
747```
748 GN DOES NOT generate Eclipse CDT projects. Instead, it generates a settings
749 file which can be imported into an Eclipse CDT project. The XML file contains
750 a list of include paths and defines. Because GN does not generate a full
751 .cproject definition, it is not possible to properly define includes/defines
752 for each file individually. Instead, one set of includes/defines is generated
753 for the entire project. This works fairly well but may still result in a few
754 indexer issues here and there.
755```
756
757#### **Generic JSON Output**
758
759```
760 Dumps target information to a JSON file and optionally invokes a
761 python script on the generated file. See the comments at the beginning
762 of json_project_writer.cc and desc_builder.cc for an overview of the JSON
763 file format.
764
765 --json-file-name=
766 Overrides default file name (project.json) of generated JSON file.
767
768 --json-ide-script=
769 Executes python script after the JSON file is generated. Path can be
770 project absolute (//), system absolute (/) or relative, in which case the
771 output directory will be base. Path to generated JSON file will be first
772 argument when invoking script.
773
774 --json-ide-script-args=
775 Optional second argument that will passed to executed script.
776```
Julie Hockett11e09912018-07-31 13:15:08 -0700777
778#### **Compilation Database**
779
780```
Robert Sesek252674d2019-05-10 14:08:52 -0400781 --export-compile-commands[=]
Julie Hockett11e09912018-07-31 13:15:08 -0700782 Produces a compile_commands.json file in the root of the build directory
783 containing an array of “command objects”, where each command object
Robert Sesek252674d2019-05-10 14:08:52 -0400784 specifies one way a translation unit is compiled in the project. If a list
785 of target_name is supplied, only targets that are reachable from the list
786 of target_name will be used for “command objects” generation, otherwise
787 all available targets will be used. This is used for various Clang-based
788 tooling, allowing for the replay of individual compilations independent
789 of the build system.
Julie Hockett11e09912018-07-31 13:15:08 -0700790```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800791### **gn help <anything>**
Brett Wilson796ed472018-07-16 15:11:09 -0700792
793```
794 Yo dawg, I heard you like help on your help so I put help on the help in the
795 help.
796
797 You can also use "all" as the parameter to get all help at once.
798```
799
800#### **Switches**
801
802```
803 --markdown
804 Format output in markdown syntax.
805```
806
807#### **Example**
808
809```
810 gn help --markdown all
811 Dump all help to stdout in markdown format.
812```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800813### **gn ls <out_dir> [<label_pattern>] [\--all-toolchains] [\--as=...]**
Brett Wilson796ed472018-07-16 15:11:09 -0700814```
815 [--type=...] [--testonly=...]
816
817 Lists all targets matching the given pattern for the given build directory.
818 By default, only targets in the default toolchain will be matched unless a
819 toolchain is explicitly supplied.
820
821 If the label pattern is unspecified, list all targets. The label pattern is
822 not a general regular expression (see "gn help label_pattern"). If you need
823 more complex expressions, pipe the result through grep.
824```
825
826#### **Options**
827
828```
829 --as=(buildfile|label|output)
830 How to print targets.
831
832 buildfile
833 Prints the build files where the given target was declared as
834 file names.
835 label (default)
836 Prints the label of the target.
837 output
838 Prints the first output file for the target relative to the
839 root build directory.
840
841 --all-toolchains
842 Normally only inputs in the default toolchain will be included.
843 This switch will turn on matching all toolchains.
844
845 For example, a file is in a target might be compiled twice:
846 once in the default toolchain and once in a secondary one. Without
847 this flag, only the default toolchain one will be matched by
848 wildcards. With this flag, both will be matched.
849
850 --testonly=(true|false)
851 Restrict outputs to targets with the testonly flag set
852 accordingly. When unspecified, the target's testonly flags are
853 ignored.
854
855 --type=(action|copy|executable|group|loadable_module|shared_library|
856 source_set|static_library)
857 Restrict outputs to targets matching the given type. If
858 unspecified, no filtering will be performed.
859```
860
861#### **Examples**
862
863```
864 gn ls out/Debug
865 Lists all targets in the default toolchain.
866
867 gn ls out/Debug "//base/*"
868 Lists all targets in the directory base and all subdirectories.
869
870 gn ls out/Debug "//base:*"
871 Lists all targets defined in //base/BUILD.gn.
872
873 gn ls out/Debug //base --as=output
874 Lists the build output file for //base:base
875
876 gn ls out/Debug --type=executable
877 Lists all executables produced by the build.
878
879 gn ls out/Debug "//base/*" --as=output | xargs ninja -C out/Debug
880 Builds all targets in //base and all subdirectories.
881
882 gn ls out/Debug //base --all-toolchains
883 Lists all variants of the target //base:base (it may be referenced
884 in multiple toolchains).
885```
Joe Armstrongb199e542019-03-21 09:40:08 +0800886### **gn meta**
887
Nate Fischer8ed01d32019-01-08 17:32:01 -0800888```
Joe Armstrongb199e542019-03-21 09:40:08 +0800889 gn meta * --data=[,*]* [--walk=[,*]*]
890 [--rebase=]
Nate Fischer8ed01d32019-01-08 17:32:01 -0800891
892 Lists collected metaresults of all given targets for the given data key(s),
893 collecting metadata dependencies as specified by the given walk key(s).
894
895 See `gn help generated_file` for more information on the walk.
896```
897
898#### **Arguments**
899
900```
901
902 A list of target labels from which to initiate the walk.
903
904 --data
905 A list of keys from which to extract data. In each target walked, its metadata
906 scope is checked for the presence of these keys. If present, the contents of
907 those variable in the scope are appended to the results list.
908
909 --walk (optional)
910 A list of keys from which to control the walk. In each target walked, its
911 metadata scope is checked for the presence of any of these keys. If present,
912 the contents of those variables is checked to ensure that it is a label of
913 a valid dependency of the target and then added to the set of targets to walk.
914 If the empty string ("") is present in any of these keys, all deps and data_deps
915 are added to the walk set.
916
917 --rebase (optional)
918 A destination directory onto which to rebase any paths found. If set, all
919 collected metadata will be rebased onto this path. This option will throw errors
920 if collected metadata is not a list of strings.
921```
922
923#### **Examples**
924
925```
926 gn meta out/Debug "//base/foo" --data=files
927 Lists collected metaresults for the `files` key in the //base/foo:foo
928 target and all of its dependency tree.
929
930 gn meta out/Debug "//base/foo" --data=files --data=other
931 Lists collected metaresults for the `files` and `other` keys in the
932 //base/foo:foo target and all of its dependency tree.
933
934 gn meta out/Debug "//base/foo" --data=files --walk=stop
935 Lists collected metaresults for the `files` key in the //base/foo:foo
936 target and all of the dependencies listed in the `stop` key (and so on).
937
938 gn meta out/Debug "//base/foo" --data=files --rebase="/"
939 Lists collected metaresults for the `files` key in the //base/foo:foo
940 target and all of its dependency tree, rebasing the strings in the `files`
941 key onto the source directory of the target's declaration relative to "/".
942```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -0800943### **gn path <out_dir> <target_one> <target_two>**
Brett Wilson796ed472018-07-16 15:11:09 -0700944
945```
946 Finds paths of dependencies between two targets. Each unique path will be
947 printed in one group, and groups will be separate by newlines. The two
948 targets can appear in either order (paths will be found going in either
949 direction).
950
951 By default, a single path will be printed. If there is a path with only
952 public dependencies, the shortest public path will be printed. Otherwise, the
953 shortest path using either public or private dependencies will be printed. If
954 --with-data is specified, data deps will also be considered. If there are
955 multiple shortest paths, an arbitrary one will be selected.
956```
957
958#### **Interesting paths**
959
960```
961 In a large project, there can be 100's of millions of unique paths between a
962 very high level and a common low-level target. To make the output more useful
963 (and terminate in a reasonable time), GN will not revisit sub-paths
964 previously known to lead to the target.
965```
966
967#### **Options**
968
969```
970 --all
971 Prints all "interesting" paths found rather than just the first one.
972 Public paths will be printed first in order of increasing length, followed
973 by non-public paths in order of increasing length.
974
975 --public
976 Considers only public paths. Can't be used with --with-data.
977
978 --with-data
979 Additionally follows data deps. Without this flag, only public and private
980 linked deps will be followed. Can't be used with --public.
981```
982
983#### **Example**
984
985```
986 gn path out/Default //base //tools/gn
987```
Joe Armstrongb199e542019-03-21 09:40:08 +0800988### **gn refs**
989
Brett Wilson796ed472018-07-16 15:11:09 -0700990```
Joe Armstrongb199e542019-03-21 09:40:08 +0800991 gn refs (|
992 [--all] [--all-toolchains] [--as=...] [--testonly=...] [--type=...]
Brett Wilson796ed472018-07-16 15:11:09 -0700993
994 Finds reverse dependencies (which targets reference something). The input is
995 a list containing:
996
997 - Target label: The result will be which targets depend on it.
998
999 - Config label: The result will be which targets list the given config in
1000 its "configs" or "public_configs" list.
1001
1002 - Label pattern: The result will be which targets depend on any target
1003 matching the given pattern. Patterns will not match configs. These are not
1004 general regular expressions, see "gn help label_pattern" for details.
1005
1006 - File name: The result will be which targets list the given file in its
1007 "inputs", "sources", "public", "data", or "outputs". Any input that does
1008 not contain wildcards and does not match a target or a config will be
1009 treated as a file.
1010
1011 - Response file: If the input starts with an "@", it will be interpreted as
1012 a path to a file containing a list of labels or file names, one per line.
1013 This allows us to handle long lists of inputs without worrying about
1014 command line limits.
1015```
1016
1017#### **Options**
1018
1019```
1020 --all
1021 When used without --tree, will recurse and display all unique
1022 dependencies of the given targets. For example, if the input is a target,
1023 this will output all targets that depend directly or indirectly on the
1024 input. If the input is a file, this will output all targets that depend
1025 directly or indirectly on that file.
1026
1027 When used with --tree, turns off eliding to show a complete tree.
1028 --all-toolchains
1029 Normally only inputs in the default toolchain will be included.
1030 This switch will turn on matching all toolchains.
1031
1032 For example, a file is in a target might be compiled twice:
1033 once in the default toolchain and once in a secondary one. Without
1034 this flag, only the default toolchain one will be matched by
1035 wildcards. With this flag, both will be matched.
1036
1037 --as=(buildfile|label|output)
1038 How to print targets.
1039
1040 buildfile
1041 Prints the build files where the given target was declared as
1042 file names.
1043 label (default)
1044 Prints the label of the target.
1045 output
1046 Prints the first output file for the target relative to the
1047 root build directory.
1048
1049 -q
1050 Quiet. If nothing matches, don't print any output. Without this option, if
1051 there are no matches there will be an informational message printed which
1052 might interfere with scripts processing the output.
1053 --testonly=(true|false)
1054 Restrict outputs to targets with the testonly flag set
1055 accordingly. When unspecified, the target's testonly flags are
1056 ignored.
1057
1058 --tree
1059 Outputs a reverse dependency tree from the given target. Duplicates will
1060 be elided. Combine with --all to see a full dependency tree.
1061
1062 Tree output can not be used with the filtering or output flags: --as,
1063 --type, --testonly.
1064 --type=(action|copy|executable|group|loadable_module|shared_library|
1065 source_set|static_library)
1066 Restrict outputs to targets matching the given type. If
1067 unspecified, no filtering will be performed.
1068```
1069
1070#### **Examples (target input)**
1071
1072```
1073 gn refs out/Debug //tools/gn:gn
1074 Find all targets depending on the given exact target name.
1075
1076 gn refs out/Debug //base:i18n --as=buildfiles | xargs gvim
1077 Edit all .gn files containing references to //base:i18n
1078
1079 gn refs out/Debug //base --all
1080 List all targets depending directly or indirectly on //base:base.
1081
1082 gn refs out/Debug "//base/*"
1083 List all targets depending directly on any target in //base or
1084 its subdirectories.
1085
1086 gn refs out/Debug "//base:*"
1087 List all targets depending directly on any target in
1088 //base/BUILD.gn.
1089
1090 gn refs out/Debug //base --tree
1091 Print a reverse dependency tree of //base:base
1092```
1093
1094#### **Examples (file input)**
1095
1096```
1097 gn refs out/Debug //base/macros.h
1098 Print target(s) listing //base/macros.h as a source.
1099
1100 gn refs out/Debug //base/macros.h --tree
1101 Display a reverse dependency tree to get to the given file. This
1102 will show how dependencies will reference that file.
1103
1104 gn refs out/Debug //base/macros.h //base/at_exit.h --all
1105 Display all unique targets with some dependency path to a target
1106 containing either of the given files as a source.
1107
1108 gn refs out/Debug //base/macros.h --testonly=true --type=executable
1109 --all --as=output
1110 Display the executable file names of all test executables
1111 potentially affected by a change to the given file.
1112```
1113## Target declarations
1114
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001115### **action**: Declare a target that runs a script a single time.
Brett Wilson796ed472018-07-16 15:11:09 -07001116
1117```
1118 This target type allows you to run a script a single time to produce one or
1119 more output files. If you want to run a script once for each of a set of
1120 input files, see "gn help action_foreach".
1121```
1122
1123#### **Inputs**
1124
1125```
1126 In an action the "sources" and "inputs" are treated the same: they're both
1127 input dependencies on script execution with no special handling. If you want
1128 to pass the sources to your script, you must do so explicitly by including
1129 them in the "args". Note also that this means there is no special handling of
1130 paths since GN doesn't know which of the args are paths and not. You will
1131 want to use rebase_path() to convert paths to be relative to the
1132 root_build_dir.
1133
1134 You can dynamically write input dependencies (for incremental rebuilds if an
1135 input file changes) by writing a depfile when the script is run (see "gn help
1136 depfile"). This is more flexible than "inputs".
1137
1138 If the command line length is very long, you can use response files to pass
1139 args to your script. See "gn help response_file_contents".
1140
1141 It is recommended you put inputs to your script in the "sources" variable,
1142 and stuff like other Python files required to run your script in the "inputs"
1143 variable.
Julie Hockette2a29402018-07-31 10:11:42 -07001144
Brett Wilson796ed472018-07-16 15:11:09 -07001145 The "deps" and "public_deps" for an action will always be
1146 completed before any part of the action is run so it can depend on
1147 the output of previous steps. The "data_deps" will be built if the
1148 action is built, but may not have completed before all steps of the
1149 action are started. This can give additional parallelism in the build
1150 for runtime-only dependencies.
1151```
1152
1153#### **Outputs**
1154
1155```
1156 You should specify files created by your script by specifying them in the
1157 "outputs".
Julie Hockette2a29402018-07-31 10:11:42 -07001158
Brett Wilson796ed472018-07-16 15:11:09 -07001159 The script will be executed with the given arguments with the current
1160 directory being that of the root build directory. If you pass files
1161 to your script, see "gn help rebase_path" for how to convert
1162 file names to be relative to the build directory (file names in the
1163 sources, outputs, and inputs will be all treated as relative to the
1164 current build file and converted as needed automatically).
1165```
1166
1167#### **File name handling**
Julie Hockette2a29402018-07-31 10:11:42 -07001168
Brett Wilson796ed472018-07-16 15:11:09 -07001169```
1170 All output files must be inside the output directory of the build.
1171 You would generally use |$target_out_dir| or |$target_gen_dir| to
1172 reference the output or generated intermediate file directories,
1173 respectively.
1174```
1175
1176#### **Variables**
1177
1178```
Nate Fischer8ed01d32019-01-08 17:32:01 -08001179 args, data, data_deps, depfile, deps, inputs, metadata, outputs*, pool,
Brett Wilson796ed472018-07-16 15:11:09 -07001180 response_file_contents, script*, sources
1181 * = required
1182```
1183
1184#### **Example**
1185
1186```
1187 action("run_this_guy_once") {
1188 script = "doprocessing.py"
1189 sources = [ "my_configuration.txt" ]
1190 outputs = [ "$target_gen_dir/insightful_output.txt" ]
1191
1192 # Our script imports this Python file so we want to rebuild if it changes.
1193 inputs = [ "helper_library.py" ]
1194
1195 # Note that we have to manually pass the sources to our script if the
1196 # script needs them as inputs.
1197 args = [ "--out", rebase_path(target_gen_dir, root_build_dir) ] +
1198 rebase_path(sources, root_build_dir)
1199 }
1200```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001201### **action_foreach**: Declare a target that runs a script over a set of files.
Brett Wilson796ed472018-07-16 15:11:09 -07001202
1203```
1204 This target type allows you to run a script once-per-file over a set of
1205 sources. If you want to run a script once that takes many files as input, see
1206 "gn help action".
1207```
1208
1209#### **Inputs**
1210
1211```
1212 The script will be run once per file in the "sources" variable. The "outputs"
1213 variable should specify one or more files with a source expansion pattern in
1214 it (see "gn help source_expansion"). The output file(s) for each script
1215 invocation should be unique. Normally you use "{{source_name_part}}" in each
1216 output file.
1217
1218 If your script takes additional data as input, such as a shared configuration
1219 file or a Python module it uses, those files should be listed in the "inputs"
1220 variable. These files are treated as dependencies of each script invocation.
1221
1222 If the command line length is very long, you can use response files to pass
1223 args to your script. See "gn help response_file_contents".
1224
1225 You can dynamically write input dependencies (for incremental rebuilds if an
1226 input file changes) by writing a depfile when the script is run (see "gn help
1227 depfile"). This is more flexible than "inputs".
Julie Hockette2a29402018-07-31 10:11:42 -07001228
Brett Wilson796ed472018-07-16 15:11:09 -07001229 The "deps" and "public_deps" for an action will always be
1230 completed before any part of the action is run so it can depend on
1231 the output of previous steps. The "data_deps" will be built if the
1232 action is built, but may not have completed before all steps of the
1233 action are started. This can give additional parallelism in the build
1234 for runtime-only dependencies.
1235```
1236
1237#### **Outputs**
Julie Hockette2a29402018-07-31 10:11:42 -07001238
Brett Wilson796ed472018-07-16 15:11:09 -07001239```
1240 The script will be executed with the given arguments with the current
1241 directory being that of the root build directory. If you pass files
1242 to your script, see "gn help rebase_path" for how to convert
1243 file names to be relative to the build directory (file names in the
1244 sources, outputs, and inputs will be all treated as relative to the
1245 current build file and converted as needed automatically).
1246```
1247
1248#### **File name handling**
Julie Hockette2a29402018-07-31 10:11:42 -07001249
Brett Wilson796ed472018-07-16 15:11:09 -07001250```
1251 All output files must be inside the output directory of the build.
1252 You would generally use |$target_out_dir| or |$target_gen_dir| to
1253 reference the output or generated intermediate file directories,
1254 respectively.
1255```
1256
1257#### **Variables**
1258
1259```
Nate Fischer8ed01d32019-01-08 17:32:01 -08001260 args, data, data_deps, depfile, deps, inputs, metadata, outputs*, pool,
Brett Wilson796ed472018-07-16 15:11:09 -07001261 response_file_contents, script*, sources*
1262 * = required
1263```
1264
1265#### **Example**
1266
1267```
1268 # Runs the script over each IDL file. The IDL script will generate both a .cc
1269 # and a .h file for each input.
1270 action_foreach("my_idl") {
1271 script = "idl_processor.py"
1272 sources = [ "foo.idl", "bar.idl" ]
1273
Joe Armstrong73e89072019-05-10 11:23:52 +08001274 # Our script reads this file each time, so we need to list it as a
Brett Wilson796ed472018-07-16 15:11:09 -07001275 # dependency so we can rebuild if it changes.
1276 inputs = [ "my_configuration.txt" ]
1277
1278 # Transformation from source file name to output file names.
1279 outputs = [ "$target_gen_dir/{{source_name_part}}.h",
1280 "$target_gen_dir/{{source_name_part}}.cc" ]
1281
1282 # Note that since "args" is opaque to GN, if you specify paths here, you
1283 # will need to convert it to be relative to the build directory using
1284 # rebase_path().
1285 args = [
1286 "{{source}}",
1287 "-o",
1288 rebase_path(relative_target_gen_dir, root_build_dir) +
1289 "/{{source_name_part}}.h" ]
1290 }
1291```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001292### **bundle_data**: [iOS/macOS] Declare a target without output.
Brett Wilson796ed472018-07-16 15:11:09 -07001293
1294```
1295 This target type allows to declare data that is required at runtime. It is
1296 used to inform "create_bundle" targets of the files to copy into generated
1297 bundle, see "gn help create_bundle" for help.
1298
1299 The target must define a list of files as "sources" and a single "outputs".
1300 If there are multiple files, source expansions must be used to express the
1301 output. The output must reference a file inside of {{bundle_root_dir}}.
1302
1303 This target can be used on all platforms though it is designed only to
1304 generate iOS/macOS bundle. In cross-platform projects, it is advised to put it
1305 behind iOS/macOS conditionals.
1306
1307 See "gn help create_bundle" for more information.
1308```
1309
1310#### **Variables**
1311
1312```
Nate Fischer8ed01d32019-01-08 17:32:01 -08001313 sources*, outputs*, deps, data_deps, metadata, public_deps, visibility
Brett Wilson796ed472018-07-16 15:11:09 -07001314 * = required
1315```
1316
1317#### **Examples**
1318
1319```
1320 bundle_data("icudata") {
1321 sources = [ "sources/data/in/icudtl.dat" ]
1322 outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ]
1323 }
1324
1325 bundle_data("base_unittests_bundle_data]") {
1326 sources = [ "test/data" ]
1327 outputs = [
1328 "{{bundle_resources_dir}}/{{source_root_relative_dir}}/" +
1329 "{{source_file_part}}"
1330 ]
1331 }
1332
1333 bundle_data("material_typography_bundle_data") {
1334 sources = [
1335 "src/MaterialTypography.bundle/Roboto-Bold.ttf",
1336 "src/MaterialTypography.bundle/Roboto-Italic.ttf",
1337 "src/MaterialTypography.bundle/Roboto-Regular.ttf",
1338 "src/MaterialTypography.bundle/Roboto-Thin.ttf",
1339 ]
1340 outputs = [
1341 "{{bundle_resources_dir}}/MaterialTypography.bundle/"
1342 "{{source_file_part}}"
1343 ]
1344 }
1345```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001346### **copy**: Declare a target that copies files.
Brett Wilson796ed472018-07-16 15:11:09 -07001347
1348#### **File name handling**
1349
1350```
1351 All output files must be inside the output directory of the build. You would
1352 generally use |$target_out_dir| or |$target_gen_dir| to reference the output
1353 or generated intermediate file directories, respectively.
1354
1355 Both "sources" and "outputs" must be specified. Sources can include as many
1356 files as you want, but there can only be one item in the outputs list (plural
1357 is used for the name for consistency with other target types).
1358
1359 If there is more than one source file, your output name should specify a
1360 mapping from each source file to an output file name using source expansion
1361 (see "gn help source_expansion"). The placeholders will look like
1362 "{{source_name_part}}", for example.
1363```
1364
1365#### **Examples**
1366
1367```
1368 # Write a rule that copies a checked-in DLL to the output directory.
1369 copy("mydll") {
1370 sources = [ "mydll.dll" ]
1371 outputs = [ "$target_out_dir/mydll.dll" ]
1372 }
1373
1374 # Write a rule to copy several files to the target generated files directory.
1375 copy("myfiles") {
1376 sources = [ "data1.dat", "data2.dat", "data3.dat" ]
1377
1378 # Use source expansion to generate output files with the corresponding file
1379 # names in the gen dir. This will just copy each file.
1380 outputs = [ "$target_gen_dir/{{source_file_part}}" ]
1381 }
1382```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001383### **create_bundle**: [ios/macOS] Build an iOS or macOS bundle.
Brett Wilson796ed472018-07-16 15:11:09 -07001384
1385```
1386 This target generates an iOS or macOS bundle (which is a directory with a
1387 well-know structure). This target does not define any sources, instead they
1388 are computed from all "bundle_data" target this one depends on transitively
1389 (the recursion stops at "create_bundle" targets).
1390
Sylvain Defresned46f92f2019-04-03 16:14:29 +02001391 The "bundle_*_dir" are be used for the expansion of {{bundle_*_dir}} rules in
1392 "bundle_data" outputs. The properties are optional but must be defined if any
1393 of the "bundle_data" target use them.
Brett Wilson796ed472018-07-16 15:11:09 -07001394
1395 This target can be used on all platforms though it is designed only to
1396 generate iOS or macOS bundle. In cross-platform projects, it is advised to put
1397 it behind iOS/macOS conditionals.
1398
1399 If a create_bundle is specified as a data_deps for another target, the bundle
1400 is considered a leaf, and its public and private dependencies will not
1401 contribute to any data or data_deps. Required runtime dependencies should be
1402 placed in the bundle. A create_bundle can declare its own explicit data and
1403 data_deps, however.
1404```
1405
1406#### **Code signing**
1407
1408```
1409 Some bundle needs to be code signed as part of the build (on iOS all
1410 application needs to be code signed to run on a device). The code signature
1411 can be configured via the code_signing_script variable.
1412
1413 If set, code_signing_script is the path of a script that invoked after all
1414 files have been moved into the bundle. The script must not change any file in
1415 the bundle, but may add new files.
1416
1417 If code_signing_script is defined, then code_signing_outputs must also be
1418 defined and non-empty to inform when the script needs to be re-run. The
1419 code_signing_args will be passed as is to the script (so path have to be
1420 rebased) and additional inputs may be listed with the variable
1421 code_signing_sources.
1422```
1423
1424#### **Variables**
1425
1426```
Sylvain Defresned46f92f2019-04-03 16:14:29 +02001427 bundle_root_dir, bundle_contents_dir, bundle_resources_dir,
Sylvain Defresnedcab2f92019-04-03 16:34:05 +02001428 bundle_executable_dir, bundle_deps_filter, deps, data_deps, public_deps,
1429 visibility, product_type, code_signing_args, code_signing_script,
1430 code_signing_sources, code_signing_outputs, xcode_extra_attributes,
1431 xcode_test_application_name, partial_info_plist, metadata
Brett Wilson796ed472018-07-16 15:11:09 -07001432```
1433
1434#### **Example**
1435
1436```
1437 # Defines a template to create an application. On most platform, this is just
1438 # an alias for an "executable" target, but on iOS/macOS, it builds an
1439 # application bundle.
1440 template("app") {
1441 if (!is_ios && !is_mac) {
1442 executable(target_name) {
1443 forward_variables_from(invoker, "*")
1444 }
1445 } else {
1446 app_name = target_name
1447 gen_path = target_gen_dir
1448
1449 action("${app_name}_generate_info_plist") {
1450 script = [ "//build/ios/ios_gen_plist.py" ]
1451 sources = [ "templates/Info.plist" ]
1452 outputs = [ "$gen_path/Info.plist" ]
1453 args = rebase_path(sources, root_build_dir) +
1454 rebase_path(outputs, root_build_dir)
1455 }
1456
1457 bundle_data("${app_name}_bundle_info_plist") {
Sylvain Defresnedcab2f92019-04-03 16:34:05 +02001458 public_deps = [ ":${app_name}_generate_info_plist" ]
Brett Wilson796ed472018-07-16 15:11:09 -07001459 sources = [ "$gen_path/Info.plist" ]
1460 outputs = [ "{{bundle_contents_dir}}/Info.plist" ]
1461 }
1462
1463 executable("${app_name}_generate_executable") {
1464 forward_variables_from(invoker, "*", [
1465 "output_name",
1466 "visibility",
1467 ])
1468 output_name =
1469 rebase_path("$gen_path/$app_name", root_build_dir)
1470 }
1471
1472 code_signing =
1473 defined(invoker.code_signing) && invoker.code_signing
1474
Sylvain Defresnedcab2f92019-04-03 16:34:05 +02001475 if (!is_ios || !code_signing) {
Brett Wilson796ed472018-07-16 15:11:09 -07001476 bundle_data("${app_name}_bundle_executable") {
Sylvain Defresnedcab2f92019-04-03 16:34:05 +02001477 public_deps = [ ":${app_name}_generate_executable" ]
Brett Wilson796ed472018-07-16 15:11:09 -07001478 sources = [ "$gen_path/$app_name" ]
1479 outputs = [ "{{bundle_executable_dir}}/$app_name" ]
1480 }
1481 }
1482
Sylvain Defresnedcab2f92019-04-03 16:34:05 +02001483 create_bundle("$app_name.app") {
Brett Wilson796ed472018-07-16 15:11:09 -07001484 product_type = "com.apple.product-type.application"
1485
1486 if (is_ios) {
Sylvain Defresnedcab2f92019-04-03 16:34:05 +02001487 bundle_root_dir = "$root_build_dir/$target_name"
Brett Wilson796ed472018-07-16 15:11:09 -07001488 bundle_contents_dir = bundle_root_dir
1489 bundle_resources_dir = bundle_contents_dir
1490 bundle_executable_dir = bundle_contents_dir
Brett Wilson796ed472018-07-16 15:11:09 -07001491
1492 extra_attributes = {
1493 ONLY_ACTIVE_ARCH = "YES"
1494 DEBUG_INFORMATION_FORMAT = "dwarf"
1495 }
1496 } else {
Sylvain Defresnedcab2f92019-04-03 16:34:05 +02001497 bundle_root_dir = "$root_build_dir/$target_name"
1498 bundle_contents_dir = "$bundle_root_dir/Contents"
1499 bundle_resources_dir = "$bundle_contents_dir/Resources"
1500 bundle_executable_dir = "$bundle_contents_dir/MacOS"
Brett Wilson796ed472018-07-16 15:11:09 -07001501 }
1502 deps = [ ":${app_name}_bundle_info_plist" ]
1503 if (is_ios && code_signing) {
1504 deps += [ ":${app_name}_generate_executable" ]
1505 code_signing_script = "//build/config/ios/codesign.py"
1506 code_signing_sources = [
1507 invoker.entitlements_path,
1508 "$target_gen_dir/$app_name",
1509 ]
1510 code_signing_outputs = [
1511 "$bundle_root_dir/$app_name",
1512 "$bundle_root_dir/_CodeSignature/CodeResources",
1513 "$bundle_root_dir/embedded.mobileprovision",
1514 "$target_gen_dir/$app_name.xcent",
1515 ]
1516 code_signing_args = [
1517 "-i=" + ios_code_signing_identity,
1518 "-b=" + rebase_path(
1519 "$target_gen_dir/$app_name", root_build_dir),
1520 "-e=" + rebase_path(
1521 invoker.entitlements_path, root_build_dir),
1522 "-e=" + rebase_path(
1523 "$target_gen_dir/$app_name.xcent", root_build_dir),
1524 rebase_path(bundle_root_dir, root_build_dir),
1525 ]
1526 } else {
1527 deps += [ ":${app_name}_bundle_executable" ]
1528 }
1529 }
1530 }
1531 }
1532```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001533### **executable**: Declare an executable target.
Brett Wilson796ed472018-07-16 15:11:09 -07001534
1535#### **Variables**
1536
1537```
1538 Flags: cflags, cflags_c, cflags_cc, cflags_objc, cflags_objcc,
1539 asmflags, defines, include_dirs, inputs, ldflags, lib_dirs,
1540 libs, precompiled_header, precompiled_source
1541 Deps: data_deps, deps, public_deps
1542 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08001543 General: check_includes, configs, data, friend, inputs, metadata,
1544 output_name, output_extension, public, sources, testonly,
1545 visibility
1546```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001547### **generated_file**: Declare a generated_file target.
Nate Fischer8ed01d32019-01-08 17:32:01 -08001548
1549```
1550 Writes data value(s) to disk on resolution. This target type mirrors some
1551 functionality of the write_file() function, but also provides the ability to
1552 collect metadata from its dependencies on resolution rather than writing out
1553 parse time.
1554
1555 The `outputs` variable is required to be a list with a single element,
1556 specifying the intended location of the output file.
1557
1558 The `output_conversion` variable specified the format to write the
1559 value. See `gn help output_conversion`.
1560
1561 One of `contents` or `data_keys` must be specified; use of `data` will write
1562 the contents of that value to file, while use of `data_keys` will trigger a
1563 metadata collection walk based on the dependencies of the target and the
1564 optional values of the `rebase` and `walk_keys` variables. See
1565 `gn help metadata`.
1566
1567 Collected metadata, if specified, will be returned in postorder of
1568 dependencies. See the example for details.
1569```
1570
1571#### **Example (metadata collection)**
1572
1573```
1574 Given the following targets defined in //base/BUILD.gn, where A depends on B
1575 and B depends on C and D:
1576
1577 group("a") {
1578 metadata = {
1579 doom_melon = [ "enable" ]
1580 my_files = [ "foo.cpp" ]
1581
1582 // Note: this is functionally equivalent to not defining `my_barrier`
1583 // at all in this target's metadata.
1584 my_barrier = [ "" ]
1585 }
1586
1587 deps = [ ":b" ]
1588 }
1589
Julie Hockettd69a9c32019-01-23 14:36:18 -08001590 group("b") {
Nate Fischer8ed01d32019-01-08 17:32:01 -08001591 metadata = {
1592 my_files = [ "bar.cpp" ]
1593 my_barrier = [ ":c" ]
1594 }
1595
1596 deps = [ ":c", ":d" ]
1597 }
1598
1599 group("c") {
1600 metadata = {
1601 doom_melon = [ "disable" ]
1602 my_files = [ "baz.cpp" ]
1603 }
1604 }
1605
1606 group("d") {
1607 metadata = {
1608 my_files = [ "missing.cpp" ]
1609 }
1610 }
1611
1612 If the following generated_file target is defined:
1613
1614 generated_file("my_files_metadata") {
1615 outputs = [ "$root_build_dir/my_files.json" ]
1616 data_keys = [ "my_files" ]
1617
1618 deps = [ "//base:a" ]
1619 }
1620
1621 The following will be written to "$root_build_dir/my_files.json" (less the
1622 comments):
1623 [
1624 "baz.cpp", // from //base:c via //base:b
1625 "missing.cpp" // from //base:d via //base:b
1626 "bar.cpp", // from //base:b via //base:a
1627 "foo.cpp", // from //base:a
1628 ]
1629
1630 Alternatively, as an example of using walk_keys, if the following
1631 generated_file target is defined:
1632
1633 generated_file("my_files_metadata") {
1634 outputs = [ "$root_build_dir/my_files.json" ]
1635 data_keys = [ "my_files" ]
1636 walk_keys = [ "my_barrier" ]
1637
1638 deps = [ "//base:a" ]
1639 }
1640
1641 The following will be written to "$root_build_dir/my_files.json" (again less
1642 the comments):
1643 [
1644 "baz.cpp", // from //base:c via //base:b
1645 "bar.cpp", // from //base:b via //base:a
1646 "foo.cpp", // from //base:a
1647 ]
1648
1649 If `rebase` is used in the following generated_file target:
1650
1651 generated_file("my_files_metadata") {
1652 outputs = [ "$root_build_dir/my_files.json" ]
1653 data_keys = [ "my_files" ]
1654 walk_keys = [ "my_barrier" ]
1655 rebase = root_build_dir
1656
1657 deps = [ "//base:a" ]
1658 }
1659
1660 The following will be written to "$root_build_dir/my_files.json" (again less
1661 the comments) (assuming root_build_dir = "//out"):
1662 [
1663 "../base/baz.cpp", // from //base:c via //base:b
1664 "../base/bar.cpp", // from //base:b via //base:a
1665 "../base/foo.cpp", // from //base:a
1666 ]
1667```
1668
1669#### **Variables**
1670
1671```
Julie Hockettd69a9c32019-01-23 14:36:18 -08001672 contents
Nate Fischer8ed01d32019-01-08 17:32:01 -08001673 data_keys
1674 rebase
1675 walk_keys
1676 output_conversion
1677 Deps: data_deps, deps, public_deps
1678 Dependent configs: all_dependent_configs, public_configs
Brett Wilson796ed472018-07-16 15:11:09 -07001679```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001680### **group**: Declare a named group of targets.
Brett Wilson796ed472018-07-16 15:11:09 -07001681
1682```
1683 This target type allows you to create meta-targets that just collect a set of
1684 dependencies into one named target. Groups can additionally specify configs
1685 that apply to their dependents.
1686```
1687
1688#### **Variables**
1689
1690```
1691 Deps: data_deps, deps, public_deps
1692 Dependent configs: all_dependent_configs, public_configs
1693```
1694
1695#### **Example**
1696
1697```
1698 group("all") {
1699 deps = [
1700 "//project:runner",
1701 "//project:unit_tests",
1702 ]
1703 }
1704```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001705### **loadable_module**: Declare a loadable module target.
Brett Wilson796ed472018-07-16 15:11:09 -07001706
1707```
1708 This target type allows you to create an object file that is (and can only
1709 be) loaded and unloaded at runtime.
1710
1711 A loadable module will be specified on the linker line for targets listing
1712 the loadable module in its "deps". If you don't want this (if you don't need
1713 to dynamically load the library at runtime), then you should use a
1714 "shared_library" target type instead.
1715```
1716
1717#### **Variables**
1718
1719```
1720 Flags: cflags, cflags_c, cflags_cc, cflags_objc, cflags_objcc,
1721 asmflags, defines, include_dirs, inputs, ldflags, lib_dirs,
1722 libs, precompiled_header, precompiled_source
1723 Deps: data_deps, deps, public_deps
1724 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08001725 General: check_includes, configs, data, friend, inputs, metadata,
1726 output_name, output_extension, public, sources, testonly,
1727 visibility
Brett Wilson796ed472018-07-16 15:11:09 -07001728```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001729### **shared_library**: Declare a shared library target.
Brett Wilson796ed472018-07-16 15:11:09 -07001730
1731```
1732 A shared library will be specified on the linker line for targets listing the
1733 shared library in its "deps". If you don't want this (say you dynamically
1734 load the library at runtime), then you should depend on the shared library
1735 via "data_deps" or, on Darwin platforms, use a "loadable_module" target type
1736 instead.
1737```
1738
1739#### **Variables**
1740
1741```
1742 Flags: cflags, cflags_c, cflags_cc, cflags_objc, cflags_objcc,
1743 asmflags, defines, include_dirs, inputs, ldflags, lib_dirs,
1744 libs, precompiled_header, precompiled_source
1745 Deps: data_deps, deps, public_deps
1746 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08001747 General: check_includes, configs, data, friend, inputs, metadata,
1748 output_name, output_extension, public, sources, testonly,
1749 visibility
Brett Wilson796ed472018-07-16 15:11:09 -07001750```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001751### **source_set**: Declare a source set target.
Brett Wilson796ed472018-07-16 15:11:09 -07001752
1753```
1754 A source set is a collection of sources that get compiled, but are not linked
1755 to produce any kind of library. Instead, the resulting object files are
1756 implicitly added to the linker line of all targets that depend on the source
1757 set.
1758
1759 In most cases, a source set will behave like a static library, except no
1760 actual library file will be produced. This will make the build go a little
1761 faster by skipping creation of a large static library, while maintaining the
1762 organizational benefits of focused build targets.
1763
1764 The main difference between a source set and a static library is around
1765 handling of exported symbols. Most linkers assume declaring a function
1766 exported means exported from the static library. The linker can then do dead
1767 code elimination to delete code not reachable from exported functions.
1768
1769 A source set will not do this code elimination since there is no link step.
Julie Hockette2a29402018-07-31 10:11:42 -07001770 This allows you to link many source sets into a shared library and have the
Brett Wilson796ed472018-07-16 15:11:09 -07001771 "exported symbol" notation indicate "export from the final shared library and
1772 not from the intermediate targets." There is no way to express this concept
1773 when linking multiple static libraries into a shared library.
1774```
1775
1776#### **Variables**
1777
1778```
1779 Flags: cflags, cflags_c, cflags_cc, cflags_objc, cflags_objcc,
1780 asmflags, defines, include_dirs, inputs, ldflags, lib_dirs,
1781 libs, precompiled_header, precompiled_source
1782 Deps: data_deps, deps, public_deps
1783 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08001784 General: check_includes, configs, data, friend, inputs, metadata,
1785 output_name, output_extension, public, sources, testonly,
1786 visibility
Brett Wilson796ed472018-07-16 15:11:09 -07001787```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001788### **static_library**: Declare a static library target.
Brett Wilson796ed472018-07-16 15:11:09 -07001789
1790```
1791 Make a ".a" / ".lib" file.
1792
1793 If you only need the static library for intermediate results in the build,
1794 you should consider a source_set instead since it will skip the (potentially
1795 slow) step of creating the intermediate library file.
1796```
1797
1798#### **Variables**
1799
1800```
1801 complete_static_lib
1802 Flags: cflags, cflags_c, cflags_cc, cflags_objc, cflags_objcc,
1803 asmflags, defines, include_dirs, inputs, ldflags, lib_dirs,
1804 libs, precompiled_header, precompiled_source
1805 Deps: data_deps, deps, public_deps
1806 Dependent configs: all_dependent_configs, public_configs
Nate Fischer8ed01d32019-01-08 17:32:01 -08001807 General: check_includes, configs, data, friend, inputs, metadata,
1808 output_name, output_extension, public, sources, testonly,
1809 visibility
Brett Wilson796ed472018-07-16 15:11:09 -07001810```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001811### **target**: Declare an target with the given programmatic type.
Brett Wilson796ed472018-07-16 15:11:09 -07001812
1813```
1814 target(target_type_string, target_name_string) { ... }
1815
1816 The target() function is a way to invoke a built-in target or template with a
1817 type determined at runtime. This is useful for cases where the type of a
1818 target might not be known statically.
1819
1820 Only templates and built-in target functions are supported for the
1821 target_type_string parameter. Arbitrary functions, configs, and toolchains
1822 are not supported.
1823
1824 The call:
1825 target("source_set", "doom_melon") {
1826 Is equivalent to:
1827 source_set("doom_melon") {
1828```
1829
1830#### **Example**
1831
1832```
1833 if (foo_build_as_shared) {
1834 my_type = "shared_library"
1835 } else {
1836 my_type = "source_set"
1837 }
1838
1839 target(my_type, "foo") {
1840 ...
1841 }
1842```
1843## Buildfile functions
1844
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001845### **assert**: Assert an expression is true at generation time.
Brett Wilson796ed472018-07-16 15:11:09 -07001846
1847```
1848 assert( [, ])
1849
1850 If the condition is false, the build will fail with an error. If the
1851 optional second argument is provided, that string will be printed
1852 with the error message.
1853```
1854
1855#### **Examples**
1856
1857```
1858 assert(is_win)
1859 assert(defined(sources), "Sources must be defined");
1860```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001861### **config**: Defines a configuration object.
Brett Wilson796ed472018-07-16 15:11:09 -07001862
1863```
1864 Configuration objects can be applied to targets and specify sets of compiler
1865 flags, includes, defines, etc. They provide a way to conveniently group sets
1866 of this configuration information.
1867
1868 A config is referenced by its label just like a target.
1869
1870 The values in a config are additive only. If you want to remove a flag you
1871 need to remove the corresponding config that sets it. The final set of flags,
1872 defines, etc. for a target is generated in this order:
1873
1874 1. The values specified directly on the target (rather than using a config.
1875 2. The configs specified in the target's "configs" list, in order.
1876 3. Public_configs from a breadth-first traversal of the dependency tree in
1877 the order that the targets appear in "deps".
1878 4. All dependent configs from a breadth-first traversal of the dependency
1879 tree in the order that the targets appear in "deps".
1880```
1881
Joe Armstrong39413942019-03-15 10:34:03 +08001882#### **More background**
1883
1884```
1885 Configs solve a problem where the build system needs to have a higher-level
1886 understanding of various compiler settings. For example, some compiler flags
1887 have to appear in a certain order relative to each other, some settings like
1888 defines and flags logically go together, and the build system needs to
1889 de-duplicate flags even though raw command-line parameters can't always be
1890 operated on in that way.
1891
1892 The config gives a name to a group of settings that can then be reasoned
1893 about by GN. GN can know that configs with the same label are the same thing
1894 so can be de-duplicated. It allows related settings to be grouped so they
1895 are added or removed as a unit. And it allows targets to refer to settings
1896 with conceptual names ("no_rtti", "enable_exceptions", etc.) rather than
1897 having to hard-coding every compiler's flags each time they are referred to.
1898```
1899
Brett Wilson796ed472018-07-16 15:11:09 -07001900#### **Variables valid in a config definition**
Joe Armstrong39413942019-03-15 10:34:03 +08001901
Brett Wilson796ed472018-07-16 15:11:09 -07001902```
1903 Flags: cflags, cflags_c, cflags_cc, cflags_objc, cflags_objcc,
1904 asmflags, defines, include_dirs, inputs, ldflags, lib_dirs,
1905 libs, precompiled_header, precompiled_source
1906 Nested configs: configs
1907```
1908
1909#### **Variables on a target used to apply configs**
1910
1911```
1912 all_dependent_configs, configs, public_configs
1913```
1914
1915#### **Example**
1916
1917```
1918 config("myconfig") {
Joe Armstrongf5ad8072019-05-08 08:42:56 +08001919 include_dirs = [ "include/common" ]
Brett Wilson796ed472018-07-16 15:11:09 -07001920 defines = [ "ENABLE_DOOM_MELON" ]
1921 }
1922
1923 executable("mything") {
1924 configs = [ ":myconfig" ]
1925 }
1926```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001927### **declare_args**: Declare build arguments.
Brett Wilson796ed472018-07-16 15:11:09 -07001928
1929```
1930 Introduces the given arguments into the current scope. If they are not
1931 specified on the command line or in a toolchain's arguments, the default
1932 values given in the declare_args block will be used. However, these defaults
1933 will not override command-line values.
1934
1935 See also "gn help buildargs" for an overview.
1936
1937 The precise behavior of declare args is:
1938
1939 1. The declare_args() block executes. Any variable defined in the enclosing
1940 scope is available for reading, but any variable defined earlier in
1941 the current scope is not (since the overrides haven't been applied yet).
1942
1943 2. At the end of executing the block, any variables set within that scope
1944 are saved globally as build arguments, with their current values being
1945 saved as the "default value" for that argument.
1946
1947 3. User-defined overrides are applied. Anything set in "gn args" now
1948 overrides any default values. The resulting set of variables is promoted
1949 to be readable from the following code in the file.
1950
1951 This has some ramifications that may not be obvious:
1952
1953 - You should not perform difficult work inside a declare_args block since
1954 this only sets a default value that may be discarded. In particular,
1955 don't use the result of exec_script() to set the default value. If you
1956 want to have a script-defined default, set some default "undefined" value
1957 like [], "", or -1, and after the declare_args block, call exec_script if
1958 the value is unset by the user.
1959
1960 - Because you cannot read the value of a variable defined in the same
1961 block, if you need to make the default value of one arg depend
1962 on the possibly-overridden value of another, write two separate
1963 declare_args() blocks:
1964
1965 declare_args() {
1966 enable_foo = true
1967 }
1968 declare_args() {
1969 # Bar defaults to same user-overridden state as foo.
1970 enable_bar = enable_foo
1971 }
1972```
1973
1974#### **Example**
1975
1976```
1977 declare_args() {
1978 enable_teleporter = true
1979 enable_doom_melon = false
1980 }
1981
1982 If you want to override the (default disabled) Doom Melon:
1983 gn --args="enable_doom_melon=true enable_teleporter=true"
1984 This also sets the teleporter, but it's already defaulted to on so it will
1985 have no effect.
1986```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08001987### **defined**: Returns whether an identifier is defined.
Brett Wilson796ed472018-07-16 15:11:09 -07001988
1989```
1990 Returns true if the given argument is defined. This is most useful in
1991 templates to assert that the caller set things up properly.
1992
1993 You can pass an identifier:
1994 defined(foo)
1995 which will return true or false depending on whether foo is defined in the
1996 current scope.
1997
1998 You can also check a named scope:
1999 defined(foo.bar)
2000 which will return true or false depending on whether bar is defined in the
2001 named scope foo. It will throw an error if foo is not defined or is not a
2002 scope.
2003```
2004
2005#### **Example**
2006
2007```
2008 template("mytemplate") {
2009 # To help users call this template properly...
2010 assert(defined(invoker.sources), "Sources must be defined")
2011
2012 # If we want to accept an optional "values" argument, we don't
2013 # want to dereference something that may not be defined.
2014 if (defined(invoker.values)) {
2015 values = invoker.values
2016 } else {
2017 values = "some default value"
2018 }
2019 }
2020```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002021### **exec_script**: Synchronously run a script and return the output.
Brett Wilson796ed472018-07-16 15:11:09 -07002022
2023```
2024 exec_script(filename,
2025 arguments = [],
2026 input_conversion = "",
2027 file_dependencies = [])
2028
2029 Runs the given script, returning the stdout of the script. The build
2030 generation will fail if the script does not exist or returns a nonzero exit
2031 code.
2032
2033 The current directory when executing the script will be the root build
2034 directory. If you are passing file names, you will want to use the
2035 rebase_path() function to make file names relative to this path (see "gn help
2036 rebase_path").
Gary Miguelce7fa362018-09-17 12:48:17 -07002037
2038 The default script interpreter is Python ("python" on POSIX, "python.exe" or
2039 "python.bat" on Windows). This can be configured by the script_executable
2040 variable, see "gn help dotfile".
Brett Wilson796ed472018-07-16 15:11:09 -07002041```
2042
2043#### **Arguments**:
2044
2045```
2046 filename:
Gary Miguelce7fa362018-09-17 12:48:17 -07002047 File name of script to execute. Non-absolute names will be treated as
2048 relative to the current build file.
Brett Wilson796ed472018-07-16 15:11:09 -07002049
2050 arguments:
2051 A list of strings to be passed to the script as arguments. May be
2052 unspecified or the empty list which means no arguments.
2053
2054 input_conversion:
Julie Hockett81ee1962019-05-13 11:24:42 -07002055 Controls how the file is read and parsed. See "gn help io_conversion".
Brett Wilson796ed472018-07-16 15:11:09 -07002056
2057 If unspecified, defaults to the empty string which causes the script
2058 result to be discarded. exec script will return None.
2059
2060 dependencies:
2061 (Optional) A list of files that this script reads or otherwise depends
2062 on. These dependencies will be added to the build result such that if any
2063 of them change, the build will be regenerated and the script will be
2064 re-run.
2065
2066 The script itself will be an implicit dependency so you do not need to
2067 list it.
2068```
2069
2070#### **Example**
2071
2072```
2073 all_lines = exec_script(
2074 "myscript.py", [some_input], "list lines",
2075 [ rebase_path("data_file.txt", root_build_dir) ])
2076
2077 # This example just calls the script with no arguments and discards the
2078 # result.
2079 exec_script("//foo/bar/myscript.py")
2080```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002081### **foreach**: Iterate over a list.
Brett Wilson796ed472018-07-16 15:11:09 -07002082
2083```
2084 foreach(, ) {
2085
2086 }
2087
2088 Executes the loop contents block over each item in the list, assigning the
2089 loop_var to each item in sequence. The will be a copy so assigning
2090 to it will not mutate the list. The loop will iterate over a copy of
2091 so mutating it inside the loop will not affect iteration.
2092
2093 The block does not introduce a new scope, so that variable assignments inside
2094 the loop will be visible once the loop terminates.
2095
2096 The loop variable will temporarily shadow any existing variables with the
2097 same name for the duration of the loop. After the loop terminates the loop
2098 variable will no longer be in scope, and the previous value (if any) will be
2099 restored.
2100```
2101
2102#### **Example**
2103
2104```
2105 mylist = [ "a", "b", "c" ]
2106 foreach(i, mylist) {
2107 print(i)
2108 }
2109
2110 Prints:
2111 a
2112 b
2113 c
2114```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002115### **forward_variables_from**: Copies variables from a different scope.
Brett Wilson796ed472018-07-16 15:11:09 -07002116
2117```
2118 forward_variables_from(from_scope, variable_list_or_star,
2119 variable_to_not_forward_list = [])
2120
2121 Copies the given variables from the given scope to the local scope if they
2122 exist. This is normally used in the context of templates to use the values of
2123 variables defined in the template invocation to a template-defined target.
2124
2125 The variables in the given variable_list will be copied if they exist in the
2126 given scope or any enclosing scope. If they do not exist, nothing will happen
2127 and they be left undefined in the current scope.
2128
2129 As a special case, if the variable_list is a string with the value of "*",
2130 all variables from the given scope will be copied. "*" only copies variables
2131 set directly on the from_scope, not enclosing ones. Otherwise it would
2132 duplicate all global variables.
2133
2134 When an explicit list of variables is supplied, if the variable exists in the
2135 current (destination) scope already, an error will be thrown. If "*" is
2136 specified, variables in the current scope will be clobbered (the latter is
2137 important because most targets have an implicit configs list, which means it
2138 wouldn't work at all if it didn't clobber).
2139
2140 The sources assignment filter (see "gn help set_sources_assignment_filter")
2141 is never applied by this function. It's assumed than any desired filtering
2142 was already done when sources was set on the from_scope.
2143
2144 If variables_to_not_forward_list is non-empty, then it must contains a list
2145 of variable names that will not be forwarded. This is mostly useful when
2146 variable_list_or_star has a value of "*".
2147```
2148
2149#### **Examples**
2150
2151```
Andrew Grieve57a964c2018-09-14 10:50:56 -04002152 # forward_variables_from(invoker, ["foo"])
2153 # is equivalent to:
2154 assert(!defined(foo))
2155 if (defined(invoker.foo)) {
2156 foo = invoker.foo
2157 }
2158
Brett Wilson796ed472018-07-16 15:11:09 -07002159 # This is a common action template. It would invoke a script with some given
2160 # parameters, and wants to use the various types of deps and the visibility
2161 # from the invoker if it's defined. It also injects an additional dependency
2162 # to all targets.
2163 template("my_test") {
2164 action(target_name) {
2165 forward_variables_from(invoker, [ "data_deps", "deps",
Julie Hockette2a29402018-07-31 10:11:42 -07002166 "public_deps", "visibility"])
Brett Wilson796ed472018-07-16 15:11:09 -07002167 # Add our test code to the dependencies.
2168 # "deps" may or may not be defined at this point.
2169 if (defined(deps)) {
2170 deps += [ "//tools/doom_melon" ]
2171 } else {
2172 deps = [ "//tools/doom_melon" ]
2173 }
2174 }
2175 }
2176
Julie Hockette2a29402018-07-31 10:11:42 -07002177 # This is a template around a target whose type depends on a global variable.
2178 # It forwards all values from the invoker.
Brett Wilson796ed472018-07-16 15:11:09 -07002179 template("my_wrapper") {
2180 target(my_wrapper_target_type, target_name) {
2181 forward_variables_from(invoker, "*")
2182 }
2183 }
2184
2185 # A template that wraps another. It adds behavior based on one
2186 # variable, and forwards all others to the nested target.
2187 template("my_ios_test_app") {
2188 ios_test_app(target_name) {
2189 forward_variables_from(invoker, "*", ["test_bundle_name"])
2190 if (!defined(extra_substitutions)) {
2191 extra_substitutions = []
2192 }
2193 extra_substitutions += [ "BUNDLE_ID_TEST_NAME=$test_bundle_name" ]
2194 }
2195 }
2196```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002197### **get_label_info**: Get an attribute from a target's label.
Brett Wilson796ed472018-07-16 15:11:09 -07002198
2199```
2200 get_label_info(target_label, what)
2201
2202 Given the label of a target, returns some attribute of that target. The
2203 target need not have been previously defined in the same file, since none of
2204 the attributes depend on the actual target definition, only the label itself.
2205
2206 See also "gn help get_target_outputs".
2207```
2208
2209#### **Possible values for the "what" parameter**
2210
2211```
2212 "name"
2213 The short name of the target. This will match the value of the
2214 "target_name" variable inside that target's declaration. For the label
2215 "//foo/bar:baz" this will return "baz".
2216
2217 "dir"
2218 The directory containing the target's definition, with no slash at the
2219 end. For the label "//foo/bar:baz" this will return "//foo/bar".
2220
2221 "target_gen_dir"
2222 The generated file directory for the target. This will match the value of
2223 the "target_gen_dir" variable when inside that target's declaration.
2224
2225 "root_gen_dir"
2226 The root of the generated file tree for the target. This will match the
2227 value of the "root_gen_dir" variable when inside that target's
2228 declaration.
2229
2230 "target_out_dir
2231 The output directory for the target. This will match the value of the
2232 "target_out_dir" variable when inside that target's declaration.
2233
2234 "root_out_dir"
2235 The root of the output file tree for the target. This will match the
2236 value of the "root_out_dir" variable when inside that target's
2237 declaration.
2238
2239 "label_no_toolchain"
2240 The fully qualified version of this label, not including the toolchain.
2241 For the input ":bar" it might return "//foo:bar".
2242
2243 "label_with_toolchain"
2244 The fully qualified version of this label, including the toolchain. For
2245 the input ":bar" it might return "//foo:bar(//toolchain:x64)".
2246
2247 "toolchain"
2248 The label of the toolchain. This will match the value of the
2249 "current_toolchain" variable when inside that target's declaration.
2250```
2251
2252#### **Examples**
2253
2254```
2255 get_label_info(":foo", "name")
2256 # Returns string "foo".
2257
2258 get_label_info("//foo/bar:baz", "target_gen_dir")
2259 # Returns string "//out/Debug/gen/foo/bar".
2260```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002261### **get_path_info**: Extract parts of a file or directory name.
Brett Wilson796ed472018-07-16 15:11:09 -07002262
2263```
2264 get_path_info(input, what)
2265
2266 The first argument is either a string representing a file or directory name,
2267 or a list of such strings. If the input is a list the return value will be a
2268 list containing the result of applying the rule to each item in the input.
2269```
2270
2271#### **Possible values for the "what" parameter**
2272
2273```
2274 "file"
2275 The substring after the last slash in the path, including the name and
2276 extension. If the input ends in a slash, the empty string will be
2277 returned.
2278 "foo/bar.txt" => "bar.txt"
2279 "bar.txt" => "bar.txt"
2280 "foo/" => ""
2281 "" => ""
2282
2283 "name"
2284 The substring of the file name not including the extension.
2285 "foo/bar.txt" => "bar"
2286 "foo/bar" => "bar"
2287 "foo/" => ""
2288
2289 "extension"
2290 The substring following the last period following the last slash, or the
2291 empty string if not found. The period is not included.
2292 "foo/bar.txt" => "txt"
2293 "foo/bar" => ""
2294
2295 "dir"
2296 The directory portion of the name, not including the slash.
2297 "foo/bar.txt" => "foo"
2298 "//foo/bar" => "//foo"
2299 "foo" => "."
2300
2301 The result will never end in a slash, so if the resulting is empty, the
2302 system ("/") or source ("//") roots, a "." will be appended such that it
2303 is always legal to append a slash and a filename and get a valid path.
2304
2305 "out_dir"
2306 The output file directory corresponding to the path of the given file,
2307 not including a trailing slash.
2308 "//foo/bar/baz.txt" => "//out/Default/obj/foo/bar"
2309
2310 "gen_dir"
2311 The generated file directory corresponding to the path of the given file,
2312 not including a trailing slash.
2313 "//foo/bar/baz.txt" => "//out/Default/gen/foo/bar"
2314
2315 "abspath"
2316 The full absolute path name to the file or directory. It will be resolved
2317 relative to the current directory, and then the source- absolute version
2318 will be returned. If the input is system- absolute, the same input will
2319 be returned.
2320 "foo/bar.txt" => "//mydir/foo/bar.txt"
2321 "foo/" => "//mydir/foo/"
2322 "//foo/bar" => "//foo/bar" (already absolute)
2323 "/usr/include" => "/usr/include" (already absolute)
2324
2325 If you want to make the path relative to another directory, or to be
2326 system-absolute, see rebase_path().
2327```
2328
2329#### **Examples**
2330```
2331 sources = [ "foo.cc", "foo.h" ]
2332 result = get_path_info(source, "abspath")
2333 # result will be [ "//mydir/foo.cc", "//mydir/foo.h" ]
2334
2335 result = get_path_info("//foo/bar/baz.cc", "dir")
2336 # result will be "//foo/bar"
2337
2338 # Extract the source-absolute directory name,
Joe Armstrong39413942019-03-15 10:34:03 +08002339 result = get_path_info(get_path_info(path, "dir"), "abspath")
Brett Wilson796ed472018-07-16 15:11:09 -07002340```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002341### **get_target_outputs**: [file list] Get the list of outputs from a target.
Brett Wilson796ed472018-07-16 15:11:09 -07002342
2343```
2344 get_target_outputs(target_label)
2345
2346 Returns a list of output files for the named target. The named target must
2347 have been previously defined in the current file before this function is
2348 called (it can't reference targets in other files because there isn't a
2349 defined execution order, and it obviously can't reference targets that are
2350 defined after the function call).
2351
2352 Only copy and action targets are supported. The outputs from binary targets
2353 will depend on the toolchain definition which won't necessarily have been
2354 loaded by the time a given line of code has run, and source sets and groups
2355 have no useful output file.
2356```
2357
2358#### **Return value**
2359
2360```
2361 The names in the resulting list will be absolute file paths (normally like
2362 "//out/Debug/bar.exe", depending on the build directory).
2363
2364 action targets: this will just return the files specified in the "outputs"
2365 variable of the target.
2366
2367 action_foreach targets: this will return the result of applying the output
2368 template to the sources (see "gn help source_expansion"). This will be the
2369 same result (though with guaranteed absolute file paths), as
2370 process_file_template will return for those inputs (see "gn help
2371 process_file_template").
2372
2373 binary targets (executables, libraries): this will return a list of the
2374 resulting binary file(s). The "main output" (the actual binary or library)
2375 will always be the 0th element in the result. Depending on the platform and
2376 output type, there may be other output files as well (like import libraries)
2377 which will follow.
2378
2379 source sets and groups: this will return a list containing the path of the
2380 "stamp" file that Ninja will produce once all outputs are generated. This
2381 probably isn't very useful.
2382```
2383
2384#### **Example**
2385
2386```
2387 # Say this action generates a bunch of C source files.
2388 action_foreach("my_action") {
2389 sources = [ ... ]
2390 outputs = [ ... ]
2391 }
2392
2393 # Compile the resulting source files into a source set.
2394 source_set("my_lib") {
2395 sources = get_target_outputs(":my_action")
2396 }
2397```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002398### **getenv**: Get an environment variable.
Brett Wilson796ed472018-07-16 15:11:09 -07002399
2400```
2401 value = getenv(env_var_name)
2402
2403 Returns the value of the given environment variable. If the value is not
2404 found, it will try to look up the variable with the "opposite" case (based on
2405 the case of the first letter of the variable), but is otherwise
2406 case-sensitive.
2407
2408 If the environment variable is not found, the empty string will be returned.
2409 Note: it might be nice to extend this if we had the concept of "none" in the
2410 language to indicate lookup failure.
2411```
2412
2413#### **Example**
2414
2415```
2416 home_dir = getenv("HOME")
2417```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002418### **import**: Import a file into the current scope.
Brett Wilson796ed472018-07-16 15:11:09 -07002419
2420```
2421 The import command loads the rules and variables resulting from executing the
2422 given file into the current scope.
2423
2424 By convention, imported files are named with a .gni extension.
2425
2426 An import is different than a C++ "include". The imported file is executed in
2427 a standalone environment from the caller of the import command. The results
2428 of this execution are cached for other files that import the same .gni file.
2429
2430 Note that you can not import a BUILD.gn file that's otherwise used in the
2431 build. Files must either be imported or implicitly loaded as a result of deps
2432 rules, but not both.
2433
2434 The imported file's scope will be merged with the scope at the point import
2435 was called. If there is a conflict (both the current scope and the imported
2436 file define some variable or rule with the same name but different value), a
2437 runtime error will be thrown. Therefore, it's good practice to minimize the
2438 stuff that an imported file defines.
2439
2440 Variables and templates beginning with an underscore '_' are considered
2441 private and will not be imported. Imported files can use such variables for
2442 internal computation without affecting other files.
2443```
2444
2445#### **Examples**
2446
2447```
2448 import("//build/rules/idl_compilation_rule.gni")
2449
2450 # Looks in the current directory.
2451 import("my_vars.gni")
2452```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002453### **not_needed**: Mark variables from scope as not needed.
Brett Wilson796ed472018-07-16 15:11:09 -07002454
2455```
2456 not_needed(variable_list_or_star, variable_to_ignore_list = [])
2457 not_needed(from_scope, variable_list_or_star,
2458 variable_to_ignore_list = [])
2459
2460 Mark the variables in the current or given scope as not needed, which means
2461 you will not get an error about unused variables for these. The
2462 variable_to_ignore_list allows excluding variables from "all matches" if
2463 variable_list_or_star is "*".
2464```
2465
2466#### **Example**
2467
2468```
2469 not_needed("*", [ "config" ])
2470 not_needed([ "data_deps", "deps" ])
2471 not_needed(invoker, "*", [ "config" ])
2472 not_needed(invoker, [ "data_deps", "deps" ])
2473```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002474### **pool**: Defines a pool object.
Brett Wilson796ed472018-07-16 15:11:09 -07002475
2476```
2477 Pool objects can be applied to a tool to limit the parallelism of the
2478 build. This object has a single property "depth" corresponding to
2479 the number of tasks that may run simultaneously.
2480
2481 As the file containing the pool definition may be executed in the
2482 context of more than one toolchain it is recommended to specify an
2483 explicit toolchain when defining and referencing a pool.
2484
Julie Hockette2a29402018-07-31 10:11:42 -07002485 A pool named "console" defined in the root build file represents Ninja's
2486 console pool. Targets using this pool will have access to the console's
2487 stdin and stdout, and output will not be buffered. This special pool must
2488 have a depth of 1. Pools not defined in the root must not be named "console".
2489 The console pool can only be defined for the default toolchain.
2490 Refer to the Ninja documentation on the console pool for more info.
2491
Brett Wilson796ed472018-07-16 15:11:09 -07002492 A pool is referenced by its label just like a target.
2493```
2494
2495#### **Variables**
2496
2497```
2498 depth*
2499 * = required
2500```
2501
2502#### **Example**
2503
2504```
2505 if (current_toolchain == default_toolchain) {
2506 pool("link_pool") {
2507 depth = 1
2508 }
2509 }
2510
2511 toolchain("toolchain") {
2512 tool("link") {
2513 command = "..."
2514 pool = ":link_pool($default_toolchain)")
2515 }
2516 }
2517```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002518### **print**: Prints to the console.
Brett Wilson796ed472018-07-16 15:11:09 -07002519
2520```
2521 Prints all arguments to the console separated by spaces. A newline is
2522 automatically appended to the end.
2523
2524 This function is intended for debugging. Note that build files are run in
2525 parallel so you may get interleaved prints. A buildfile may also be executed
2526 more than once in parallel in the context of different toolchains so the
2527 prints from one file may be duplicated or
2528 interleaved with itself.
2529```
2530
2531#### **Examples**
2532
2533```
2534 print("Hello world")
2535
2536 print(sources, deps)
2537```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002538### **process_file_template**: Do template expansion over a list of files.
Brett Wilson796ed472018-07-16 15:11:09 -07002539
2540```
2541 process_file_template(source_list, template)
2542
2543 process_file_template applies a template list to a source file list,
2544 returning the result of applying each template to each source. This is
2545 typically used for computing output file names from input files.
2546
2547 In most cases, get_target_outputs() will give the same result with shorter,
2548 more maintainable code. This function should only be used when that function
2549 can't be used (like there's no target or the target is defined in another
2550 build file).
2551```
2552
2553#### **Arguments**
2554
2555```
2556 The source_list is a list of file names.
2557
2558 The template can be a string or a list. If it is a list, multiple output
2559 strings are generated for each input.
2560
2561 The template should contain source expansions to which each name in the
2562 source list is applied. See "gn help source_expansion".
2563```
2564
2565#### **Example**
2566
2567```
2568 sources = [
2569 "foo.idl",
2570 "bar.idl",
2571 ]
2572 myoutputs = process_file_template(
2573 sources,
2574 [ "$target_gen_dir/{{source_name_part}}.cc",
2575 "$target_gen_dir/{{source_name_part}}.h" ])
2576
2577 The result in this case will be:
2578 [ "//out/Debug/foo.cc"
2579 "//out/Debug/foo.h"
2580 "//out/Debug/bar.cc"
2581 "//out/Debug/bar.h" ]
2582```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002583### **read_file**: Read a file into a variable.
Brett Wilson796ed472018-07-16 15:11:09 -07002584
2585```
2586 read_file(filename, input_conversion)
2587
2588 Whitespace will be trimmed from the end of the file. Throws an error if the
2589 file can not be opened.
2590```
2591
2592#### **Arguments**
2593
2594```
2595 filename
2596 Filename to read, relative to the build file.
2597
2598 input_conversion
Julie Hockett81ee1962019-05-13 11:24:42 -07002599 Controls how the file is read and parsed. See "gn help io_conversion".
Brett Wilson796ed472018-07-16 15:11:09 -07002600```
2601
2602#### **Example**
2603
2604```
2605 lines = read_file("foo.txt", "list lines")
2606```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002607### **rebase_path**: Rebase a file or directory to another location.
Brett Wilson796ed472018-07-16 15:11:09 -07002608
2609```
2610 converted = rebase_path(input,
2611 new_base = "",
2612 current_base = ".")
2613
2614 Takes a string argument representing a file name, or a list of such strings
2615 and converts it/them to be relative to a different base directory.
2616
2617 When invoking the compiler or scripts, GN will automatically convert sources
2618 and include directories to be relative to the build directory. However, if
2619 you're passing files directly in the "args" array or doing other manual
2620 manipulations where GN doesn't know something is a file name, you will need
2621 to convert paths to be relative to what your tool is expecting.
2622
2623 The common case is to use this to convert paths relative to the current
2624 directory to be relative to the build directory (which will be the current
2625 directory when executing scripts).
2626
2627 If you want to convert a file path to be source-absolute (that is, beginning
2628 with a double slash like "//foo/bar"), you should use the get_path_info()
2629 function. This function won't work because it will always make relative
2630 paths, and it needs to support making paths relative to the source root, so
2631 can't also generate source-absolute paths without more special-cases.
2632```
2633
2634#### **Arguments**
2635
2636```
2637 input
2638 A string or list of strings representing file or directory names These
2639 can be relative paths ("foo/bar.txt"), system absolute paths
2640 ("/foo/bar.txt"), or source absolute paths ("//foo/bar.txt").
2641
2642 new_base
2643 The directory to convert the paths to be relative to. This can be an
2644 absolute path or a relative path (which will be treated as being relative
2645 to the current BUILD-file's directory).
2646
2647 As a special case, if new_base is the empty string (the default), all
2648 paths will be converted to system-absolute native style paths with system
2649 path separators. This is useful for invoking external programs.
2650
2651 current_base
2652 Directory representing the base for relative paths in the input. If this
2653 is not an absolute path, it will be treated as being relative to the
2654 current build file. Use "." (the default) to convert paths from the
2655 current BUILD-file's directory.
2656```
2657
2658#### **Return value**
2659
2660```
2661 The return value will be the same type as the input value (either a string or
2662 a list of strings). All relative and source-absolute file names will be
2663 converted to be relative to the requested output System-absolute paths will
2664 be unchanged.
2665
2666 Whether an output path will end in a slash will match whether the
2667 corresponding input path ends in a slash. It will return "." or "./"
2668 (depending on whether the input ends in a slash) to avoid returning empty
2669 strings. This means if you want a root path ("//" or "/") not ending in a
2670 slash, you can add a dot ("//.").
2671```
2672
2673#### **Example**
2674
2675```
2676 # Convert a file in the current directory to be relative to the build
2677 # directory (the current dir when executing compilers and scripts).
2678 foo = rebase_path("myfile.txt", root_build_dir)
2679 # might produce "../../project/myfile.txt".
2680
2681 # Convert a file to be system absolute:
2682 foo = rebase_path("myfile.txt")
2683 # Might produce "D:\\source\\project\\myfile.txt" on Windows or
2684 # "/home/you/source/project/myfile.txt" on Linux.
2685
2686 # Typical usage for converting to the build directory for a script.
2687 action("myscript") {
2688 # Don't convert sources, GN will automatically convert these to be relative
2689 # to the build directory when it constructs the command line for your
2690 # script.
2691 sources = [ "foo.txt", "bar.txt" ]
2692
2693 # Extra file args passed manually need to be explicitly converted
2694 # to be relative to the build directory:
2695 args = [
2696 "--data",
2697 rebase_path("//mything/data/input.dat", root_build_dir),
2698 "--rel",
2699 rebase_path("relative_path.txt", root_build_dir)
2700 ] + rebase_path(sources, root_build_dir)
2701 }
2702```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002703### **set_default_toolchain**: Sets the default toolchain name.
Brett Wilson796ed472018-07-16 15:11:09 -07002704
2705```
2706 set_default_toolchain(toolchain_label)
2707
2708 The given label should identify a toolchain definition (see "gn help
2709 toolchain"). This toolchain will be used for all targets unless otherwise
2710 specified.
2711
2712 This function is only valid to call during the processing of the build
2713 configuration file. Since the build configuration file is processed
2714 separately for each toolchain, this function will be a no-op when called
2715 under any non-default toolchains.
2716
2717 For example, the default toolchain should be appropriate for the current
2718 environment. If the current environment is 32-bit and somebody references a
2719 target with a 64-bit toolchain, we wouldn't want processing of the build
2720 config file for the 64-bit toolchain to reset the default toolchain to
2721 64-bit, we want to keep it 32-bits.
2722```
2723
2724#### **Argument**
2725
2726```
2727 toolchain_label
2728 Toolchain name.
2729```
2730
2731#### **Example**
2732
2733```
2734 # Set default toolchain only has an effect when run in the context of the
2735 # default toolchain. Pick the right one according to the current CPU
2736 # architecture.
2737 if (target_cpu == "x64") {
2738 set_default_toolchain("//toolchains:64")
2739 } else if (target_cpu == "x86") {
2740 set_default_toolchain("//toolchains:32")
2741 }
2742```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002743### **set_defaults**: Set default values for a target type.
Brett Wilson796ed472018-07-16 15:11:09 -07002744
2745```
2746 set_defaults() { }
2747
2748 Sets the default values for a given target type. Whenever target_type_name is
2749 seen in the future, the values specified in set_default's block will be
2750 copied into the current scope.
2751
2752 When the target type is used, the variable copying is very strict. If a
2753 variable with that name is already in scope, the build will fail with an
2754 error.
2755
2756 set_defaults can be used for built-in target types ("executable",
2757 "shared_library", etc.) and custom ones defined via the "template" command.
2758 It can be called more than once and the most recent call in any scope will
2759 apply, but there is no way to refer to the previous defaults and modify them
2760 (each call to set_defaults must supply a complete list of all defaults it
2761 wants). If you want to share defaults, store them in a separate variable.
2762```
2763
2764#### **Example**
2765
2766```
2767 set_defaults("static_library") {
2768 configs = [ "//tools/mything:settings" ]
2769 }
2770
Nico Webere49cb722018-08-28 13:10:29 -04002771 static_library("mylib") {
Brett Wilson796ed472018-07-16 15:11:09 -07002772 # The configs will be auto-populated as above. You can remove it if
2773 # you don't want the default for a particular default:
2774 configs -= [ "//tools/mything:settings" ]
2775 }
2776```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002777### **set_sources_assignment_filter**: Set a pattern to filter source files.
Brett Wilson796ed472018-07-16 15:11:09 -07002778
2779```
2780 The sources assignment filter is a list of patterns that remove files from
2781 the list implicitly whenever the "sources" variable is assigned to. This will
2782 do nothing for non-lists.
2783
2784 This is intended to be used to globally filter out files with
2785 platform-specific naming schemes when they don't apply, for example you may
2786 want to filter out all "*_win.cc" files on non-Windows platforms.
2787
2788 Typically this will be called once in the master build config script to set
2789 up the filter for the current platform. Subsequent calls will overwrite the
2790 previous values.
2791
2792 If you want to bypass the filter and add a file even if it might be filtered
2793 out, call set_sources_assignment_filter([]) to clear the list of filters.
2794 This will apply until the current scope exits
2795```
2796
2797#### **How to use patterns**
2798
2799```
2800 File patterns are VERY limited regular expressions. They must match the
2801 entire input string to be counted as a match. In regular expression parlance,
2802 there is an implicit "^...$" surrounding your input. If you want to match a
2803 substring, you need to use wildcards at the beginning and end.
2804
2805 There are only two special tokens understood by the pattern matcher.
2806 Everything else is a literal.
2807
2808 - "*" Matches zero or more of any character. It does not depend on the
2809 preceding character (in regular expression parlance it is equivalent to
2810 ".*").
2811
2812 - "\b" Matches a path boundary. This will match the beginning or end of a
2813 string, or a slash.
2814```
2815
2816#### **Pattern examples**
2817
2818```
2819 "*asdf*"
2820 Matches a string containing "asdf" anywhere.
2821
2822 "asdf"
2823 Matches only the exact string "asdf".
2824
2825 "*.cc"
2826 Matches strings ending in the literal ".cc".
2827
2828 "\bwin/*"
2829 Matches "win/foo" and "foo/win/bar.cc" but not "iwin/foo".
2830```
2831
2832#### **Sources assignment example**
2833
2834```
2835 # Filter out all _win files.
2836 set_sources_assignment_filter([ "*_win.cc", "*_win.h" ])
2837 sources = [ "a.cc", "b_win.cc" ]
2838 print(sources)
2839 # Will print [ "a.cc" ]. b_win one was filtered out.
2840```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002841### **split_list**: Splits a list into N different sub-lists.
Brett Wilson796ed472018-07-16 15:11:09 -07002842
2843```
2844 result = split_list(input, n)
2845
2846 Given a list and a number N, splits the list into N sub-lists of
2847 approximately equal size. The return value is a list of the sub-lists. The
2848 result will always be a list of size N. If N is greater than the number of
2849 elements in the input, it will be padded with empty lists.
2850
2851 The expected use is to divide source files into smaller uniform chunks.
2852```
2853
2854#### **Example**
2855
2856```
2857 The code:
2858 mylist = [1, 2, 3, 4, 5, 6]
2859 print(split_list(mylist, 3))
2860
2861 Will print:
2862 [[1, 2], [3, 4], [5, 6]
2863```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002864### **string_replace**: Replaces substring in the given string.
Petr Hosekc0744ed2018-08-04 16:13:59 -07002865
2866```
2867 result = string_replace(str, old, new[, max])
2868
2869 Returns a copy of the string str in which the occurrences of old have been
2870 replaced with new, optionally restricting the number of replacements. The
2871 replacement is performed sequentially, so if new contains old, it won't be
2872 replaced.
2873```
2874
2875#### **Example**
2876
2877```
2878 The code:
2879 mystr = "Hello, world!"
2880 print(string_replace(mystr, "world", "GN"))
2881
2882 Will print:
2883 Hello, GN!
2884```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08002885### **template**: Define a template rule.
Brett Wilson796ed472018-07-16 15:11:09 -07002886
2887```
2888 A template defines a custom name that acts like a function. It provides a way
2889 to add to the built-in target types.
2890
2891 The template() function is used to declare a template. To invoke the
2892 template, just use the name of the template like any other target type.
2893
2894 Often you will want to declare your template in a special file that other
2895 files will import (see "gn help import") so your template rule can be shared
2896 across build files.
2897```
2898
2899#### **Variables and templates**:
2900
2901```
2902 When you call template() it creates a closure around all variables currently
2903 in scope with the code in the template block. When the template is invoked,
2904 the closure will be executed.
2905
2906 When the template is invoked, the code in the caller is executed and passed
2907 to the template code as an implicit "invoker" variable. The template uses
2908 this to read state out of the invoking code.
2909
2910 One thing explicitly excluded from the closure is the "current directory"
2911 against which relative file names are resolved. The current directory will be
2912 that of the invoking code, since typically that code specifies the file
2913 names. This means all files internal to the template should use absolute
2914 names.
2915
2916 A template will typically forward some or all variables from the invoking
2917 scope to a target that it defines. Often, such variables might be optional.
2918 Use the pattern:
2919
2920 if (defined(invoker.deps)) {
2921 deps = invoker.deps
2922 }
2923
2924 The function forward_variables_from() provides a shortcut to forward one or
2925 more or possibly all variables in this manner:
2926
2927 forward_variables_from(invoker, ["deps", "public_deps"])
2928```
2929
2930#### **Target naming**
2931
2932```
2933 Your template should almost always define a built-in target with the name the
2934 template invoker specified. For example, if you have an IDL template and
2935 somebody does:
2936 idl("foo") {...
2937 you will normally want this to expand to something defining a source_set or
2938 static_library named "foo" (among other things you may need). This way, when
2939 another target specifies a dependency on "foo", the static_library or
2940 source_set will be linked.
2941
2942 It is also important that any other targets your template expands to have
2943 unique names, or you will get collisions.
2944
2945 Access the invoking name in your template via the implicit "target_name"
2946 variable. This should also be the basis for how other targets that a template
2947 expands to ensure uniqueness.
2948
2949 A typical example would be a template that defines an action to generate some
2950 source files, and a source_set to compile that source. Your template would
2951 name the source_set "target_name" because that's what you want external
2952 targets to depend on to link your code. And you would name the action
2953 something like "${target_name}_action" to make it unique. The source set
2954 would have a dependency on the action to make it run.
2955```
2956
2957#### **Overriding builtin targets**
2958
2959```
2960 You can use template to redefine a built-in target in which case your template
2961 takes a precedence over the built-in one. All uses of the target from within
2962 the template definition will refer to the built-in target which makes it
2963 possible to extend the behavior of the built-in target:
2964
2965 template("shared_library") {
2966 shared_library(shlib) {
Julie Hockette2a29402018-07-31 10:11:42 -07002967 forward_variables_from(invoker, "*")
Brett Wilson796ed472018-07-16 15:11:09 -07002968 ...
2969 }
2970 }
2971```
2972
2973#### **Example of defining a template**
2974
2975```
2976 template("my_idl") {
2977 # Be nice and help callers debug problems by checking that the variables
2978 # the template requires are defined. This gives a nice message rather than
2979 # giving the user an error about an undefined variable in the file defining
2980 # the template
2981 #
2982 # You can also use defined() to give default values to variables
2983 # unspecified by the invoker.
2984 assert(defined(invoker.sources),
2985 "Need sources in $target_name listing the idl files.")
2986
2987 # Name of the intermediate target that does the code gen. This must
2988 # incorporate the target name so it's unique across template
2989 # instantiations.
2990 code_gen_target_name = target_name + "_code_gen"
2991
2992 # Intermediate target to convert IDL to C source. Note that the name is
2993 # based on the name the invoker of the template specified. This way, each
2994 # time the template is invoked we get a unique intermediate action name
2995 # (since all target names are in the global scope).
2996 action_foreach(code_gen_target_name) {
2997 # Access the scope defined by the invoker via the implicit "invoker"
2998 # variable.
2999 sources = invoker.sources
3000
3001 # Note that we need an absolute path for our script file name. The
3002 # current directory when executing this code will be that of the invoker
3003 # (this is why we can use the "sources" directly above without having to
3004 # rebase all of the paths). But if we need to reference a script relative
3005 # to the template file, we'll need to use an absolute path instead.
3006 script = "//tools/idl/idl_code_generator.py"
3007
3008 # Tell GN how to expand output names given the sources.
3009 # See "gn help source_expansion" for more.
3010 outputs = [ "$target_gen_dir/{{source_name_part}}.cc",
3011 "$target_gen_dir/{{source_name_part}}.h" ]
3012 }
3013
3014 # Name the source set the same as the template invocation so instancing
3015 # this template produces something that other targets can link to in their
3016 # deps.
3017 source_set(target_name) {
3018 # Generates the list of sources, we get these from the action_foreach
3019 # above.
3020 sources = get_target_outputs(":$code_gen_target_name")
3021
3022 # This target depends on the files produced by the above code gen target.
3023 deps = [ ":$code_gen_target_name" ]
3024 }
3025 }
3026```
3027
3028#### **Example of invoking the resulting template**
3029
3030```
3031 # This calls the template code above, defining target_name to be
3032 # "foo_idl_files" and "invoker" to be the set of stuff defined in the curly
3033 # brackets.
3034 my_idl("foo_idl_files") {
3035 # Goes into the template as "invoker.sources".
3036 sources = [ "foo.idl", "bar.idl" ]
3037 }
3038
3039 # Here is a target that depends on our template.
3040 executable("my_exe") {
3041 # Depend on the name we gave the template call above. Internally, this will
3042 # produce a dependency from executable to the source_set inside the
3043 # template (since it has this name), which will in turn depend on the code
3044 # gen action.
3045 deps = [ ":foo_idl_files" ]
3046 }
3047```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003048### **tool**: Specify arguments to a toolchain tool.
Brett Wilson796ed472018-07-16 15:11:09 -07003049
3050#### **Usage**
3051
3052```
3053 tool() {
3054
3055 }
3056```
3057
3058#### **Tool types**
3059
3060```
3061 Compiler tools:
3062 "cc": C compiler
3063 "cxx": C++ compiler
3064 "objc": Objective C compiler
3065 "objcxx": Objective C++ compiler
3066 "rc": Resource compiler (Windows .rc files)
3067 "asm": Assembler
3068
3069 Linker tools:
3070 "alink": Linker for static libraries (archives)
3071 "solink": Linker for shared libraries
3072 "link": Linker for executables
3073
3074 Other tools:
3075 "stamp": Tool for creating stamp files
3076 "copy": Tool to copy files.
3077 "action": Defaults for actions
3078
3079 Platform specific tools:
3080 "copy_bundle_data": [iOS, macOS] Tool to copy files in a bundle.
3081 "compile_xcassets": [iOS, macOS] Tool to compile asset catalogs.
3082```
3083
3084#### **Tool variables**
3085
3086```
3087 command [string with substitutions]
3088 Valid for: all tools except "action" (required)
3089
3090 The command to run.
3091
3092 default_output_dir [string with substitutions]
3093 Valid for: linker tools
3094
3095 Default directory name for the output file relative to the
3096 root_build_dir. It can contain other substitution patterns. This will
3097 be the default value for the {{output_dir}} expansion (discussed below)
3098 but will be overridden by the "output_dir" variable in a target, if one
3099 is specified.
3100
3101 GN doesn't do anything with this string other than pass it along,
3102 potentially with target-specific overrides. It is the tool's job to use
3103 the expansion so that the files will be in the right place.
3104
3105 default_output_extension [string]
3106 Valid for: linker tools
3107
3108 Extension for the main output of a linkable tool. It includes the
3109 leading dot. This will be the default value for the
3110 {{output_extension}} expansion (discussed below) but will be overridden
3111 by by the "output extension" variable in a target, if one is specified.
3112 Empty string means no extension.
3113
3114 GN doesn't actually do anything with this extension other than pass it
3115 along, potentially with target-specific overrides. One would typically
3116 use the {{output_extension}} value in the "outputs" to read this value.
3117
3118 Example: default_output_extension = ".exe"
3119
3120 depfile [string with substitutions]
3121 Valid for: compiler tools (optional)
3122
3123 If the tool can write ".d" files, this specifies the name of the
3124 resulting file. These files are used to list header file dependencies
3125 (or other implicit input dependencies) that are discovered at build
3126 time. See also "depsformat".
3127
3128 Example: depfile = "{{output}}.d"
3129
3130 depsformat [string]
3131 Valid for: compiler tools (when depfile is specified)
3132
3133 Format for the deps outputs. This is either "gcc" or "msvc". See the
3134 ninja documentation for "deps" for more information.
3135
3136 Example: depsformat = "gcc"
3137
3138 description [string with substitutions, optional]
3139 Valid for: all tools
3140
3141 What to print when the command is run.
3142
3143 Example: description = "Compiling {{source}}"
3144
3145 lib_switch [string, optional, link tools only]
3146 lib_dir_switch [string, optional, link tools only]
3147 Valid for: Linker tools except "alink"
3148
3149 These strings will be prepended to the libraries and library search
3150 directories, respectively, because linkers differ on how specify them.
3151 If you specified:
3152 lib_switch = "-l"
3153 lib_dir_switch = "-L"
3154 then the "{{libs}}" expansion for [ "freetype", "expat"] would be
3155 "-lfreetype -lexpat".
3156
3157 outputs [list of strings with substitutions]
3158 Valid for: Linker and compiler tools (required)
3159
3160 An array of names for the output files the tool produces. These are
3161 relative to the build output directory. There must always be at least
3162 one output file. There can be more than one output (a linker might
3163 produce a library and an import library, for example).
3164
3165 This array just declares to GN what files the tool will produce. It is
3166 your responsibility to specify the tool command that actually produces
3167 these files.
3168
3169 If you specify more than one output for shared library links, you
3170 should consider setting link_output, depend_output, and
3171 runtime_outputs.
3172
3173 Example for a compiler tool that produces .obj files:
3174 outputs = [
3175 "{{source_out_dir}}/{{source_name_part}}.obj"
3176 ]
3177
3178 Example for a linker tool that produces a .dll and a .lib. The use of
3179 {{target_output_name}}, {{output_extension}} and {{output_dir}} allows
3180 the target to override these values.
3181 outputs = [
3182 "{{output_dir}}/{{target_output_name}}"
3183 "{{output_extension}}",
3184 "{{output_dir}}/{{target_output_name}}.lib",
3185 ]
3186
3187 pool [label, optional]
3188 Valid for: all tools (optional)
3189
3190 Label of the pool to use for the tool. Pools are used to limit the
3191 number of tasks that can execute concurrently during the build.
3192
3193 See also "gn help pool".
3194
3195 link_output [string with substitutions]
3196 depend_output [string with substitutions]
3197 Valid for: "solink" only (optional)
3198
3199 These two files specify which of the outputs from the solink tool
3200 should be used for linking and dependency tracking. These should match
3201 entries in the "outputs". If unspecified, the first item in the
3202 "outputs" array will be used for all. See "Separate linking and
3203 dependencies for shared libraries" below for more.
3204
3205 On Windows, where the tools produce a .dll shared library and a .lib
3206 import library, you will want the first two to be the import library
3207 and the third one to be the .dll file. On Linux, if you're not doing
3208 the separate linking/dependency optimization, all of these should be
3209 the .so output.
3210
3211 output_prefix [string]
3212 Valid for: Linker tools (optional)
3213
3214 Prefix to use for the output name. Defaults to empty. This prefix will
3215 be prepended to the name of the target (or the output_name if one is
3216 manually specified for it) if the prefix is not already there. The
3217 result will show up in the {{output_name}} substitution pattern.
3218
3219 Individual targets can opt-out of the output prefix by setting:
3220 output_prefix_override = true
3221 (see "gn help output_prefix_override").
3222
3223 This is typically used to prepend "lib" to libraries on
3224 Posix systems:
3225 output_prefix = "lib"
3226
3227 precompiled_header_type [string]
3228 Valid for: "cc", "cxx", "objc", "objcxx"
3229
3230 Type of precompiled headers. If undefined or the empty string,
3231 precompiled headers will not be used for this tool. Otherwise use "gcc"
3232 or "msvc".
3233
3234 For precompiled headers to be used for a given target, the target (or a
3235 config applied to it) must also specify a "precompiled_header" and, for
3236 "msvc"-style headers, a "precompiled_source" value. If the type is
3237 "gcc", then both "precompiled_header" and "precompiled_source" must
3238 resolve to the same file, despite the different formats required for
3239 each."
3240
3241 See "gn help precompiled_header" for more.
3242
3243 restat [boolean]
3244 Valid for: all tools (optional, defaults to false)
3245
3246 Requests that Ninja check the file timestamp after this tool has run to
3247 determine if anything changed. Set this if your tool has the ability to
3248 skip writing output if the output file has not changed.
3249
3250 Normally, Ninja will assume that when a tool runs the output be new and
3251 downstream dependents must be rebuild. When this is set to trye, Ninja
3252 can skip rebuilding downstream dependents for input changes that don't
3253 actually affect the output.
3254
3255 Example:
3256 restat = true
3257
3258 rspfile [string with substitutions]
3259 Valid for: all tools except "action" (optional)
3260
3261 Name of the response file. If empty, no response file will be
3262 used. See "rspfile_content".
3263
3264 rspfile_content [string with substitutions]
3265 Valid for: all tools except "action" (required when "rspfile" is used)
3266
3267 The contents to be written to the response file. This may include all
3268 or part of the command to send to the tool which allows you to get
3269 around OS command-line length limits.
3270
3271 This example adds the inputs and libraries to a response file, but
3272 passes the linker flags directly on the command line:
3273 tool("link") {
3274 command = "link -o {{output}} {{ldflags}} @{{output}}.rsp"
3275 rspfile = "{{output}}.rsp"
3276 rspfile_content = "{{inputs}} {{solibs}} {{libs}}"
3277 }
3278
3279 runtime_outputs [string list with substitutions]
3280 Valid for: linker tools
3281
3282 If specified, this list is the subset of the outputs that should be
3283 added to runtime deps (see "gn help runtime_deps"). By default (if
3284 runtime_outputs is empty or unspecified), it will be the link_output.
3285```
3286
3287#### **Expansions for tool variables**
3288
3289```
3290 All paths are relative to the root build directory, which is the current
3291 directory for running all tools. These expansions are available to all tools:
3292
3293 {{label}}
3294 The label of the current target. This is typically used in the
3295 "description" field for link tools. The toolchain will be omitted from
3296 the label for targets in the default toolchain, and will be included
3297 for targets in other toolchains.
3298
3299 {{label_name}}
3300 The short name of the label of the target. This is the part after the
3301 colon. For "//foo/bar:baz" this will be "baz". Unlike
3302 {{target_output_name}}, this is not affected by the "output_prefix" in
3303 the tool or the "output_name" set on the target.
3304
3305 {{output}}
3306 The relative path and name of the output(s) of the current build step.
3307 If there is more than one output, this will expand to a list of all of
3308 them. Example: "out/base/my_file.o"
3309
3310 {{target_gen_dir}}
3311 {{target_out_dir}}
3312 The directory of the generated file and output directories,
3313 respectively, for the current target. There is no trailing slash. See
3314 also {{output_dir}} for linker tools. Example: "out/base/test"
3315
3316 {{target_output_name}}
3317 The short name of the current target with no path information, or the
3318 value of the "output_name" variable if one is specified in the target.
3319 This will include the "output_prefix" if any. See also {{label_name}}.
3320
3321 Example: "libfoo" for the target named "foo" and an output prefix for
3322 the linker tool of "lib".
3323
3324 Compiler tools have the notion of a single input and a single output, along
3325 with a set of compiler-specific flags. The following expansions are
3326 available:
3327
3328 {{asmflags}}
3329 {{cflags}}
3330 {{cflags_c}}
3331 {{cflags_cc}}
3332 {{cflags_objc}}
3333 {{cflags_objcc}}
3334 {{defines}}
3335 {{include_dirs}}
3336 Strings correspond that to the processed flags/defines/include
3337 directories specified for the target.
3338 Example: "--enable-foo --enable-bar"
3339
3340 Defines will be prefixed by "-D" and include directories will be
3341 prefixed by "-I" (these work with Posix tools as well as Microsoft
3342 ones).
3343
3344 {{source}}
3345 The relative path and name of the current input file.
3346 Example: "../../base/my_file.cc"
3347
3348 {{source_file_part}}
3349 The file part of the source including the extension (with no directory
3350 information).
3351 Example: "foo.cc"
3352
3353 {{source_name_part}}
3354 The filename part of the source file with no directory or extension.
3355 Example: "foo"
3356
3357 {{source_gen_dir}}
3358 {{source_out_dir}}
3359 The directory in the generated file and output directories,
3360 respectively, for the current input file. If the source file is in the
3361 same directory as the target is declared in, they will will be the same
3362 as the "target" versions above. Example: "gen/base/test"
3363
Julie Hockette2a29402018-07-31 10:11:42 -07003364 Linker tools have multiple inputs and (potentially) multiple outputs. The
Brett Wilson796ed472018-07-16 15:11:09 -07003365 static library tool ("alink") is not considered a linker tool. The following
3366 expansions are available:
3367
3368 {{inputs}}
3369 {{inputs_newline}}
3370 Expands to the inputs to the link step. This will be a list of object
3371 files and static libraries.
3372 Example: "obj/foo.o obj/bar.o obj/somelibrary.a"
3373
3374 The "_newline" version will separate the input files with newlines
3375 instead of spaces. This is useful in response files: some linkers can
3376 take a "-filelist" flag which expects newline separated files, and some
3377 Microsoft tools have a fixed-sized buffer for parsing each line of a
3378 response file.
3379
3380 {{ldflags}}
3381 Expands to the processed set of ldflags and library search paths
3382 specified for the target.
3383 Example: "-m64 -fPIC -pthread -L/usr/local/mylib"
3384
3385 {{libs}}
3386 Expands to the list of system libraries to link to. Each will be
3387 prefixed by the "lib_switch".
3388
3389 As a special case to support Mac, libraries with names ending in
3390 ".framework" will be added to the {{libs}} with "-framework" preceding
3391 it, and the lib prefix will be ignored.
3392
3393 Example: "-lfoo -lbar"
3394
3395 {{output_dir}}
3396 The value of the "output_dir" variable in the target, or the the value
3397 of the "default_output_dir" value in the tool if the target does not
3398 override the output directory. This will be relative to the
3399 root_build_dir and will not end in a slash. Will be "." for output to
3400 the root_build_dir.
3401
3402 This is subtly different than {{target_out_dir}} which is defined by GN
3403 based on the target's path and not overridable. {{output_dir}} is for
3404 the final output, {{target_out_dir}} is generally for object files and
3405 other outputs.
3406
3407 Usually {{output_dir}} would be defined in terms of either
3408 {{target_out_dir}} or {{root_out_dir}}
3409
3410 {{output_extension}}
3411 The value of the "output_extension" variable in the target, or the
3412 value of the "default_output_extension" value in the tool if the target
3413 does not specify an output extension.
3414 Example: ".so"
3415
3416 {{solibs}}
3417 Extra libraries from shared library dependencies not specified in the
3418 {{inputs}}. This is the list of link_output files from shared libraries
3419 (if the solink tool specifies a "link_output" variable separate from
3420 the "depend_output").
3421
3422 These should generally be treated the same as libs by your tool.
3423
3424 Example: "libfoo.so libbar.so"
3425
3426 The static library ("alink") tool allows {{arflags}} plus the common tool
3427 substitutions.
3428
3429 The copy tool allows the common compiler/linker substitutions, plus
3430 {{source}} which is the source of the copy. The stamp tool allows only the
3431 common tool substitutions.
3432
3433 The copy_bundle_data and compile_xcassets tools only allows the common tool
3434 substitutions. Both tools are required to create iOS/macOS bundles and need
3435 only be defined on those platforms.
3436
3437 The copy_bundle_data tool will be called with one source and needs to copy
3438 (optionally optimizing the data representation) to its output. It may be
3439 called with a directory as input and it needs to be recursively copied.
3440
3441 The compile_xcassets tool will be called with one or more source (each an
3442 asset catalog) that needs to be compiled to a single output. The following
3443 substitutions are available:
3444
3445 {{inputs}}
3446 Expands to the list of .xcassets to use as input to compile the asset
3447 catalog.
3448
3449 {{bundle_product_type}}
3450 Expands to the product_type of the bundle that will contain the
3451 compiled asset catalog. Usually corresponds to the product_type
3452 property of the corresponding create_bundle target.
3453
3454 {{bundle_partial_info_plist}}
3455 Expands to the path to the partial Info.plist generated by the
3456 assets catalog compiler. Usually based on the target_name of
3457 the create_bundle target.
3458```
3459
3460#### **Separate linking and dependencies for shared libraries**
3461
3462```
3463 Shared libraries are special in that not all changes to them require that
3464 dependent targets be re-linked. If the shared library is changed but no
3465 imports or exports are different, dependent code needn't be relinked, which
3466 can speed up the build.
3467
3468 If your link step can output a list of exports from a shared library and
3469 writes the file only if the new one is different, the timestamp of this file
3470 can be used for triggering re-links, while the actual shared library would be
3471 used for linking.
3472
3473 You will need to specify
3474 restat = true
3475 in the linker tool to make this work, so Ninja will detect if the timestamp
3476 of the dependency file has changed after linking (otherwise it will always
3477 assume that running a command updates the output):
3478
3479 tool("solink") {
3480 command = "..."
3481 outputs = [
3482 "{{output_dir}}/{{target_output_name}}{{output_extension}}",
3483 "{{output_dir}}/{{target_output_name}}"
3484 "{{output_extension}}.TOC",
3485 ]
3486 link_output =
3487 "{{output_dir}}/{{target_output_name}}{{output_extension}}"
3488 depend_output =
3489 "{{output_dir}}/{{target_output_name}}"
3490 "{{output_extension}}.TOC"
3491 restat = true
3492 }
3493```
3494
3495#### **Example**
3496
3497```
3498 toolchain("my_toolchain") {
3499 # Put these at the top to apply to all tools below.
3500 lib_switch = "-l"
3501 lib_dir_switch = "-L"
3502
3503 tool("cc") {
3504 command = "gcc {{source}} -o {{output}}"
3505 outputs = [ "{{source_out_dir}}/{{source_name_part}}.o" ]
3506 description = "GCC {{source}}"
3507 }
3508 tool("cxx") {
3509 command = "g++ {{source}} -o {{output}}"
3510 outputs = [ "{{source_out_dir}}/{{source_name_part}}.o" ]
3511 description = "G++ {{source}}"
3512 }
3513 };
3514```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003515### **toolchain**: Defines a toolchain.
Brett Wilson796ed472018-07-16 15:11:09 -07003516
3517```
3518 A toolchain is a set of commands and build flags used to compile the source
3519 code. The toolchain() function defines these commands.
3520```
3521
3522#### **Toolchain overview**
3523
3524```
3525 You can have more than one toolchain in use at once in a build and a target
3526 can exist simultaneously in multiple toolchains. A build file is executed
3527 once for each toolchain it is referenced in so the GN code can vary all
3528 parameters of each target (or which targets exist) on a per-toolchain basis.
3529
3530 When you have a simple build with only one toolchain, the build config file
3531 is loaded only once at the beginning of the build. It must call
3532 set_default_toolchain() (see "gn help set_default_toolchain") to tell GN the
3533 label of the toolchain definition to use. The "toolchain_args" section of the
3534 toolchain definition is ignored.
3535
3536 When a target has a dependency on a target using different toolchain (see "gn
3537 help labels" for how to specify this), GN will start a build using that
3538 secondary toolchain to resolve the target. GN will load the build config file
3539 with the build arguments overridden as specified in the toolchain_args.
3540 Because the default toolchain is already known, calls to
3541 set_default_toolchain() are ignored.
3542
3543 To load a file in an alternate toolchain, GN does the following:
3544
3545 1. Loads the file with the toolchain definition in it (as determined by the
3546 toolchain label).
3547 2. Re-runs the master build configuration file, applying the arguments
3548 specified by the toolchain_args section of the toolchain definition.
3549 3. Loads the destination build file in the context of the configuration file
3550 in the previous step.
3551
3552 The toolchain configuration is two-way. In the default toolchain (i.e. the
3553 main build target) the configuration flows from the build config file to the
3554 toolchain. The build config file looks at the state of the build (OS type,
3555 CPU architecture, etc.) and decides which toolchain to use (via
3556 set_default_toolchain()). In secondary toolchains, the configuration flows
3557 from the toolchain to the build config file: the "toolchain_args" in the
3558 toolchain definition specifies the arguments to re-invoke the build.
3559```
3560
3561#### **Functions and variables**
3562
3563```
3564 tool()
Julie Hockette2a29402018-07-31 10:11:42 -07003565 The tool() function call specifies the commands to run for a given step. See
3566 "gn help tool".
Brett Wilson796ed472018-07-16 15:11:09 -07003567
Julie Hockette2a29402018-07-31 10:11:42 -07003568 toolchain_args [scope]
Brett Wilson796ed472018-07-16 15:11:09 -07003569 Overrides for build arguments to pass to the toolchain when invoking it.
3570 This is a variable of type "scope" where the variable names correspond to
3571 variables in declare_args() blocks.
3572
3573 When you specify a target using an alternate toolchain, the master build
3574 configuration file is re-interpreted in the context of that toolchain.
3575 toolchain_args allows you to control the arguments passed into this
3576 alternate invocation of the build.
3577
3578 Any default system arguments or arguments passed in via "gn args" will also
3579 be passed to the alternate invocation unless explicitly overridden by
3580 toolchain_args.
3581
3582 The toolchain_args will be ignored when the toolchain being defined is the
3583 default. In this case, it's expected you want the default argument values.
3584
3585 See also "gn help buildargs" for an overview of these arguments.
3586
Julie Hockette2a29402018-07-31 10:11:42 -07003587 propagates_configs [boolean, default=false]
3588 Determines whether public_configs and all_dependent_configs in this
3589 toolchain propagate to targets in other toolchains.
3590
3591 When false (the default), this toolchain will not propagate any configs to
3592 targets in other toolchains that depend on it targets inside this
3593 toolchain. This matches the most common usage of toolchains where they
3594 represent different architectures or compilers and the settings that apply
3595 to one won't necessarily apply to others.
3596
3597 When true, configs (public and all-dependent) will cross the boundary out
3598 of this toolchain as if the toolchain boundary wasn't there. This only
3599 affects one direction of dependencies: a toolchain can't control whether
3600 it accepts such configs, only whether it pushes them. The build is
3601 responsible for ensuring that any external targets depending on targets in
3602 this toolchain are compatible with the compiler flags, etc. that may be
3603 propagated.
3604
3605 deps [string list]
Brett Wilson796ed472018-07-16 15:11:09 -07003606 Dependencies of this toolchain. These dependencies will be resolved before
3607 any target in the toolchain is compiled. To avoid circular dependencies
3608 these must be targets defined in another toolchain.
3609
3610 This is expressed as a list of targets, and generally these targets will
3611 always specify a toolchain:
3612 deps = [ "//foo/bar:baz(//build/toolchain:bootstrap)" ]
3613
3614 This concept is somewhat inefficient to express in Ninja (it requires a lot
3615 of duplicate of rules) so should only be used when absolutely necessary.
3616```
3617
3618#### **Example of defining a toolchain**
3619
3620```
3621 toolchain("32") {
3622 tool("cc") {
3623 command = "gcc {{source}}"
3624 ...
3625 }
3626
3627 toolchain_args = {
3628 use_doom_melon = true # Doom melon always required for 32-bit builds.
3629 current_cpu = "x86"
3630 }
3631 }
3632
3633 toolchain("64") {
3634 tool("cc") {
3635 command = "gcc {{source}}"
3636 ...
3637 }
3638
3639 toolchain_args = {
3640 # use_doom_melon is not overridden here, it will take the default.
3641 current_cpu = "x64"
3642 }
3643 }
3644```
3645
3646#### **Example of cross-toolchain dependencies**
3647
3648```
3649 If a 64-bit target wants to depend on a 32-bit binary, it would specify a
3650 dependency using data_deps (data deps are like deps that are only needed at
3651 runtime and aren't linked, since you can't link a 32-bit and a 64-bit
3652 library).
3653
3654 executable("my_program") {
3655 ...
3656 if (target_cpu == "x64") {
3657 # The 64-bit build needs this 32-bit helper.
3658 data_deps = [ ":helper(//toolchains:32)" ]
3659 }
3660 }
3661
3662 if (target_cpu == "x86") {
3663 # Our helper library is only compiled in 32-bits.
3664 shared_library("helper") {
3665 ...
3666 }
3667 }
3668```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003669### **write_file**: Write a file to disk.
Brett Wilson796ed472018-07-16 15:11:09 -07003670
3671```
Julie Hockett09171292018-07-31 14:35:10 -07003672 write_file(filename, data, output_conversion = "")
Brett Wilson796ed472018-07-16 15:11:09 -07003673
3674 If data is a list, the list will be written one-item-per-line with no quoting
3675 or brackets.
3676
3677 If the file exists and the contents are identical to that being written, the
3678 file will not be updated. This will prevent unnecessary rebuilds of targets
3679 that depend on this file.
3680
3681 One use for write_file is to write a list of inputs to an script that might
3682 be too long for the command line. However, it is preferable to use response
3683 files for this purpose. See "gn help response_file_contents".
Brett Wilson796ed472018-07-16 15:11:09 -07003684```
3685
3686#### **Arguments**
3687
3688```
3689 filename
3690 Filename to write. This must be within the output directory.
3691
3692 data
3693 The list or string to write.
Julie Hockett09171292018-07-31 14:35:10 -07003694
3695 output_conversion
Julie Hockett81ee1962019-05-13 11:24:42 -07003696 Controls how the output is written. See "gn help io_conversion".
Brett Wilson796ed472018-07-16 15:11:09 -07003697```
3698## Built-in predefined variables
3699
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003700### **current_cpu**: The processor architecture of the current toolchain.
Brett Wilson796ed472018-07-16 15:11:09 -07003701
3702```
3703 The build configuration usually sets this value based on the value of
3704 "host_cpu" (see "gn help host_cpu") and then threads this through the
3705 toolchain definitions to ensure that it always reflects the appropriate
3706 value.
3707
Julie Hockette2a29402018-07-31 10:11:42 -07003708 This value is not used internally by GN for any purpose. It is set to the
Brett Wilson796ed472018-07-16 15:11:09 -07003709 empty string ("") by default but is declared so that it can be overridden on
3710 the command line if so desired.
3711
3712 See "gn help target_cpu" for a list of common values returned.
3713```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003714### **current_os**: The operating system of the current toolchain.
Brett Wilson796ed472018-07-16 15:11:09 -07003715
3716```
3717 The build configuration usually sets this value based on the value of
3718 "target_os" (see "gn help target_os"), and then threads this through the
3719 toolchain definitions to ensure that it always reflects the appropriate
3720 value.
3721
Julie Hockette2a29402018-07-31 10:11:42 -07003722 This value is not used internally by GN for any purpose. It is set to the
Brett Wilson796ed472018-07-16 15:11:09 -07003723 empty string ("") by default but is declared so that it can be overridden on
3724 the command line if so desired.
3725
3726 See "gn help target_os" for a list of common values returned.
3727```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003728### **current_toolchain**: Label of the current toolchain.
Brett Wilson796ed472018-07-16 15:11:09 -07003729
3730```
3731 A fully-qualified label representing the current toolchain. You can use this
3732 to make toolchain-related decisions in the build. See also
3733 "default_toolchain".
3734```
3735
3736#### **Example**
3737
3738```
3739 if (current_toolchain == "//build:64_bit_toolchain") {
3740 executable("output_thats_64_bit_only") {
3741 ...
3742```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003743### **default_toolchain**: [string] Label of the default toolchain.
Brett Wilson796ed472018-07-16 15:11:09 -07003744
3745```
3746 A fully-qualified label representing the default toolchain, which may not
3747 necessarily be the current one (see "current_toolchain").
3748```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003749### **host_cpu**: The processor architecture that GN is running on.
Brett Wilson796ed472018-07-16 15:11:09 -07003750
3751```
3752 This is value is exposed so that cross-compile toolchains can access the host
3753 architecture when needed.
3754
3755 The value should generally be considered read-only, but it can be overriden
3756 in order to handle unusual cases where there might be multiple plausible
3757 values for the host architecture (e.g., if you can do either 32-bit or 64-bit
3758 builds). The value is not used internally by GN for any purpose.
3759```
3760
3761#### **Some possible values**
3762
3763```
3764 - "x64"
3765 - "x86"
3766```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003767### **host_os**: [string] The operating system that GN is running on.
Brett Wilson796ed472018-07-16 15:11:09 -07003768
3769```
3770 This value is exposed so that cross-compiles can access the host build
3771 system's settings.
3772
3773 This value should generally be treated as read-only. It, however, is not used
3774 internally by GN for any purpose.
3775```
3776
3777#### **Some possible values**
3778
3779```
3780 - "linux"
3781 - "mac"
3782 - "win"
3783```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003784### **invoker**: [string] The invoking scope inside a template.
Brett Wilson796ed472018-07-16 15:11:09 -07003785
3786```
3787 Inside a template invocation, this variable refers to the scope of the
3788 invoker of the template. Outside of template invocations, this variable is
3789 undefined.
3790
3791 All of the variables defined inside the template invocation are accessible as
3792 members of the "invoker" scope. This is the way that templates read values
3793 set by the callers.
3794
3795 This is often used with "defined" to see if a value is set on the invoking
3796 scope.
3797
3798 See "gn help template" for more examples.
3799```
3800
3801#### **Example**
3802
3803```
3804 template("my_template") {
3805 print(invoker.sources) # Prints [ "a.cc", "b.cc" ]
3806 print(defined(invoker.foo)) # Prints false.
3807 print(defined(invoker.bar)) # Prints true.
3808 }
3809
3810 my_template("doom_melon") {
3811 sources = [ "a.cc", "b.cc" ]
3812 bar = 123
3813 }
3814```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003815### **python_path**: Absolute path of Python.
Brett Wilson796ed472018-07-16 15:11:09 -07003816
3817```
3818 Normally used in toolchain definitions if running some command requires
3819 Python. You will normally not need this when invoking scripts since GN
3820 automatically finds it for you.
3821```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003822### **root_build_dir**: [string] Directory where build commands are run.
Brett Wilson796ed472018-07-16 15:11:09 -07003823
3824```
3825 This is the root build output directory which will be the current directory
3826 when executing all compilers and scripts.
3827
3828 Most often this is used with rebase_path (see "gn help rebase_path") to
3829 convert arguments to be relative to a script's current directory.
3830```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003831### **root_gen_dir**: Directory for the toolchain's generated files.
Brett Wilson796ed472018-07-16 15:11:09 -07003832
3833```
3834 Absolute path to the root of the generated output directory tree for the
3835 current toolchain. An example would be "//out/Debug/gen" for the default
3836 toolchain, or "//out/Debug/arm/gen" for the "arm" toolchain.
3837
3838 This is primarily useful for setting up include paths for generated files. If
3839 you are passing this to a script, you will want to pass it through
3840 rebase_path() (see "gn help rebase_path") to convert it to be relative to the
3841 build directory.
3842
3843 See also "target_gen_dir" which is usually a better location for generated
3844 files. It will be inside the root generated dir.
3845```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003846### **root_out_dir**: [string] Root directory for toolchain output files.
Brett Wilson796ed472018-07-16 15:11:09 -07003847
3848```
3849 Absolute path to the root of the output directory tree for the current
3850 toolchain. It will not have a trailing slash.
3851
3852 For the default toolchain this will be the same as the root_build_dir. An
3853 example would be "//out/Debug" for the default toolchain, or
3854 "//out/Debug/arm" for the "arm" toolchain.
3855
3856 This is primarily useful for setting up script calls. If you are passing this
3857 to a script, you will want to pass it through rebase_path() (see "gn help
3858 rebase_path") to convert it to be relative to the build directory.
3859
3860 See also "target_out_dir" which is usually a better location for output
3861 files. It will be inside the root output dir.
3862```
3863
3864#### **Example**
3865
3866```
3867 action("myscript") {
3868 # Pass the output dir to the script.
3869 args = [ "-o", rebase_path(root_out_dir, root_build_dir) ]
3870 }
3871```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003872### **target_cpu**: The desired cpu architecture for the build.
Brett Wilson796ed472018-07-16 15:11:09 -07003873
3874```
3875 This value should be used to indicate the desired architecture for the
3876 primary objects of the build. It will match the cpu architecture of the
3877 default toolchain, but not necessarily the current toolchain.
3878
3879 In many cases, this is the same as "host_cpu", but in the case of
3880 cross-compiles, this can be set to something different. This value is
3881 different from "current_cpu" in that it does not change based on the current
3882 toolchain. When writing rules, "current_cpu" should be used rather than
3883 "target_cpu" most of the time.
3884
3885 This value is not used internally by GN for any purpose, so it may be set to
3886 whatever value is needed for the build. GN defaults this value to the empty
3887 string ("") and the configuration files should set it to an appropriate value
3888 (e.g., setting it to the value of "host_cpu") if it is not overridden on the
3889 command line or in the args.gn file.
3890```
3891
3892#### **Possible values**
3893
3894```
3895 - "x86"
3896 - "x64"
3897 - "arm"
3898 - "arm64"
3899 - "mipsel"
3900```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003901### **target_gen_dir**: Directory for a target's generated files.
Brett Wilson796ed472018-07-16 15:11:09 -07003902
3903```
3904 Absolute path to the target's generated file directory. This will be the
3905 "root_gen_dir" followed by the relative path to the current build file. If
3906 your file is in "//tools/doom_melon" then target_gen_dir would be
3907 "//out/Debug/gen/tools/doom_melon". It will not have a trailing slash.
3908
3909 This is primarily useful for setting up include paths for generated files. If
3910 you are passing this to a script, you will want to pass it through
3911 rebase_path() (see "gn help rebase_path") to convert it to be relative to the
3912 build directory.
3913
3914 See also "gn help root_gen_dir".
3915```
3916
3917#### **Example**
3918
3919```
3920 action("myscript") {
3921 # Pass the generated output dir to the script.
3922 args = [ "-o", rebase_path(target_gen_dir, root_build_dir) ]"
3923 }
3924```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003925### **target_name**: [string] The name of the current target.
Brett Wilson796ed472018-07-16 15:11:09 -07003926
3927```
3928 Inside a target or template invocation, this variable refers to the name
3929 given to the target or template invocation. Outside of these, this variable
3930 is undefined.
3931
3932 This is most often used in template definitions to name targets defined in
3933 the template based on the name of the invocation. This is necessary both to
3934 ensure generated targets have unique names and to generate a target with the
3935 exact name of the invocation that other targets can depend on.
3936
3937 Be aware that this value will always reflect the innermost scope. So when
3938 defining a target inside a template, target_name will refer to the target
3939 rather than the template invocation. To get the name of the template
3940 invocation in this case, you should save target_name to a temporary variable
3941 outside of any target definitions.
3942
3943 See "gn help template" for more examples.
3944```
3945
3946#### **Example**
3947
3948```
3949 executable("doom_melon") {
3950 print(target_name) # Prints "doom_melon".
3951 }
3952
3953 template("my_template") {
3954 print(target_name) # Prints "space_ray" when invoked below.
3955
3956 executable(target_name + "_impl") {
3957 print(target_name) # Prints "space_ray_impl".
3958 }
3959 }
3960
3961 my_template("space_ray") {
3962 }
3963```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08003964### **target_os**: The desired operating system for the build.
Brett Wilson796ed472018-07-16 15:11:09 -07003965
3966```
3967 This value should be used to indicate the desired operating system for the
3968 primary object(s) of the build. It will match the OS of the default
3969 toolchain.
3970
3971 In many cases, this is the same as "host_os", but in the case of
3972 cross-compiles, it may be different. This variable differs from "current_os"
3973 in that it can be referenced from inside any toolchain and will always return
3974 the initial value.
3975
3976 This should be set to the most specific value possible. So, "android" or
3977 "chromeos" should be used instead of "linux" where applicable, even though
3978 Android and ChromeOS are both Linux variants. This can mean that one needs to
3979 write
3980
3981 if (target_os == "android" || target_os == "linux") {
3982 # ...
3983 }
3984
3985 and so forth.
3986
3987 This value is not used internally by GN for any purpose, so it may be set to
3988 whatever value is needed for the build. GN defaults this value to the empty
3989 string ("") and the configuration files should set it to an appropriate value
3990 (e.g., setting it to the value of "host_os") if it is not set via the command
3991 line or in the args.gn file.
3992```
3993
3994#### **Possible values**
3995
3996```
3997 - "android"
3998 - "chromeos"
3999 - "ios"
4000 - "linux"
4001 - "nacl"
4002 - "mac"
4003 - "win"
4004```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004005### **target_out_dir**: [string] Directory for target output files.
Brett Wilson796ed472018-07-16 15:11:09 -07004006
4007```
4008 Absolute path to the target's generated file directory. If your current
4009 target is in "//tools/doom_melon" then this value might be
4010 "//out/Debug/obj/tools/doom_melon". It will not have a trailing slash.
4011
4012 This is primarily useful for setting up arguments for calling scripts. If you
4013 are passing this to a script, you will want to pass it through rebase_path()
4014 (see "gn help rebase_path") to convert it to be relative to the build
4015 directory.
4016
4017 See also "gn help root_out_dir".
4018```
4019
4020#### **Example**
4021
4022```
4023 action("myscript") {
4024 # Pass the output dir to the script.
4025 args = [ "-o", rebase_path(target_out_dir, root_build_dir) ]"
Brett Wilson796ed472018-07-16 15:11:09 -07004026 }
4027```
4028## Variables you set in targets
4029
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004030### **all_dependent_configs**: Configs to be forced on dependents.
Brett Wilson796ed472018-07-16 15:11:09 -07004031
4032```
4033 A list of config labels.
4034
4035 All targets depending on this one, and recursively, all targets depending on
4036 those, will have the configs listed in this variable added to them. These
4037 configs will also apply to the current target.
4038
4039 This addition happens in a second phase once a target and all of its
4040 dependencies have been resolved. Therefore, a target will not see these
4041 force-added configs in their "configs" variable while the script is running,
4042 and they can not be removed. As a result, this capability should generally
4043 only be used to add defines and include directories necessary to compile a
4044 target's headers.
4045
4046 See also "public_configs".
4047```
4048
4049#### **Ordering of flags and values**
4050
4051```
4052 1. Those set on the current target (not in a config).
4053 2. Those set on the "configs" on the target in order that the
4054 configs appear in the list.
4055 3. Those set on the "all_dependent_configs" on the target in order
4056 that the configs appear in the list.
4057 4. Those set on the "public_configs" on the target in order that
4058 those configs appear in the list.
4059 5. all_dependent_configs pulled from dependencies, in the order of
4060 the "deps" list. This is done recursively. If a config appears
4061 more than once, only the first occurence will be used.
4062 6. public_configs pulled from dependencies, in the order of the
4063 "deps" list. If a dependency is public, they will be applied
4064 recursively.
4065```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004066### **allow_circular_includes_from**: Permit includes from deps.
Brett Wilson796ed472018-07-16 15:11:09 -07004067
4068```
4069 A list of target labels. Must be a subset of the target's "deps". These
4070 targets will be permitted to include headers from the current target despite
4071 the dependency going in the opposite direction.
4072
4073 When you use this, both targets must be included in a final binary for it to
4074 link. To keep linker errors from happening, it is good practice to have all
4075 external dependencies depend only on one of the two targets, and to set the
4076 visibility on the other to enforce this. Thus the targets will always be
4077 linked together in any output.
4078```
4079
4080#### **Details**
4081
4082```
4083 Normally, for a file in target A to include a file from target B, A must list
4084 B as a dependency. This invariant is enforced by the "gn check" command (and
4085 the --check flag to "gn gen" -- see "gn help check").
4086
4087 Sometimes, two targets might be the same unit for linking purposes (two
4088 source sets or static libraries that would always be linked together in a
4089 final executable or shared library) and they each include headers from the
4090 other: you want A to be able to include B's headers, and B to include A's
4091 headers. This is not an ideal situation but is sometimes unavoidable.
4092
4093 This list, if specified, lists which of the dependencies of the current
4094 target can include header files from the current target. That is, if A
4095 depends on B, B can only include headers from A if it is in A's
4096 allow_circular_includes_from list. Normally includes must follow the
4097 direction of dependencies, this flag allows them to go in the opposite
4098 direction.
4099```
4100
4101#### **Danger**
4102
4103```
4104 In the above example, A's headers are likely to include headers from A's
4105 dependencies. Those dependencies may have public_configs that apply flags,
4106 defines, and include paths that make those headers work properly.
4107
4108 With allow_circular_includes_from, B can include A's headers, and
4109 transitively from A's dependencies, without having the dependencies that
4110 would bring in the public_configs those headers need. The result may be
4111 errors or inconsistent builds.
4112
4113 So when you use allow_circular_includes_from, make sure that any compiler
4114 settings, flags, and include directories are the same between both targets
4115 (consider putting such things in a shared config they can both reference).
4116 Make sure the dependencies are also the same (you might consider a group to
4117 collect such dependencies they both depend on).
4118```
4119
4120#### **Example**
4121
4122```
4123 source_set("a") {
4124 deps = [ ":b", ":a_b_shared_deps" ]
4125 allow_circular_includes_from = [ ":b" ]
4126 ...
4127 }
4128
4129 source_set("b") {
4130 deps = [ ":a_b_shared_deps" ]
4131 # Sources here can include headers from a despite lack of deps.
4132 ...
4133 }
4134
4135 group("a_b_shared_deps") {
4136 public_deps = [ ":c" ]
4137 }
4138```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004139### **arflags**: Arguments passed to static_library archiver.
Brett Wilson796ed472018-07-16 15:11:09 -07004140
4141```
4142 A list of flags passed to the archive/lib command that creates static
4143 libraries.
4144
4145 arflags are NOT pushed to dependents, so applying arflags to source sets or
4146 any other target type will be a no-op. As with ldflags, you could put the
4147 arflags in a config and set that as a public or "all dependent" config, but
4148 that will likely not be what you want. If you have a chain of static
4149 libraries dependent on each other, this can cause the flags to propagate up
4150 to other static libraries. Due to the nature of how arflags are typically
4151 used, you will normally want to apply them directly on static_library targets
4152 themselves.
4153```
4154
4155#### **Ordering of flags and values**
4156
4157```
4158 1. Those set on the current target (not in a config).
4159 2. Those set on the "configs" on the target in order that the
4160 configs appear in the list.
4161 3. Those set on the "all_dependent_configs" on the target in order
4162 that the configs appear in the list.
4163 4. Those set on the "public_configs" on the target in order that
4164 those configs appear in the list.
4165 5. all_dependent_configs pulled from dependencies, in the order of
4166 the "deps" list. This is done recursively. If a config appears
4167 more than once, only the first occurence will be used.
4168 6. public_configs pulled from dependencies, in the order of the
4169 "deps" list. If a dependency is public, they will be applied
4170 recursively.
4171```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004172### **args**: (target variable) Arguments passed to an action.
Brett Wilson796ed472018-07-16 15:11:09 -07004173
4174```
4175 For action and action_foreach targets, args is the list of arguments to pass
4176 to the script. Typically you would use source expansion (see "gn help
4177 source_expansion") to insert the source file names.
4178
4179 See also "gn help action" and "gn help action_foreach".
4180```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004181### **asmflags**: Flags passed to the assembler.
Brett Wilson796ed472018-07-16 15:11:09 -07004182
4183```
4184 A list of strings.
4185
4186 "asmflags" are passed to any invocation of a tool that takes an .asm or .S
4187 file as input.
4188```
4189
4190#### **Ordering of flags and values**
4191
4192```
4193 1. Those set on the current target (not in a config).
4194 2. Those set on the "configs" on the target in order that the
4195 configs appear in the list.
4196 3. Those set on the "all_dependent_configs" on the target in order
4197 that the configs appear in the list.
4198 4. Those set on the "public_configs" on the target in order that
4199 those configs appear in the list.
4200 5. all_dependent_configs pulled from dependencies, in the order of
4201 the "deps" list. This is done recursively. If a config appears
4202 more than once, only the first occurence will be used.
4203 6. public_configs pulled from dependencies, in the order of the
4204 "deps" list. If a dependency is public, they will be applied
4205 recursively.
4206```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004207### **assert_no_deps**: Ensure no deps on these targets.
Brett Wilson796ed472018-07-16 15:11:09 -07004208
4209```
4210 A list of label patterns.
4211
4212 This list is a list of patterns that must not match any of the transitive
4213 dependencies of the target. These include all public, private, and data
4214 dependencies, and cross shared library boundaries. This allows you to express
4215 that undesirable code isn't accidentally added to downstream dependencies in
4216 a way that might otherwise be difficult to notice.
4217
4218 Checking does not cross executable boundaries. If a target depends on an
4219 executable, it's assumed that the executable is a tool that is producing part
4220 of the build rather than something that is linked and distributed. This
4221 allows assert_no_deps to express what is distributed in the final target
4222 rather than depend on the internal build steps (which may include
4223 non-distributable code).
4224
4225 See "gn help label_pattern" for the format of the entries in the list. These
4226 patterns allow blacklisting individual targets or whole directory
4227 hierarchies.
4228
4229 Sometimes it is desirable to enforce that many targets have no dependencies
4230 on a target or set of targets. One efficient way to express this is to create
4231 a group with the assert_no_deps rule on it, and make that group depend on all
4232 targets you want to apply that assertion to.
4233```
4234
4235#### **Example**
4236
4237```
4238 executable("doom_melon") {
4239 deps = [ "//foo:bar" ]
4240 ...
4241 assert_no_deps = [
4242 "//evil/*", # Don't link any code from the evil directory.
4243 "//foo:test_support", # This target is also disallowed.
4244 ]
4245 }
4246```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004247### **bundle_contents_dir**: Expansion of {{bundle_contents_dir}} in
Brett Wilson796ed472018-07-16 15:11:09 -07004248```
4249 create_bundle.
4250
4251 A string corresponding to a path in $root_build_dir.
4252
4253 This string is used by the "create_bundle" target to expand the
4254 {{bundle_contents_dir}} of the "bundle_data" target it depends on. This must
4255 correspond to a path under "bundle_root_dir".
4256
4257 See "gn help bundle_root_dir" for examples.
4258```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004259### **bundle_deps_filter**: [label list] A list of labels that are filtered out.
Brett Wilson796ed472018-07-16 15:11:09 -07004260
4261```
4262 A list of target labels.
4263
4264 This list contains target label patterns that should be filtered out when
4265 creating the bundle. Any target matching one of those label will be removed
4266 from the dependencies of the create_bundle target.
4267
4268 This is mostly useful when creating application extension bundle as the
4269 application extension has access to runtime resources from the application
4270 bundle and thus do not require a second copy.
4271
4272 See "gn help create_bundle" for more information.
4273```
4274
4275#### **Example**
4276
4277```
4278 create_bundle("today_extension") {
4279 deps = [
4280 "//base"
4281 ]
4282 bundle_root_dir = "$root_out_dir/today_extension.appex"
4283 bundle_deps_filter = [
4284 # The extension uses //base but does not use any function calling into
4285 # third_party/icu and thus does not need the icudtl.dat file.
4286 "//third_party/icu:icudata",
4287 ]
4288 }
4289```
Sylvain Defresned46f92f2019-04-03 16:14:29 +02004290### **bundle_executable_dir**
Brett Wilson796ed472018-07-16 15:11:09 -07004291
Joe Armstrongb199e542019-03-21 09:40:08 +08004292```
Sylvain Defresned46f92f2019-04-03 16:14:29 +02004293 bundle_executable_dir: Expansion of {{bundle_executable_dir}} in
4294 create_bundle.
4295
Brett Wilson796ed472018-07-16 15:11:09 -07004296 A string corresponding to a path in $root_build_dir.
4297
4298 This string is used by the "create_bundle" target to expand the
4299 {{bundle_executable_dir}} of the "bundle_data" target it depends on. This
4300 must correspond to a path under "bundle_root_dir".
4301
4302 See "gn help bundle_root_dir" for examples.
4303```
Joe Armstrongb199e542019-03-21 09:40:08 +08004304### **bundle_resources_dir**
4305
Brett Wilson796ed472018-07-16 15:11:09 -07004306```
Sylvain Defresned46f92f2019-04-03 16:14:29 +02004307 bundle_resources_dir: Expansion of {{bundle_resources_dir}} in
4308 create_bundle.
Brett Wilson796ed472018-07-16 15:11:09 -07004309
4310 A string corresponding to a path in $root_build_dir.
4311
4312 This string is used by the "create_bundle" target to expand the
4313 {{bundle_resources_dir}} of the "bundle_data" target it depends on. This must
4314 correspond to a path under "bundle_root_dir".
4315
4316 See "gn help bundle_root_dir" for examples.
4317```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004318### **bundle_root_dir**: Expansion of {{bundle_root_dir}} in create_bundle.
Brett Wilson796ed472018-07-16 15:11:09 -07004319
4320```
4321 A string corresponding to a path in root_build_dir.
4322
4323 This string is used by the "create_bundle" target to expand the
4324 {{bundle_root_dir}} of the "bundle_data" target it depends on. This must
4325 correspond to a path under root_build_dir.
4326```
4327
4328#### **Example**
4329
4330```
4331 bundle_data("info_plist") {
4332 sources = [ "Info.plist" ]
4333 outputs = [ "{{bundle_contents_dir}}/Info.plist" ]
4334 }
4335
4336 create_bundle("doom_melon.app") {
4337 deps = [ ":info_plist" ]
4338 bundle_root_dir = "${root_build_dir}/doom_melon.app"
4339 bundle_contents_dir = "${bundle_root_dir}/Contents"
4340 bundle_resources_dir = "${bundle_contents_dir}/Resources"
4341 bundle_executable_dir = "${bundle_contents_dir}/MacOS"
Brett Wilson796ed472018-07-16 15:11:09 -07004342 }
4343```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004344### **cflags***: Flags passed to the C compiler.
Brett Wilson796ed472018-07-16 15:11:09 -07004345
4346```
4347 A list of strings.
4348
4349 "cflags" are passed to all invocations of the C, C++, Objective C, and
4350 Objective C++ compilers.
4351
4352 To target one of these variants individually, use "cflags_c", "cflags_cc",
4353 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
4354 versions of cflags* will be appended on the compiler command line after
4355 "cflags".
4356
4357 See also "asmflags" for flags for assembly-language files.
4358```
4359
4360#### **Ordering of flags and values**
4361
4362```
4363 1. Those set on the current target (not in a config).
4364 2. Those set on the "configs" on the target in order that the
4365 configs appear in the list.
4366 3. Those set on the "all_dependent_configs" on the target in order
4367 that the configs appear in the list.
4368 4. Those set on the "public_configs" on the target in order that
4369 those configs appear in the list.
4370 5. all_dependent_configs pulled from dependencies, in the order of
4371 the "deps" list. This is done recursively. If a config appears
4372 more than once, only the first occurence will be used.
4373 6. public_configs pulled from dependencies, in the order of the
4374 "deps" list. If a dependency is public, they will be applied
4375 recursively.
4376```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004377### **cflags***: Flags passed to the C compiler.
Brett Wilson796ed472018-07-16 15:11:09 -07004378
4379```
4380 A list of strings.
4381
4382 "cflags" are passed to all invocations of the C, C++, Objective C, and
4383 Objective C++ compilers.
4384
4385 To target one of these variants individually, use "cflags_c", "cflags_cc",
4386 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
4387 versions of cflags* will be appended on the compiler command line after
4388 "cflags".
4389
4390 See also "asmflags" for flags for assembly-language files.
4391```
4392
4393#### **Ordering of flags and values**
4394
4395```
4396 1. Those set on the current target (not in a config).
4397 2. Those set on the "configs" on the target in order that the
4398 configs appear in the list.
4399 3. Those set on the "all_dependent_configs" on the target in order
4400 that the configs appear in the list.
4401 4. Those set on the "public_configs" on the target in order that
4402 those configs appear in the list.
4403 5. all_dependent_configs pulled from dependencies, in the order of
4404 the "deps" list. This is done recursively. If a config appears
4405 more than once, only the first occurence will be used.
4406 6. public_configs pulled from dependencies, in the order of the
4407 "deps" list. If a dependency is public, they will be applied
4408 recursively.
4409```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004410### **cflags***: Flags passed to the C compiler.
Brett Wilson796ed472018-07-16 15:11:09 -07004411
4412```
4413 A list of strings.
4414
4415 "cflags" are passed to all invocations of the C, C++, Objective C, and
4416 Objective C++ compilers.
4417
4418 To target one of these variants individually, use "cflags_c", "cflags_cc",
4419 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
4420 versions of cflags* will be appended on the compiler command line after
4421 "cflags".
4422
4423 See also "asmflags" for flags for assembly-language files.
4424```
4425
4426#### **Ordering of flags and values**
4427
4428```
4429 1. Those set on the current target (not in a config).
4430 2. Those set on the "configs" on the target in order that the
4431 configs appear in the list.
4432 3. Those set on the "all_dependent_configs" on the target in order
4433 that the configs appear in the list.
4434 4. Those set on the "public_configs" on the target in order that
4435 those configs appear in the list.
4436 5. all_dependent_configs pulled from dependencies, in the order of
4437 the "deps" list. This is done recursively. If a config appears
4438 more than once, only the first occurence will be used.
4439 6. public_configs pulled from dependencies, in the order of the
4440 "deps" list. If a dependency is public, they will be applied
4441 recursively.
4442```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004443### **cflags***: Flags passed to the C compiler.
Brett Wilson796ed472018-07-16 15:11:09 -07004444
4445```
4446 A list of strings.
4447
4448 "cflags" are passed to all invocations of the C, C++, Objective C, and
4449 Objective C++ compilers.
4450
4451 To target one of these variants individually, use "cflags_c", "cflags_cc",
4452 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
4453 versions of cflags* will be appended on the compiler command line after
4454 "cflags".
4455
4456 See also "asmflags" for flags for assembly-language files.
4457```
4458
4459#### **Ordering of flags and values**
4460
4461```
4462 1. Those set on the current target (not in a config).
4463 2. Those set on the "configs" on the target in order that the
4464 configs appear in the list.
4465 3. Those set on the "all_dependent_configs" on the target in order
4466 that the configs appear in the list.
4467 4. Those set on the "public_configs" on the target in order that
4468 those configs appear in the list.
4469 5. all_dependent_configs pulled from dependencies, in the order of
4470 the "deps" list. This is done recursively. If a config appears
4471 more than once, only the first occurence will be used.
4472 6. public_configs pulled from dependencies, in the order of the
4473 "deps" list. If a dependency is public, they will be applied
4474 recursively.
4475```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004476### **cflags***: Flags passed to the C compiler.
Brett Wilson796ed472018-07-16 15:11:09 -07004477
4478```
4479 A list of strings.
4480
4481 "cflags" are passed to all invocations of the C, C++, Objective C, and
4482 Objective C++ compilers.
4483
4484 To target one of these variants individually, use "cflags_c", "cflags_cc",
4485 "cflags_objc", and "cflags_objcc", respectively. These variant-specific
4486 versions of cflags* will be appended on the compiler command line after
4487 "cflags".
4488
4489 See also "asmflags" for flags for assembly-language files.
4490```
4491
4492#### **Ordering of flags and values**
4493
4494```
4495 1. Those set on the current target (not in a config).
4496 2. Those set on the "configs" on the target in order that the
4497 configs appear in the list.
4498 3. Those set on the "all_dependent_configs" on the target in order
4499 that the configs appear in the list.
4500 4. Those set on the "public_configs" on the target in order that
4501 those configs appear in the list.
4502 5. all_dependent_configs pulled from dependencies, in the order of
4503 the "deps" list. This is done recursively. If a config appears
4504 more than once, only the first occurence will be used.
4505 6. public_configs pulled from dependencies, in the order of the
4506 "deps" list. If a dependency is public, they will be applied
4507 recursively.
4508```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004509### **check_includes**: [boolean] Controls whether a target's files are checked.
Brett Wilson796ed472018-07-16 15:11:09 -07004510
4511```
4512 When true (the default), the "gn check" command (as well as "gn gen" with the
4513 --check flag) will check this target's sources and headers for proper
4514 dependencies.
4515
4516 When false, the files in this target will be skipped by default. This does
4517 not affect other targets that depend on the current target, it just skips
4518 checking the includes of the current target's files.
4519
4520 If there are a few conditionally included headers that trip up checking, you
4521 can exclude headers individually by annotating them with "nogncheck" (see "gn
4522 help nogncheck").
4523
4524 The topic "gn help check" has general information on how checking works and
4525 advice on how to pass a check in problematic cases.
4526```
4527
4528#### **Example**
4529
4530```
4531 source_set("busted_includes") {
4532 # This target's includes are messed up, exclude it from checking.
4533 check_includes = false
4534 ...
4535 }
4536```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004537### **code_signing_args**: [string list] Arguments passed to code signing script.
Brett Wilson796ed472018-07-16 15:11:09 -07004538
4539```
4540 For create_bundle targets, code_signing_args is the list of arguments to pass
4541 to the code signing script. Typically you would use source expansion (see "gn
4542 help source_expansion") to insert the source file names.
4543
4544 See also "gn help create_bundle".
4545```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004546### **code_signing_outputs**: [file list] Output files for code signing step.
Brett Wilson796ed472018-07-16 15:11:09 -07004547
4548```
4549 Outputs from the code signing step of a create_bundle target. Must refer to
4550 files in the build directory.
4551
4552 See also "gn help create_bundle".
4553```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004554### **code_signing_script**: [file name] Script for code signing."
Brett Wilson796ed472018-07-16 15:11:09 -07004555
4556```
4557 An absolute or buildfile-relative file name of a Python script to run for a
4558 create_bundle target to perform code signing step.
4559
4560 See also "gn help create_bundle".
4561```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004562### **code_signing_sources**: [file list] Sources for code signing step.
Brett Wilson796ed472018-07-16 15:11:09 -07004563
4564```
4565 A list of files used as input for code signing script step of a create_bundle
4566 target. Non-absolute paths will be resolved relative to the current build
4567 file.
4568
4569 See also "gn help create_bundle".
4570```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004571### **complete_static_lib**: [boolean] Links all deps into a static library.
Brett Wilson796ed472018-07-16 15:11:09 -07004572
4573```
4574 A static library normally doesn't include code from dependencies, but instead
4575 forwards the static libraries and source sets in its deps up the dependency
4576 chain until a linkable target (an executable or shared library) is reached.
4577 The final linkable target only links each static library once, even if it
4578 appears more than once in its dependency graph.
4579
4580 In some cases the static library might be the final desired output. For
4581 example, you may be producing a static library for distribution to third
4582 parties. In this case, the static library should include code for all
4583 dependencies in one complete package. However, complete static libraries
4584 themselves are never linked into other complete static libraries. All
4585 complete static libraries are for distribution and linking them in would
4586 cause code duplication in this case. If the static library is not for
4587 distribution, it should not be complete.
4588
4589 GN treats non-complete static libraries as source sets when they are linked
4590 into complete static libraries. This is done because some tools like AR do
4591 not handle dependent static libraries properly. This makes it easier to write
4592 "alink" rules.
4593
4594 In rare cases it makes sense to list a header in more than one target if it
4595 could be considered conceptually a member of both. libraries.
4596```
4597
4598#### **Example**
4599
4600```
4601 static_library("foo") {
4602 complete_static_lib = true
4603 deps = [ "bar" ]
4604 }
4605```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004606### **configs**: Configs applying to this target or config.
Brett Wilson796ed472018-07-16 15:11:09 -07004607
4608```
4609 A list of config labels.
4610```
4611
4612#### **Configs on a target**
4613
4614```
4615 When used on a target, the include_dirs, defines, etc. in each config are
4616 appended in the order they appear to the compile command for each file in the
4617 target. They will appear after the include_dirs, defines, etc. that the
4618 target sets directly.
4619
4620 Since configs apply after the values set on a target, directly setting a
4621 compiler flag will prepend it to the command line. If you want to append a
4622 flag instead, you can put that flag in a one-off config and append that
4623 config to the target's configs list.
4624
4625 The build configuration script will generally set up the default configs
4626 applying to a given target type (see "set_defaults"). When a target is being
4627 defined, it can add to or remove from this list.
4628```
4629
4630#### **Configs on a config**
4631
4632```
4633 It is possible to create composite configs by specifying configs on a config.
4634 One might do this to forward values, or to factor out blocks of settings from
4635 very large configs into more manageable named chunks.
4636
4637 In this case, the composite config is expanded to be the concatenation of its
4638 own values, and in order, the values from its sub-configs *before* anything
4639 else happens. This has some ramifications:
4640
4641 - A target has no visibility into a config's sub-configs. Target code only
4642 sees the name of the composite config. It can't remove sub-configs or opt
4643 in to only parts of it. The composite config may not even be defined
4644 before the target is.
4645
4646 - You can get duplication of values if a config is listed twice, say, on a
4647 target and in a sub-config that also applies. In other cases, the configs
4648 applying to a target are de-duped. It's expected that if a config is
4649 listed as a sub-config that it is only used in that context. (Note that
4650 it's possible to fix this and de-dupe, but it's not normally relevant and
4651 complicates the implementation.)
4652```
4653
4654#### **Ordering of flags and values**
4655
4656```
4657 1. Those set on the current target (not in a config).
4658 2. Those set on the "configs" on the target in order that the
4659 configs appear in the list.
4660 3. Those set on the "all_dependent_configs" on the target in order
4661 that the configs appear in the list.
4662 4. Those set on the "public_configs" on the target in order that
4663 those configs appear in the list.
4664 5. all_dependent_configs pulled from dependencies, in the order of
4665 the "deps" list. This is done recursively. If a config appears
4666 more than once, only the first occurence will be used.
4667 6. public_configs pulled from dependencies, in the order of the
4668 "deps" list. If a dependency is public, they will be applied
4669 recursively.
4670```
4671
4672#### **Example**
4673
4674```
4675 # Configs on a target.
4676 source_set("foo") {
4677 # Don't use the default RTTI config that BUILDCONFIG applied to us.
4678 configs -= [ "//build:no_rtti" ]
4679
4680 # Add some of our own settings.
4681 configs += [ ":mysettings" ]
4682 }
4683
4684 # Create a default_optimization config that forwards to one of a set of more
4685 # specialized configs depending on build flags. This pattern is useful
4686 # because it allows a target to opt in to either a default set, or a more
4687 # specific set, while avoid duplicating the settings in two places.
4688 config("super_optimization") {
4689 cflags = [ ... ]
4690 }
4691 config("default_optimization") {
4692 if (optimize_everything) {
4693 configs = [ ":super_optimization" ]
4694 } else {
4695 configs = [ ":no_optimization" ]
4696 }
4697 }
4698```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004699### **contents**: Contents to write to file.
Nate Fischer8ed01d32019-01-08 17:32:01 -08004700
4701```
4702 The contents of the file for a generated_file target.
4703 See "gn help generated_file".
4704```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004705### **data**: Runtime data file dependencies.
Brett Wilson796ed472018-07-16 15:11:09 -07004706
4707```
4708 Lists files or directories required to run the given target. These are
4709 typically data files or directories of data files. The paths are interpreted
4710 as being relative to the current build file. Since these are runtime
4711 dependencies, they do not affect which targets are built or when. To declare
4712 input files to a script, use "inputs".
4713
4714 Appearing in the "data" section does not imply any special handling such as
4715 copying them to the output directory. This is just used for declaring runtime
4716 dependencies. Runtime dependencies can be queried using the "runtime_deps"
4717 category of "gn desc" or written during build generation via
4718 "--runtime-deps-list-file".
4719
4720 GN doesn't require data files to exist at build-time. So actions that produce
4721 files that are in turn runtime dependencies can list those generated files
4722 both in the "outputs" list as well as the "data" list.
4723
4724 By convention, directories are listed with a trailing slash:
4725 data = [ "test/data/" ]
4726 However, no verification is done on these so GN doesn't enforce this. The
4727 paths are just rebased and passed along when requested.
4728
4729 Note: On iOS and macOS, create_bundle targets will not be recursed into when
4730 gathering data. See "gn help create_bundle" for details.
4731
4732 See "gn help runtime_deps" for how these are used.
4733```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004734### **data_deps**: Non-linked dependencies.
Brett Wilson796ed472018-07-16 15:11:09 -07004735
4736```
4737 A list of target labels.
4738
4739 Specifies dependencies of a target that are not actually linked into the
4740 current target. Such dependencies will be built and will be available at
4741 runtime.
4742
4743 This is normally used for things like plugins or helper programs that a
4744 target needs at runtime.
4745
4746 Note: On iOS and macOS, create_bundle targets will not be recursed into when
4747 gathering data_deps. See "gn help create_bundle" for details.
4748
4749 See also "gn help deps" and "gn help data".
4750```
4751
4752#### **Example**
4753
4754```
4755 executable("foo") {
4756 deps = [ "//base" ]
4757 data_deps = [ "//plugins:my_runtime_plugin" ]
4758 }
4759```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004760### **data_keys**: Keys from which to collect metadata.
Nate Fischer8ed01d32019-01-08 17:32:01 -08004761
4762```
4763 These keys are used to identify metadata to collect. If a walked target
4764 defines this key in its metadata, its value will be appended to the resulting
4765 collection.
4766
4767 See "gn help generated_file".
4768```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004769### **defines**: C preprocessor defines.
Brett Wilson796ed472018-07-16 15:11:09 -07004770
4771```
4772 A list of strings
4773
4774 These strings will be passed to the C/C++ compiler as #defines. The strings
4775 may or may not include an "=" to assign a value.
4776```
4777
4778#### **Ordering of flags and values**
4779
4780```
4781 1. Those set on the current target (not in a config).
4782 2. Those set on the "configs" on the target in order that the
4783 configs appear in the list.
4784 3. Those set on the "all_dependent_configs" on the target in order
4785 that the configs appear in the list.
4786 4. Those set on the "public_configs" on the target in order that
4787 those configs appear in the list.
4788 5. all_dependent_configs pulled from dependencies, in the order of
4789 the "deps" list. This is done recursively. If a config appears
4790 more than once, only the first occurence will be used.
4791 6. public_configs pulled from dependencies, in the order of the
4792 "deps" list. If a dependency is public, they will be applied
4793 recursively.
4794```
4795
4796#### **Example**
4797
4798```
4799 defines = [ "AWESOME_FEATURE", "LOG_LEVEL=3" ]
4800```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004801### **depfile**: [string] File name for input dependencies for actions.
Brett Wilson796ed472018-07-16 15:11:09 -07004802
4803```
4804 If nonempty, this string specifies that the current action or action_foreach
4805 target will generate the given ".d" file containing the dependencies of the
4806 input. Empty or unset means that the script doesn't generate the files.
4807
4808 A depfile should be used only when a target depends on files that are not
4809 already specified by a target's inputs and sources. Likewise, depfiles should
4810 specify only those dependencies not already included in sources or inputs.
4811
4812 The .d file should go in the target output directory. If you have more than
4813 one source file that the script is being run over, you can use the output
4814 file expansions described in "gn help action_foreach" to name the .d file
4815 according to the input."
4816
4817 The format is that of a Makefile and all paths must be relative to the root
4818 build directory. Only one output may be listed and it must match the first
4819 output of the action.
4820
4821 Although depfiles are created by an action, they should not be listed in the
4822 action's "outputs" unless another target will use the file as an input.
4823```
4824
4825#### **Example**
4826
4827```
4828 action_foreach("myscript_target") {
4829 script = "myscript.py"
4830 sources = [ ... ]
4831
4832 # Locate the depfile in the output directory named like the
4833 # inputs but with a ".d" appended.
4834 depfile = "$relative_target_output_dir/{{source_name}}.d"
4835
4836 # Say our script uses "-o " to indicate the depfile.
4837 args = [ "{{source}}", "-o", depfile ]
4838 }
4839```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004840### **deps**: Private linked dependencies.
Brett Wilson796ed472018-07-16 15:11:09 -07004841
4842```
4843 A list of target labels.
4844
4845 Specifies private dependencies of a target. Private dependencies are
4846 propagated up the dependency tree and linked to dependent targets, but do not
4847 grant the ability to include headers from the dependency. Public configs are
4848 not forwarded.
4849```
4850
4851#### **Details of dependency propagation**
4852
4853```
4854 Source sets, shared libraries, and non-complete static libraries will be
4855 propagated up the dependency tree across groups, non-complete static
4856 libraries and source sets.
4857
4858 Executables, shared libraries, and complete static libraries will link all
4859 propagated targets and stop propagation. Actions and copy steps also stop
4860 propagation, allowing them to take a library as an input but not force
4861 dependents to link to it.
4862
4863 Propagation of all_dependent_configs and public_configs happens independently
4864 of target type. all_dependent_configs are always propagated across all types
4865 of targets, and public_configs are always propagated across public deps of
4866 all types of targets.
4867
4868 Data dependencies are propagated differently. See "gn help data_deps" and
4869 "gn help runtime_deps".
4870
4871 See also "public_deps".
4872```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004873### **friend**: Allow targets to include private headers.
Brett Wilson796ed472018-07-16 15:11:09 -07004874
4875```
4876 A list of label patterns (see "gn help label_pattern") that allow dependent
4877 targets to include private headers. Applies to all binary targets.
4878
4879 Normally if a target lists headers in the "public" list (see "gn help
4880 public"), other headers are implicitly marked as private. Private headers
4881 can not be included by other targets, even with a public dependency path.
4882 The "gn check" function performs this validation.
4883
4884 A friend declaration allows one or more targets to include private headers.
4885 This is useful for things like unit tests that are closely associated with a
4886 target and require internal knowledge without opening up all headers to be
4887 included by all dependents.
4888
4889 A friend target does not allow that target to include headers when no
4890 dependency exists. A public dependency path must still exist between two
4891 targets to include any headers from a destination target. The friend
4892 annotation merely allows the use of headers that would otherwise be
4893 prohibited because they are private.
4894
4895 The friend annotation is matched only against the target containing the file
4896 with the include directive. Friend annotations are not propagated across
4897 public or private dependencies. Friend annotations do not affect visibility.
4898```
4899
4900#### **Example**
4901
4902```
4903 static_library("lib") {
4904 # This target can include our private headers.
4905 friend = [ ":unit_tests" ]
4906
4907 public = [
4908 "public_api.h", # Normal public API for dependent targets.
4909 ]
4910
4911 # Private API and sources.
4912 sources = [
4913 "a_source_file.cc",
4914
4915 # Normal targets that depend on this one won't be able to include this
4916 # because this target defines a list of "public" headers. Without the
4917 # "public" list, all headers are implicitly public.
4918 "private_api.h",
4919 ]
4920 }
4921
4922 executable("unit_tests") {
4923 sources = [
4924 # This can include "private_api.h" from the :lib target because it
4925 # depends on that target and because of the friend annotation.
4926 "my_test.cc",
4927 ]
4928
4929 deps = [
4930 ":lib", # Required for the include to be allowed.
4931 ]
4932 }
4933```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004934### **include_dirs**: Additional include directories.
Brett Wilson796ed472018-07-16 15:11:09 -07004935
4936```
4937 A list of source directories.
4938
4939 The directories in this list will be added to the include path for the files
4940 in the affected target.
4941```
4942
4943#### **Ordering of flags and values**
4944
4945```
4946 1. Those set on the current target (not in a config).
4947 2. Those set on the "configs" on the target in order that the
4948 configs appear in the list.
4949 3. Those set on the "all_dependent_configs" on the target in order
4950 that the configs appear in the list.
4951 4. Those set on the "public_configs" on the target in order that
4952 those configs appear in the list.
4953 5. all_dependent_configs pulled from dependencies, in the order of
4954 the "deps" list. This is done recursively. If a config appears
4955 more than once, only the first occurence will be used.
4956 6. public_configs pulled from dependencies, in the order of the
4957 "deps" list. If a dependency is public, they will be applied
4958 recursively.
4959```
4960
4961#### **Example**
4962
4963```
4964 include_dirs = [ "src/include", "//third_party/foo" ]
4965```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08004966### **inputs**: Additional compile-time dependencies.
Brett Wilson796ed472018-07-16 15:11:09 -07004967
4968```
4969 Inputs are compile-time dependencies of the current target. This means that
4970 all inputs must be available before compiling any of the sources or executing
4971 any actions.
4972
4973 Inputs are typically only used for action and action_foreach targets.
4974```
4975
4976#### **Inputs for actions**
4977
4978```
4979 For action and action_foreach targets, inputs should be the inputs to script
4980 that don't vary. These should be all .py files that the script uses via
4981 imports (the main script itself will be an implicit dependency of the action
4982 so need not be listed).
4983
4984 For action targets, inputs and sources are treated the same, but from a style
4985 perspective, it's recommended to follow the same rule as action_foreach and
4986 put helper files in the inputs, and the data used by the script (if any) in
4987 sources.
4988
4989 Note that another way to declare input dependencies from an action is to have
4990 the action write a depfile (see "gn help depfile"). This allows the script to
4991 dynamically write input dependencies, that might not be known until actually
4992 executing the script. This is more efficient than doing processing while
4993 running GN to determine the inputs, and is easier to keep in-sync than
4994 hardcoding the list.
4995```
4996
4997#### **Script input gotchas**
4998
4999```
5000 It may be tempting to write a script that enumerates all files in a directory
5001 as inputs. Don't do this! Even if you specify all the files in the inputs or
5002 sources in the GN target (or worse, enumerate the files in an exec_script
5003 call when running GN, which will be slow), the dependencies will be broken.
5004
5005 The problem happens if a file is ever removed because the inputs are not
5006 listed on the command line to the script. Because the script hasn't changed
5007 and all inputs are up to date, the script will not re-run and you will get a
5008 stale build. Instead, either list all inputs on the command line to the
5009 script, or if there are many, create a separate list file that the script
5010 reads. As long as this file is listed in the inputs, the build will detect
5011 when it has changed in any way and the action will re-run.
5012```
5013
5014#### **Inputs for binary targets**
5015
5016```
Julie Hockette2a29402018-07-31 10:11:42 -07005017 Any input dependencies will be resolved before compiling any sources or
5018 linking the target. Normally, all actions that a target depends on will be run
5019 before any files in a target are compiled. So if you depend on generated
5020 headers, you do not typically need to list them in the inputs section.
Brett Wilson796ed472018-07-16 15:11:09 -07005021
5022 Inputs for binary targets will be treated as implicit dependencies, meaning
5023 that changes in any of the inputs will force all sources in the target to be
5024 recompiled. If an input only applies to a subset of source files, you may
5025 want to split those into a separate target to avoid unnecessary recompiles.
5026```
5027
5028#### **Example**
5029
5030```
5031 action("myscript") {
5032 script = "domything.py"
5033 inputs = [ "input.data" ]
5034 }
5035```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005036### **ldflags**: Flags passed to the linker.
Brett Wilson796ed472018-07-16 15:11:09 -07005037
5038```
5039 A list of strings.
5040
5041 These flags are passed on the command-line to the linker and generally
5042 specify various linking options. Most targets will not need these and will
5043 use "libs" and "lib_dirs" instead.
5044
5045 ldflags are NOT pushed to dependents, so applying ldflags to source sets or
5046 static libraries will be a no-op. If you want to apply ldflags to dependent
5047 targets, put them in a config and set it in the all_dependent_configs or
5048 public_configs.
5049```
5050
5051#### **Ordering of flags and values**
5052
5053```
5054 1. Those set on the current target (not in a config).
5055 2. Those set on the "configs" on the target in order that the
5056 configs appear in the list.
5057 3. Those set on the "all_dependent_configs" on the target in order
5058 that the configs appear in the list.
5059 4. Those set on the "public_configs" on the target in order that
5060 those configs appear in the list.
5061 5. all_dependent_configs pulled from dependencies, in the order of
5062 the "deps" list. This is done recursively. If a config appears
5063 more than once, only the first occurence will be used.
5064 6. public_configs pulled from dependencies, in the order of the
5065 "deps" list. If a dependency is public, they will be applied
5066 recursively.
5067```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005068### **lib_dirs**: Additional library directories.
Brett Wilson796ed472018-07-16 15:11:09 -07005069
5070```
5071 A list of directories.
5072
5073 Specifies additional directories passed to the linker for searching for the
5074 required libraries. If an item is not an absolute path, it will be treated as
5075 being relative to the current build file.
5076
5077 libs and lib_dirs work differently than other flags in two respects.
5078 First, then are inherited across static library boundaries until a
5079 shared library or executable target is reached. Second, they are
5080 uniquified so each one is only passed once (the first instance of it
5081 will be the one used).
5082```
5083
5084#### **Ordering of flags and values**
5085
5086```
5087 1. Those set on the current target (not in a config).
5088 2. Those set on the "configs" on the target in order that the
5089 configs appear in the list.
5090 3. Those set on the "all_dependent_configs" on the target in order
5091 that the configs appear in the list.
5092 4. Those set on the "public_configs" on the target in order that
5093 those configs appear in the list.
5094 5. all_dependent_configs pulled from dependencies, in the order of
5095 the "deps" list. This is done recursively. If a config appears
5096 more than once, only the first occurence will be used.
5097 6. public_configs pulled from dependencies, in the order of the
5098 "deps" list. If a dependency is public, they will be applied
5099 recursively.
5100
5101 For "libs" and "lib_dirs" only, the values propagated from
5102 dependencies (as described above) are applied last assuming they
5103 are not already in the list.
5104```
5105
5106#### **Example**
5107
5108```
5109 lib_dirs = [ "/usr/lib/foo", "lib/doom_melon" ]
5110```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005111### **libs**: Additional libraries to link.
Brett Wilson796ed472018-07-16 15:11:09 -07005112
5113```
5114 A list of library names or library paths.
5115
5116 These libraries will be linked into the final binary (executable or shared
5117 library) containing the current target.
5118
5119 libs and lib_dirs work differently than other flags in two respects.
5120 First, then are inherited across static library boundaries until a
5121 shared library or executable target is reached. Second, they are
5122 uniquified so each one is only passed once (the first instance of it
5123 will be the one used).
5124```
5125
5126#### **Types of libs**
5127
5128```
5129 There are several different things that can be expressed in libs:
5130
5131 File paths
5132 Values containing '/' will be treated as references to files in the
5133 checkout. They will be rebased to be relative to the build directory and
5134 specified in the "libs" for linker tools. This facility should be used
5135 for libraries that are checked in to the version control. For libraries
5136 that are generated by the build, use normal GN deps to link them.
5137
5138 System libraries
5139 Values not containing '/' will be treated as system library names. These
5140 will be passed unmodified to the linker and prefixed with the
5141 "lib_switch" attribute of the linker tool. Generally you would set the
5142 "lib_dirs" so the given library is found. Your BUILD.gn file should not
5143 specify the switch (like "-l"): this will be encoded in the "lib_switch"
5144 of the tool.
5145
5146 Apple frameworks
5147 System libraries ending in ".framework" will be special-cased: the switch
5148 "-framework" will be prepended instead of the lib_switch, and the
5149 ".framework" suffix will be trimmed. This is to support the way Mac links
5150 framework dependencies.
5151```
5152
5153#### **Ordering of flags and values**
5154
5155```
5156 1. Those set on the current target (not in a config).
5157 2. Those set on the "configs" on the target in order that the
5158 configs appear in the list.
5159 3. Those set on the "all_dependent_configs" on the target in order
5160 that the configs appear in the list.
5161 4. Those set on the "public_configs" on the target in order that
5162 those configs appear in the list.
5163 5. all_dependent_configs pulled from dependencies, in the order of
5164 the "deps" list. This is done recursively. If a config appears
5165 more than once, only the first occurence will be used.
5166 6. public_configs pulled from dependencies, in the order of the
5167 "deps" list. If a dependency is public, they will be applied
5168 recursively.
5169
5170 For "libs" and "lib_dirs" only, the values propagated from
5171 dependencies (as described above) are applied last assuming they
5172 are not already in the list.
5173```
5174
5175#### **Examples**
5176
5177```
5178 On Windows:
5179 libs = [ "ctl3d.lib" ]
5180
5181 On Linux:
5182 libs = [ "ld" ]
5183```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005184### **metadata**: Metadata of this target.
Nate Fischer8ed01d32019-01-08 17:32:01 -08005185
5186```
5187 Metadata is a collection of keys and values relating to a particular target.
Julie Hockettd69a9c32019-01-23 14:36:18 -08005188 Values must be lists, allowing for sane and predictable collection behavior.
5189 Generally, these keys will include three types of lists: lists of ordinary
5190 strings, lists of filenames intended to be rebased according to their
5191 particular source directory, and lists of target labels intended to be used
5192 as barriers to the walk. Verfication of these categories occurs at walk time,
5193 not creation time (since it is not clear until the walk which values are
5194 intended for which purpose).
5195```
Nate Fischer8ed01d32019-01-08 17:32:01 -08005196
Julie Hockettd69a9c32019-01-23 14:36:18 -08005197#### **Example**
Nate Fischer8ed01d32019-01-08 17:32:01 -08005198
Julie Hockettd69a9c32019-01-23 14:36:18 -08005199```
Nate Fischer8ed01d32019-01-08 17:32:01 -08005200 group("doom_melon") {
5201 metadata = {
5202 # These keys are not built in to GN but are interpreted when consuming
5203 # metadata.
5204 my_barrier = []
5205 my_files = [ "a.txt", "b.txt" ]
5206 }
5207 }
5208```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005209### **"output_conversion**: Data format for generated_file targets.
Nate Fischer8ed01d32019-01-08 17:32:01 -08005210
5211```
5212 Controls how the "contents" of a generated_file target is formatted.
Julie Hockett81ee1962019-05-13 11:24:42 -07005213 See "gn help io_conversion".
Nate Fischer8ed01d32019-01-08 17:32:01 -08005214```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005215### **output_dir**: [directory] Directory to put output file in.
Brett Wilson796ed472018-07-16 15:11:09 -07005216
5217```
5218 For library and executable targets, overrides the directory for the final
5219 output. This must be in the root_build_dir or a child thereof.
5220
5221 This should generally be in the root_out_dir or a subdirectory thereof (the
5222 root_out_dir will be the same as the root_build_dir for the default
5223 toolchain, and will be a subdirectory for other toolchains). Not putting the
5224 output in a subdirectory of root_out_dir can result in collisions between
5225 different toolchains, so you will need to take steps to ensure that your
5226 target is only present in one toolchain.
5227
5228 Normally the toolchain specifies the output directory for libraries and
5229 executables (see "gn help tool"). You will have to consult that for the
5230 default location. The default location will be used if output_dir is
5231 undefined or empty.
5232```
5233
5234#### **Example**
5235
5236```
5237 shared_library("doom_melon") {
5238 output_dir = "$root_out_dir/plugin_libs"
5239 ...
5240 }
5241```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005242### **output_extension**: Value to use for the output's file extension.
Brett Wilson796ed472018-07-16 15:11:09 -07005243
5244```
5245 Normally the file extension for a target is based on the target type and the
5246 operating system, but in rare cases you will need to override the name (for
5247 example to use "libfreetype.so.6" instead of libfreetype.so on Linux).
5248
5249 This value should not include a leading dot. If undefined, the default
5250 specified on the tool will be used. If set to the empty string, no output
5251 extension will be used.
5252
5253 The output_extension will be used to set the "{{output_extension}}" expansion
5254 which the linker tool will generally use to specify the output file name. See
5255 "gn help tool".
5256```
5257
5258#### **Example**
5259
5260```
5261 shared_library("freetype") {
5262 if (is_linux) {
5263 # Call the output "libfreetype.so.6"
5264 output_extension = "so.6"
5265 }
5266 ...
5267 }
5268
5269 # On Windows, generate a "mysettings.cpl" control panel applet. Control panel
5270 # applets are actually special shared libraries.
5271 if (is_win) {
5272 shared_library("mysettings") {
5273 output_extension = "cpl"
5274 ...
5275 }
5276 }
5277```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005278### **output_name**: Define a name for the output file other than the default.
Brett Wilson796ed472018-07-16 15:11:09 -07005279
5280```
5281 Normally the output name of a target will be based on the target name, so the
5282 target "//foo/bar:bar_unittests" will generate an output file such as
5283 "bar_unittests.exe" (using Windows as an example).
5284
5285 Sometimes you will want an alternate name to avoid collisions or if the
5286 internal name isn't appropriate for public distribution.
5287
5288 The output name should have no extension or prefixes, these will be added
5289 using the default system rules. For example, on Linux an output name of "foo"
5290 will produce a shared library "libfoo.so". There is no way to override the
5291 output prefix of a linker tool on a per- target basis. If you need more
5292 flexibility, create a copy target to produce the file you want.
5293
5294 This variable is valid for all binary output target types.
5295```
5296
5297#### **Example**
5298
5299```
5300 static_library("doom_melon") {
5301 output_name = "fluffy_bunny"
5302 }
5303```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005304### **output_prefix_override**: Don't use prefix for output name.
Brett Wilson796ed472018-07-16 15:11:09 -07005305
5306```
5307 A boolean that overrides the output prefix for a target. Defaults to false.
5308
5309 Some systems use prefixes for the names of the final target output file. The
5310 normal example is "libfoo.so" on Linux for a target named "foo".
5311
5312 The output prefix for a given target type is specified on the linker tool
5313 (see "gn help tool"). Sometimes this prefix is undesired.
5314
5315 See also "gn help output_extension".
5316```
5317
5318#### **Example**
5319
5320```
5321 shared_library("doom_melon") {
5322 # Normally this will produce "libdoom_melon.so" on Linux. Setting this flag
5323 # will produce "doom_melon.so".
5324 output_prefix_override = true
5325 ...
5326 }
5327```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005328### **outputs**: Output files for actions and copy targets.
Brett Wilson796ed472018-07-16 15:11:09 -07005329
5330```
5331 Outputs is valid for "copy", "action", and "action_foreach" target types and
5332 indicates the resulting files. Outputs must always refer to files in the
5333 build directory.
5334
5335 copy
5336 Copy targets should have exactly one entry in the outputs list. If there is
5337 exactly one source, this can be a literal file name or a source expansion.
5338 If there is more than one source, this must contain a source expansion to
5339 map a single input name to a single output name. See "gn help copy".
5340
5341 action_foreach
5342 Action_foreach targets must always use source expansions to map input files
5343 to output files. There can be more than one output, which means that each
5344 invocation of the script will produce a set of files (presumably based on
5345 the name of the input file). See "gn help action_foreach".
5346
5347 action
5348 Action targets (excluding action_foreach) must list literal output file(s)
5349 with no source expansions. See "gn help action".
5350```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005351### **partial_info_plist**: [filename] Path plist from asset catalog compiler.
Brett Wilson796ed472018-07-16 15:11:09 -07005352
5353```
5354 Valid for create_bundle target, corresponds to the path for the partial
5355 Info.plist created by the asset catalog compiler that needs to be merged
5356 with the application Info.plist (usually done by the code signing script).
5357
5358 The file will be generated regardless of whether the asset compiler has
5359 been invoked or not. See "gn help create_bundle".
5360```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005361### **pool**: Label of the pool used by the action.
Brett Wilson796ed472018-07-16 15:11:09 -07005362
5363```
5364 A fully-qualified label representing the pool that will be used for the
5365 action. Pools are defined using the pool() {...} declaration.
5366```
5367
5368#### **Example**
5369
5370```
5371 action("action") {
5372 pool = "//build:custom_pool"
5373 ...
5374 }
5375```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005376### **precompiled_header**: [string] Header file to precompile.
Brett Wilson796ed472018-07-16 15:11:09 -07005377
5378```
5379 Precompiled headers will be used when a target specifies this value, or a
5380 config applying to this target specifies this value. In addition, the tool
5381 corresponding to the source files must also specify precompiled headers (see
5382 "gn help tool"). The tool will also specify what type of precompiled headers
5383 to use, by setting precompiled_header_type to either "gcc" or "msvc".
5384
5385 The precompiled header/source variables can be specified on a target or a
5386 config, but must be the same for all configs applying to a given target since
5387 a target can only have one precompiled header.
5388
5389 If you use both C and C++ sources, the precompiled header and source file
5390 will be compiled once per language. You will want to make sure to wrap C++
5391 includes in __cplusplus #ifdefs so the file will compile in C mode.
5392```
5393
5394#### **GCC precompiled headers**
5395
5396```
5397 When using GCC-style precompiled headers, "precompiled_source" contains the
5398 path of a .h file that is precompiled and then included by all source files
5399 in targets that set "precompiled_source".
5400
5401 The value of "precompiled_header" is not used with GCC-style precompiled
5402 headers.
5403```
5404
5405#### **MSVC precompiled headers**
5406
5407```
5408 When using MSVC-style precompiled headers, the "precompiled_header" value is
5409 a string corresponding to the header. This is NOT a path to a file that GN
5410 recognises, but rather the exact string that appears in quotes after
5411 an #include line in source code. The compiler will match this string against
5412 includes or forced includes (/FI).
5413
5414 MSVC also requires a source file to compile the header with. This must be
5415 specified by the "precompiled_source" value. In contrast to the header value,
5416 this IS a GN-style file name, and tells GN which source file to compile to
5417 make the .pch file used for subsequent compiles.
5418
5419 For example, if the toolchain specifies MSVC headers:
5420
5421 toolchain("vc_x64") {
5422 ...
5423 tool("cxx") {
5424 precompiled_header_type = "msvc"
5425 ...
5426
5427 You might make a config like this:
5428
5429 config("use_precompiled_headers") {
5430 precompiled_header = "build/precompile.h"
5431 precompiled_source = "//build/precompile.cc"
5432
5433 # Either your source files should #include "build/precompile.h"
5434 # first, or you can do this to force-include the header.
5435 cflags = [ "/FI$precompiled_header" ]
5436 }
5437
5438 And then define a target that uses the config:
5439
5440 executable("doom_melon") {
5441 configs += [ ":use_precompiled_headers" ]
5442 ...
5443```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005444### **precompiled_header_type**: [string] "gcc" or "msvc".
Brett Wilson796ed472018-07-16 15:11:09 -07005445
5446```
5447 See "gn help precompiled_header".
5448```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005449### **precompiled_source**: [file name] Source file to precompile.
Brett Wilson796ed472018-07-16 15:11:09 -07005450
5451```
5452 The source file that goes along with the precompiled_header when using
5453 "msvc"-style precompiled headers. It will be implicitly added to the sources
5454 of the target. See "gn help precompiled_header".
5455```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005456### **product_type**: Product type for Xcode projects.
Brett Wilson796ed472018-07-16 15:11:09 -07005457
5458```
5459 Correspond to the type of the product of a create_bundle target. Only
5460 meaningful to Xcode (used as part of the Xcode project generation).
5461
5462 When generating Xcode project files, only create_bundle target with a
5463 non-empty product_type will have a corresponding target in Xcode project.
5464```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005465### **public**: Declare public header files for a target.
Brett Wilson796ed472018-07-16 15:11:09 -07005466
5467```
5468 A list of files that other targets can include. These permissions are checked
5469 via the "check" command (see "gn help check").
5470
5471 If no public files are declared, other targets (assuming they have visibility
5472 to depend on this target) can include any file in the sources list. If this
5473 variable is defined on a target, dependent targets may only include files on
5474 this whitelist unless that target is marked as a friend (see "gn help
5475 friend").
5476
5477 Header file permissions are also subject to visibility. A target must be
5478 visible to another target to include any files from it at all and the public
5479 headers indicate which subset of those files are permitted. See "gn help
5480 visibility" for more.
5481
5482 Public files are inherited through the dependency tree. So if there is a
5483 dependency A -> B -> C, then A can include C's public headers. However, the
5484 same is NOT true of visibility, so unless A is in C's visibility list, the
5485 include will be rejected.
5486
5487 GN only knows about files declared in the "sources" and "public" sections of
5488 targets. If a file is included that is not known to the build, it will be
5489 allowed.
5490
5491 It is common for test targets to need to include private headers for their
5492 associated code. In this case, list the test target in the "friend" list of
5493 the target that owns the private header to allow the inclusion. See
5494 "gn help friend" for more.
Julie Hockette2a29402018-07-31 10:11:42 -07005495
5496 When a binary target has no explicit or implicit public headers (a "public"
5497 list is defined but is empty), GN assumes that the target can not propagate
5498 any compile-time dependencies up the dependency tree. In this case, the build
5499 can be parallelized more efficiently.
5500 Say there are dependencies:
5501 A (shared library) -> B (shared library) -> C (action).
5502 Normally C must complete before any source files in A can compile (because
5503 there might be generated includes). But when B explicitly declares no public
5504 headers, C can execute in parallel with A's compile steps. C must still be
5505 complete before any dependents link.
Brett Wilson796ed472018-07-16 15:11:09 -07005506```
5507
5508#### **Examples**
5509
5510```
5511 These exact files are public:
5512 public = [ "foo.h", "bar.h" ]
5513
5514 No files are public (no targets may include headers from this one):
Julie Hockette2a29402018-07-31 10:11:42 -07005515 # This allows starting compilation in dependent targets earlier.
Brett Wilson796ed472018-07-16 15:11:09 -07005516 public = []
5517```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005518### **public_configs**: Configs to be applied on dependents.
Brett Wilson796ed472018-07-16 15:11:09 -07005519
5520```
5521 A list of config labels.
5522
5523 Targets directly depending on this one will have the configs listed in this
5524 variable added to them. These configs will also apply to the current target.
Julie Hockette2a29402018-07-31 10:11:42 -07005525 Generally, public configs are used to apply defines and include directories
5526 necessary to compile this target's header files.
Brett Wilson796ed472018-07-16 15:11:09 -07005527
Julie Hockette2a29402018-07-31 10:11:42 -07005528 See also "gn help all_dependent_configs".
5529```
5530
5531#### **Propagation of public configs**
5532
5533```
5534 Public configs are applied to all targets that depend directly on this one.
5535 These dependant targets can further push this target's public configs
5536 higher in the dependency tree by depending on it via public_deps (see "gn
5537 help public_deps").
5538
5539 static_library("toplevel") {
5540 # This target will get "my_config" applied to it. However, since this
5541 # target uses "deps" and not "public_deps", targets that depend on this
5542 # one won't get it.
5543 deps = [ ":intermediate" ]
5544 }
5545
5546 static_library("intermediate") {
5547 # Depending on "lower" in any way will apply "my_config" to this target.
5548 # Additionall, since this target depends on "lower" via public_deps,
5549 # targets that depend on this one will also get "my_config".
5550 public_deps = [ ":lower" ]
5551 }
5552
5553 static_library("lower") {
5554 # This will get applied to all targets that depend on this one.
5555 public_configs = [ ":my_config" ]
5556 }
5557
5558 Public config propagation happens in a second phase once a target and all of
5559 its dependencies have been resolved. Therefore, a target will not see these
Brett Wilson796ed472018-07-16 15:11:09 -07005560 force-added configs in their "configs" variable while the script is running,
5561 and they can not be removed. As a result, this capability should generally
Julie Hockette2a29402018-07-31 10:11:42 -07005562 only be used to add defines and include directories rather than setting
5563 complicated flags that some targets may not want.
Brett Wilson796ed472018-07-16 15:11:09 -07005564
Julie Hockette2a29402018-07-31 10:11:42 -07005565 Public configs may or may not be propagated across toolchain boundaries
5566 depending on the value of the propagates_configs flag (see "gn help
5567 toolchain") on the toolchain of the target declaring the public_config.
5568```
5569
5570#### **Avoiding applying public configs to this target**
5571
5572```
5573 If you want the config to apply to targets that depend on this one, but NOT
5574 this one, define an extra layer of indirection using a group:
5575
5576 # External targets depend on this group.
5577 group("my_target") {
5578 # Config to apply to all targets that depend on this one.
5579 public_configs = [ ":external_settings" ]
5580 deps = [ ":internal_target" ]
5581 }
5582
5583 # Internal target to actually compile the sources.
5584 static_library("internal_target") {
5585 # Force all external targets to depend on the group instead of directly
5586 # on this so the "external_settings" config will get applied.
5587 visibility = [ ":my_target" ]
5588 ...
5589 }
Brett Wilson796ed472018-07-16 15:11:09 -07005590```
5591
5592#### **Ordering of flags and values**
5593
5594```
5595 1. Those set on the current target (not in a config).
5596 2. Those set on the "configs" on the target in order that the
5597 configs appear in the list.
5598 3. Those set on the "all_dependent_configs" on the target in order
5599 that the configs appear in the list.
5600 4. Those set on the "public_configs" on the target in order that
5601 those configs appear in the list.
5602 5. all_dependent_configs pulled from dependencies, in the order of
5603 the "deps" list. This is done recursively. If a config appears
5604 more than once, only the first occurence will be used.
5605 6. public_configs pulled from dependencies, in the order of the
5606 "deps" list. If a dependency is public, they will be applied
5607 recursively.
5608```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005609### **public_deps**: Declare public dependencies.
Brett Wilson796ed472018-07-16 15:11:09 -07005610
5611```
5612 Public dependencies are like private dependencies (see "gn help deps") but
5613 additionally express that the current target exposes the listed deps as part
5614 of its public API.
5615
5616 This has several ramifications:
5617
5618 - public_configs that are part of the dependency are forwarded to direct
5619 dependents.
5620
5621 - Public headers in the dependency are usable by dependents (includes do
5622 not require a direct dependency or visibility).
5623
5624 - If the current target is a shared library, other shared libraries that it
5625 publicly depends on (directly or indirectly) are propagated up the
5626 dependency tree to dependents for linking.
Julie Hockette2a29402018-07-31 10:11:42 -07005627
5628 See also "gn help public_configs".
Brett Wilson796ed472018-07-16 15:11:09 -07005629```
5630
5631#### **Discussion**
5632
5633```
5634 Say you have three targets: A -> B -> C. C's visibility may allow B to depend
5635 on it but not A. Normally, this would prevent A from including any headers
5636 from C, and C's public_configs would apply only to B.
5637
5638 If B lists C in its public_deps instead of regular deps, A will now inherit
5639 C's public_configs and the ability to include C's public headers.
5640
5641 Generally if you are writing a target B and you include C's headers as part
5642 of B's public headers, or targets depending on B should consider B and C to
5643 be part of a unit, you should use public_deps instead of deps.
5644```
5645
5646#### **Example**
5647
5648```
5649 # This target can include files from "c" but not from
5650 # "super_secret_implementation_details".
5651 executable("a") {
5652 deps = [ ":b" ]
5653 }
5654
5655 shared_library("b") {
5656 deps = [ ":super_secret_implementation_details" ]
5657 public_deps = [ ":c" ]
5658 }
5659```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005660### **rebase**: Rebase collected metadata as files.
Nate Fischer8ed01d32019-01-08 17:32:01 -08005661
5662```
5663 A boolean that triggers a rebase of collected metadata strings based on their
5664 declared file. Defaults to false.
5665
5666 Metadata generally declares files as strings relative to the local build file.
5667 However, this data is often used in other contexts, and so setting this flag
5668 will force the metadata collection to be rebased according to the local build
5669 file's location and thus allow the filename to be used anywhere.
5670
5671 Setting this flag will raise an error if any target's specified metadata is
5672 not a string value.
5673
5674 See also "gn help generated_file".
5675```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005676### **response_file_contents**: Contents of a response file for actions.
Brett Wilson796ed472018-07-16 15:11:09 -07005677
5678```
5679 Sometimes the arguments passed to a script can be too long for the system's
5680 command-line capabilities. This is especially the case on Windows where the
5681 maximum command-line length is less than 8K. A response file allows you to
5682 pass an unlimited amount of data to a script in a temporary file for an
5683 action or action_foreach target.
5684
5685 If the response_file_contents variable is defined and non-empty, the list
5686 will be treated as script args (including possibly substitution patterns)
5687 that will be written to a temporary file at build time. The name of the
5688 temporary file will be substituted for "{{response_file_name}}" in the script
5689 args.
5690
5691 The response file contents will always be quoted and escaped according to
5692 Unix shell rules. To parse the response file, the Python script should use
5693 "shlex.split(file_contents)".
5694```
5695
5696#### **Example**
5697
5698```
5699 action("process_lots_of_files") {
5700 script = "process.py",
5701 inputs = [ ... huge list of files ... ]
5702
5703 # Write all the inputs to a response file for the script. Also,
5704 # make the paths relative to the script working directory.
5705 response_file_contents = rebase_path(inputs, root_build_dir)
5706
5707 # The script expects the name of the response file in --file-list.
5708 args = [
5709 "--enable-foo",
5710 "--file-list={{response_file_name}}",
5711 ]
5712 }
5713```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005714### **script**: Script file for actions.
Brett Wilson796ed472018-07-16 15:11:09 -07005715
5716```
5717 An absolute or buildfile-relative file name of a Python script to run for a
5718 action and action_foreach targets (see "gn help action" and "gn help
5719 action_foreach").
5720```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005721### **sources**: Source files for a target
Brett Wilson796ed472018-07-16 15:11:09 -07005722
5723```
5724 A list of files. Non-absolute paths will be resolved relative to the current
5725 build file.
5726```
5727
5728#### **Sources for binary targets**
5729
5730```
5731 For binary targets (source sets, executables, and libraries), the known file
5732 types will be compiled with the associated tools. Unknown file types and
5733 headers will be skipped. However, you should still list all C/C+ header files
5734 so GN knows about the existence of those files for the purposes of include
5735 checking.
5736
5737 As a special case, a file ending in ".def" will be treated as a Windows
5738 module definition file. It will be appended to the link line with a
5739 preceding "/DEF:" string. There must be at most one .def file in a target
5740 and they do not cross dependency boundaries (so specifying a .def file in a
5741 static library or source set will have no effect on the executable or shared
5742 library they're linked into).
5743```
5744
5745#### **Sources for non-binary targets**
5746
5747```
5748 action_foreach
5749 The sources are the set of files that the script will be executed over. The
5750 script will run once per file.
5751
5752 action
5753 The sources will be treated the same as inputs. See "gn help inputs" for
5754 more information and usage advice.
5755
5756 copy
5757 The source are the source files to copy.
5758```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005759### **testonly**: Declares a target must only be used for testing.
Brett Wilson796ed472018-07-16 15:11:09 -07005760
5761```
5762 Boolean. Defaults to false.
5763
5764 When a target is marked "testonly = true", it must only be depended on by
5765 other test-only targets. Otherwise, GN will issue an error that the
5766 depenedency is not allowed.
5767
5768 This feature is intended to prevent accidentally shipping test code in a
5769 final product.
5770```
5771
5772#### **Example**
5773
5774```
5775 source_set("test_support") {
5776 testonly = true
5777 ...
5778 }
5779```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005780### **visibility**: A list of labels that can depend on a target.
Brett Wilson796ed472018-07-16 15:11:09 -07005781
5782```
5783 A list of labels and label patterns that define which targets can depend on
5784 the current one. These permissions are checked via the "check" command (see
5785 "gn help check").
5786
5787 If visibility is not defined, it defaults to public ("*").
5788
5789 If visibility is defined, only the targets with labels that match it can
5790 depend on the current target. The empty list means no targets can depend on
5791 the current target.
5792
5793 Tip: Often you will want the same visibility for all targets in a BUILD file.
5794 In this case you can just put the definition at the top, outside of any
5795 target, and the targets will inherit that scope and see the definition.
5796```
5797
5798#### **Patterns**
5799
5800```
5801 See "gn help label_pattern" for more details on what types of patterns are
5802 supported. If a toolchain is specified, only targets in that toolchain will
5803 be matched. If a toolchain is not specified on a pattern, targets in all
5804 toolchains will be matched.
5805```
5806
5807#### **Examples**
5808
5809```
5810 Only targets in the current buildfile ("private"):
5811 visibility = [ ":*" ]
5812
5813 No targets (used for targets that should be leaf nodes):
5814 visibility = []
5815
5816 Any target ("public", the default):
5817 visibility = [ "*" ]
5818
5819 All targets in the current directory and any subdirectory:
5820 visibility = [ "./*" ]
5821
5822 Any target in "//bar/BUILD.gn":
5823 visibility = [ "//bar:*" ]
5824
5825 Any target in "//bar/" or any subdirectory thereof:
5826 visibility = [ "//bar/*" ]
5827
5828 Just these specific targets:
5829 visibility = [ ":mything", "//foo:something_else" ]
5830
5831 Any target in the current directory and any subdirectory thereof, plus
5832 any targets in "//bar/" and any subdirectory thereof.
5833 visibility = [ "./*", "//bar/*" ]
5834```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005835### **walk_keys**: Key(s) for managing the metadata collection walk.
Nate Fischer8ed01d32019-01-08 17:32:01 -08005836
5837```
5838 Defaults to [].
5839
5840 These keys are used to control the next step in a collection walk, acting as
5841 barriers. If a specified key is defined in a target's metadata, the walk will
5842 use the targets listed in that value to determine which targets are walked.
5843
5844 If no walk_keys are specified for a generated_file target (i.e. "[]"), the
5845 walk will touch all deps and data_deps of the specified target recursively.
5846
5847 See "gn help generated_file".
5848```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005849### **write_runtime_deps**: Writes the target's runtime_deps to the given path.
Brett Wilson796ed472018-07-16 15:11:09 -07005850
5851```
5852 Does not synchronously write the file, but rather schedules it to be written
5853 at the end of generation.
5854
5855 If the file exists and the contents are identical to that being written, the
5856 file will not be updated. This will prevent unnecessary rebuilds of targets
5857 that depend on this file.
5858
5859 Path must be within the output directory.
5860
5861 See "gn help runtime_deps" for how the runtime dependencies are computed.
5862
5863 The format of this file will list one file per line with no escaping. The
5864 files will be relative to the root_build_dir. The first line of the file will
5865 be the main output file of the target itself. The file contents will be the
5866 same as requesting the runtime deps be written on the command line (see "gn
5867 help --runtime-deps-list-file").
5868```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005869### **xcode_extra_attributes**: [scope] Extra attributes for Xcode projects.
Brett Wilson796ed472018-07-16 15:11:09 -07005870
5871```
5872 The value defined in this scope will be copied to the EXTRA_ATTRIBUTES
5873 property of the generated Xcode project. They are only meaningful when
5874 generating with --ide=xcode.
5875
5876 See "gn help create_bundle" for more information.
5877```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08005878### **xcode_test_application_name**: Name for Xcode test target.
Brett Wilson796ed472018-07-16 15:11:09 -07005879
5880```
5881 Each unit and ui test target must have a test application target, and this
5882 value is used to specify the relationship. Only meaningful to Xcode (used as
5883 part of the Xcode project generation).
5884
5885 See "gn help create_bundle" for more information.
5886```
5887
Julie Hockette2a29402018-07-31 10:11:42 -07005888#### **Example**
Brett Wilson796ed472018-07-16 15:11:09 -07005889
5890```
5891 create_bundle("chrome_xctest") {
5892 test_application_name = "chrome"
5893 ...
5894 }
5895```
5896## Other help topics
5897
5898### **Build Arguments Overview**
5899
5900```
5901 Build arguments are variables passed in from outside of the build that build
5902 files can query to determine how the build works.
5903```
5904
5905#### **How build arguments are set**
5906
5907```
5908 First, system default arguments are set based on the current system. The
5909 built-in arguments are:
5910 - host_cpu
5911 - host_os
5912 - current_cpu
5913 - current_os
5914 - target_cpu
5915 - target_os
5916
5917 Next, project-specific overrides are applied. These are specified inside
5918 the default_args variable of //.gn. See "gn help dotfile" for more.
5919
5920 If specified, arguments from the --args command line flag are used. If that
5921 flag is not specified, args from previous builds in the build directory will
5922 be used (this is in the file args.gn in the build directory).
5923
5924 Last, for targets being compiled with a non-default toolchain, the toolchain
5925 overrides are applied. These are specified in the toolchain_args section of a
5926 toolchain definition. The use-case for this is that a toolchain may be
5927 building code for a different platform, and that it may want to always
5928 specify Posix, for example. See "gn help toolchain" for more.
5929
5930 If you specify an override for a build argument that never appears in a
5931 "declare_args" call, a nonfatal error will be displayed.
5932```
5933
5934#### **Examples**
5935
5936```
5937 gn args out/FooBar
5938 Create the directory out/FooBar and open an editor. You would type
5939 something like this into that file:
5940 enable_doom_melon=false
5941 os="android"
5942
5943 gn gen out/FooBar --args="enable_doom_melon=true os=\"android\""
5944 This will overwrite the build directory with the given arguments. (Note
5945 that the quotes inside the args command will usually need to be escaped
5946 for your shell to pass through strings values.)
5947```
5948
5949#### **How build arguments are used**
5950
5951```
5952 If you want to use an argument, you use declare_args() and specify default
5953 values. These default values will apply if none of the steps listed in the
5954 "How build arguments are set" section above apply to the given argument, but
5955 the defaults will not override any of these.
5956
5957 Often, the root build config file will declare global arguments that will be
5958 passed to all buildfiles. Individual build files can also specify arguments
5959 that apply only to those files. It is also useful to specify build args in an
5960 "import"-ed file if you want such arguments to apply to multiple buildfiles.
5961```
5962### **.gn file**
5963
5964```
5965 When gn starts, it will search the current directory and parent directories
5966 for a file called ".gn". This indicates the source root. You can override
5967 this detection by using the --root command-line argument
5968
5969 The .gn file in the source root will be executed. The syntax is the same as a
5970 buildfile, but with very limited build setup-specific meaning.
5971
5972 If you specify --root, by default GN will look for the file .gn in that
5973 directory. If you want to specify a different file, you can additionally pass
5974 --dotfile:
5975
5976 gn gen out/Debug --root=/home/build --dotfile=/home/my_gn_file.gn
5977```
5978
5979#### **Variables**
5980
5981```
5982 arg_file_template [optional]
5983 Path to a file containing the text that should be used as the default
5984 args.gn content when you run `gn args`.
5985
5986 buildconfig [required]
5987 Path to the build config file. This file will be used to set up the
5988 build file execution environment for each toolchain.
5989
5990 check_targets [optional]
5991 A list of labels and label patterns that should be checked when running
5992 "gn check" or "gn gen --check". If unspecified, all targets will be
Nate Fischer8ed01d32019-01-08 17:32:01 -08005993 checked. If it is the empty list, no targets will be checked. To
5994 bypass this list, request an explicit check of targets, like "//*".
Brett Wilson796ed472018-07-16 15:11:09 -07005995
5996 The format of this list is identical to that of "visibility" so see "gn
5997 help visibility" for examples.
5998
5999 exec_script_whitelist [optional]
6000 A list of .gn/.gni files (not labels) that have permission to call the
6001 exec_script function. If this list is defined, calls to exec_script will
6002 be checked against this list and GN will fail if the current file isn't
6003 in the list.
6004
6005 This is to allow the use of exec_script to be restricted since is easy to
6006 use inappropriately. Wildcards are not supported. Files in the
6007 secondary_source tree (if defined) should be referenced by ignoring the
6008 secondary tree and naming them as if they are in the main tree.
6009
6010 If unspecified, the ability to call exec_script is unrestricted.
6011
6012 Example:
6013 exec_script_whitelist = [
6014 "//base/BUILD.gn",
6015 "//build/my_config.gni",
6016 ]
6017
6018 root [optional]
6019 Label of the root build target. The GN build will start by loading the
6020 build file containing this target name. This defaults to "//:" which will
6021 cause the file //BUILD.gn to be loaded.
6022
6023 script_executable [optional]
6024 Path to specific Python executable or potentially a different language
6025 interpreter that is used to execute scripts in action targets and
6026 exec_script calls.
6027
6028 secondary_source [optional]
6029 Label of an alternate directory tree to find input files. When searching
6030 for a BUILD.gn file (or the build config file discussed above), the file
6031 will first be looked for in the source root. If it's not found, the
6032 secondary source root will be checked (which would contain a parallel
6033 directory hierarchy).
6034
6035 This behavior is intended to be used when BUILD.gn files can't be checked
6036 in to certain source directories for whatever reason.
6037
6038 The secondary source root must be inside the main source tree.
6039
6040 default_args [optional]
6041 Scope containing the default overrides for declared arguments. These
6042 overrides take precedence over the default values specified in the
6043 declare_args() block, but can be overriden using --args or the
6044 args.gn file.
6045
6046 This is intended to be used when subprojects declare arguments with
6047 default values that need to be changed for whatever reason.
6048```
6049
6050#### **Example .gn file contents**
6051
6052```
6053 buildconfig = "//build/config/BUILDCONFIG.gn"
6054
6055 check_targets = [
6056 "//doom_melon/*", # Check everything in this subtree.
6057 "//tools:mind_controlling_ant", # Check this specific target.
6058 ]
6059
6060 root = "//:root"
6061
6062 secondary_source = "//build/config/temporary_buildfiles/"
6063
6064 default_args = {
6065 # Default to release builds for this project.
6066 is_debug = false
6067 is_component_build = false
6068 }
6069```
6070### **Build graph and execution overview**
6071
6072#### **Overall build flow**
6073
6074```
6075 1. Look for ".gn" file (see "gn help dotfile") in the current directory and
6076 walk up the directory tree until one is found. Set this directory to be
6077 the "source root" and interpret this file to find the name of the build
6078 config file.
6079
6080 2. Execute the build config file identified by .gn to set up the global
6081 variables and default toolchain name. Any arguments, variables, defaults,
6082 etc. set up in this file will be visible to all files in the build.
6083
6084 3. Load the //BUILD.gn (in the source root directory).
6085
6086 4. Recursively evaluate rules and load BUILD.gn in other directories as
6087 necessary to resolve dependencies. If a BUILD file isn't found in the
6088 specified location, GN will look in the corresponding location inside
6089 the secondary_source defined in the dotfile (see "gn help dotfile").
6090
6091 5. When a target's dependencies are resolved, write out the `.ninja`
6092 file to disk.
6093
6094 6. When all targets are resolved, write out the root build.ninja file.
6095```
6096
6097#### **Executing target definitions and templates**
6098
6099```
6100 Build files are loaded in parallel. This means it is impossible to
6101 interrogate a target from GN code for any information not derivable from its
6102 label (see "gn help label"). The exception is the get_target_outputs()
6103 function which requires the target being interrogated to have been defined
6104 previously in the same file.
6105
6106 Targets are declared by their type and given a name:
6107
6108 static_library("my_static_library") {
6109 ... target parameter definitions ...
6110 }
6111
6112 There is also a generic "target" function for programmatically defined types
6113 (see "gn help target"). You can define new types using templates (see "gn
6114 help template"). A template defines some custom code that expands to one or
6115 more other targets.
6116
6117 Before executing the code inside the target's { }, the target defaults are
6118 applied (see "gn help set_defaults"). It will inject implicit variable
6119 definitions that can be overridden by the target code as necessary. Typically
6120 this mechanism is used to inject a default set of configs that define the
6121 global compiler and linker flags.
6122```
6123
6124#### **Which targets are built**
6125
6126```
6127 All targets encountered in the default toolchain (see "gn help toolchain")
6128 will have build rules generated for them, even if no other targets reference
6129 them. Their dependencies must resolve and they will be added to the implicit
6130 "all" rule (see "gn help ninja_rules").
6131
6132 Targets in non-default toolchains will only be generated when they are
6133 required (directly or transitively) to build a target in the default
6134 toolchain.
6135
6136 See also "gn help ninja_rules".
6137```
6138
6139#### **Dependencies**
6140
6141```
6142 The only difference between "public_deps" and "deps" except for pushing
6143 configs around the build tree and allowing includes for the purposes of "gn
6144 check".
6145
6146 A target's "data_deps" are guaranteed to be built whenever the target is
6147 built, but the ordering is not defined. The meaning of this is dependencies
6148 required at runtime. Currently data deps will be complete before the target
6149 is linked, but this is not semantically guaranteed and this is undesirable
6150 from a build performance perspective. Since we hope to change this in the
6151 future, do not rely on this behavior.
6152```
6153### **Language and grammar for GN build files**
6154
6155#### **Tokens**
6156
6157```
6158 GN build files are read as sequences of tokens. While splitting the file
6159 into tokens, the next token is the longest sequence of characters that form a
6160 valid token.
6161```
6162
6163#### **White space and comments**
6164
6165```
6166 White space is comprised of spaces (U+0020), horizontal tabs (U+0009),
6167 carriage returns (U+000D), and newlines (U+000A).
6168
6169 Comments start at the character "#" and stop at the next newline.
6170
6171 White space and comments are ignored except that they may separate tokens
6172 that would otherwise combine into a single token.
6173```
6174
6175#### **Identifiers**
6176
6177```
6178 Identifiers name variables and functions.
6179
6180 identifier = letter { letter | digit } .
6181 letter = "A" ... "Z" | "a" ... "z" | "_" .
6182 digit = "0" ... "9" .
6183```
6184
6185#### **Keywords**
6186
6187```
6188 The following keywords are reserved and may not be used as identifiers:
6189
6190 else false if true
6191```
6192
6193#### **Integer literals**
6194
6195```
6196 An integer literal represents a decimal integer value.
6197
6198 integer = [ "-" ] digit { digit } .
6199
6200 Leading zeros and negative zero are disallowed.
6201```
6202
6203#### **String literals**
6204
6205```
6206 A string literal represents a string value consisting of the quoted
6207 characters with possible escape sequences and variable expansions.
6208
6209 string = `"` { char | escape | expansion } `"` .
6210 escape = `\` ( "$" | `"` | char ) .
6211 BracketExpansion = "{" ( identifier | ArrayAccess | ScopeAccess "
6212 ") "}" .
6213 Hex = "0x" [0-9A-Fa-f][0-9A-Fa-f]
6214 expansion = "$" ( identifier | BracketExpansion | Hex ) .
6215 char = /* any character except "$", `"`, or newline "
6216 "*/ .
6217
6218 After a backslash, certain sequences represent special characters:
6219
6220 \" U+0022 quotation mark
6221 \$ U+0024 dollar sign
6222 \\ U+005C backslash
6223
6224 All other backslashes represent themselves.
6225
6226 To insert an arbitrary byte value, use $0xFF. For example, to insert a
6227 newline character: "Line one$0x0ALine two".
6228
6229 An expansion will evaluate the variable following the '$' and insert a
6230 stringified version of it into the result. For example, to concat two path
6231 components with a slash separating them:
6232 "$var_one/$var_two"
6233 Use the "${var_one}" format to be explicitly deliniate the variable for
6234 otherwise-ambiguous cases.
6235```
6236
6237#### **Punctuation**
6238
6239```
6240 The following character sequences represent punctuation:
6241
6242 + += == != ( )
6243 - -= < <= [ ]
6244 ! = > >= { }
6245 && || . ,
6246```
6247
6248#### **Grammar**
6249
6250```
6251 The input tokens form a syntax tree following a context-free grammar:
6252
6253 File = StatementList .
6254
6255 Statement = Assignment | Call | Condition .
6256 LValue = identifier | ArrayAccess | ScopeAccess .
6257 Assignment = LValue AssignOp Expr .
6258 Call = identifier "(" [ ExprList ] ")" [ Block ] .
6259 Condition = "if" "(" Expr ")" Block
6260 [ "else" ( Condition | Block ) ] .
6261 Block = "{" StatementList "}" .
6262 StatementList = { Statement } .
6263
6264 ArrayAccess = identifier "[" Expr "]" .
6265 ScopeAccess = identifier "." identifier .
6266 Expr = UnaryExpr | Expr BinaryOp Expr .
6267 UnaryExpr = PrimaryExpr | UnaryOp UnaryExpr .
6268 PrimaryExpr = identifier | integer | string | Call
6269 | ArrayAccess | ScopeAccess | Block
6270 | "(" Expr ")"
6271 | "[" [ ExprList [ "," ] ] "]" .
6272 ExprList = Expr { "," Expr } .
6273
6274 AssignOp = "=" | "+=" | "-=" .
6275 UnaryOp = "!" .
6276 BinaryOp = "+" | "-" // highest priority
6277 | "<" | "<=" | ">" | ">="
6278 | "==" | "!="
6279 | "&&"
6280 | "||" . // lowest priority
6281
6282 All binary operators are left-associative.
6283```
6284
6285#### **Types**
6286
6287```
6288 The GN language is dynamically typed. The following types are used:
6289
6290 - Boolean: Uses the keywords "true" and "false". There is no implicit
6291 conversion between booleans and integers.
6292
6293 - Integers: All numbers in GN are signed 64-bit integers.
6294
6295 - Strings: Strings are 8-bit with no enforced encoding. When a string is
6296 used to interact with other systems with particular encodings (like the
6297 Windows and Mac filesystems) it is assumed to be UTF-8. See "String
6298 literals" above for more.
6299
6300 - Lists: Lists are arbitrary-length ordered lists of values. See "Lists"
6301 below for more.
6302
6303 - Scopes: Scopes are like dictionaries that use variable names for keys. See
6304 "Scopes" below for more.
6305```
6306
6307#### **Lists**
6308
6309```
6310 Lists are created with [] and using commas to separate items:
6311
6312 mylist = [ 0, 1, 2, "some string" ]
6313
6314 A comma after the last item is optional. Lists are dereferenced using 0-based
6315 indexing:
6316
6317 mylist[0] += 1
6318 var = mylist[2]
6319
6320 Lists can be concatenated using the '+' and '+=' operators. Bare values can
6321 not be concatenated with lists, to add a single item, it must be put into a
6322 list of length one.
6323
6324 Items can be removed from lists using the '-' and '-=' operators. This will
6325 remove all occurrences of every item in the right-hand list from the
6326 left-hand list. It is an error to remove an item not in the list. This is to
6327 prevent common typos and to detect dead code that is removing things that no
6328 longer apply.
6329
6330 It is an error to use '=' to replace a nonempty list with another nonempty
6331 list. This is to prevent accidentally overwriting data when in most cases
6332 '+=' was intended. To overwrite a list on purpose, first assign it to the
6333 empty list:
6334
6335 mylist = []
6336 mylist = otherlist
6337
6338 When assigning to a list named 'sources' using '=' or '+=', list items may be
6339 automatically filtered out. See "gn help set_sources_assignment_filter" for
6340 more.
6341```
6342
6343#### **Scopes**
6344
6345```
6346 All execution happens in the context of a scope which holds the current state
6347 (like variables). With the exception of loops and conditions, '{' introduces
6348 a new scope that has a parent reference to the old scope.
6349
6350 Variable reads recursively search all nested scopes until the variable is
6351 found or there are no more scopes. Variable writes always go into the current
6352 scope. This means that after the closing '}' (again excepting loops and
6353 conditions), all local variables will be restored to the previous values.
6354 This also means that "foo = foo" can do useful work by copying a variable
6355 into the current scope that was defined in a containing scope.
6356
6357 Scopes can also be assigned to variables. Such scopes can be created by
6358 functions like exec_script, when invoking a template (the template code
6359 refers to the variables set by the invoking code by the implicitly-created
6360 "invoker" scope), or explicitly like:
6361
6362 empty_scope = {}
6363 myvalues = {
6364 foo = 21
6365 bar = "something"
6366 }
6367
6368 Inside such a scope definition can be any GN code including conditionals and
6369 function calls. After the close of the scope, it will contain all variables
6370 explicitly set by the code contained inside it. After this, the values can be
6371 read, modified, or added to:
6372
6373 myvalues.foo += 2
6374 empty_scope.new_thing = [ 1, 2, 3 ]
Nate Fischer8ed01d32019-01-08 17:32:01 -08006375
6376 Scope equality is defined as single-level scopes identical within the current
6377 scope. That is, all values in the first scope must be present and identical
6378 within the second, and vice versa. Note that this means inherited scopes are
6379 always unequal by definition.
Brett Wilson796ed472018-07-16 15:11:09 -07006380```
Julie Hockettd69a9c32019-01-23 14:36:18 -08006381### **Input and output conversion**
Brett Wilson796ed472018-07-16 15:11:09 -07006382
6383```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08006384 Input and output conversions are arguments to file and process functions
6385 that specify how to convert data to or from external formats. The possible
6386 values for parameters specifying conversions are:
6387
Brett Wilson796ed472018-07-16 15:11:09 -07006388 "" (the default)
Julie Hockett09171292018-07-31 14:35:10 -07006389 input: Discard the result and return None.
6390
6391 output: If value is a list, then "list lines"; otherwise "value".
Brett Wilson796ed472018-07-16 15:11:09 -07006392
6393 "list lines"
Julie Hockett09171292018-07-31 14:35:10 -07006394 input:
6395 Return the file contents as a list, with a string for each line. The
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08006396 newlines will not be present in the result. The last line may or may
6397 not end in a newline.
Brett Wilson796ed472018-07-16 15:11:09 -07006398
Julie Hockett09171292018-07-31 14:35:10 -07006399 After splitting, each individual line will be trimmed of whitespace on
6400 both ends.
6401
6402 output:
6403 Renders the value contents as a list, with a string for each line. The
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08006404 newlines will not be present in the result. The last line will end in
6405 with a newline.
Brett Wilson796ed472018-07-16 15:11:09 -07006406
6407 "scope"
Julie Hockett09171292018-07-31 14:35:10 -07006408 input:
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08006409 Execute the block as GN code and return a scope with the resulting
6410 values in it. If the input was:
Julie Hockett09171292018-07-31 14:35:10 -07006411 a = [ "hello.cc", "world.cc" ]
6412 b = 26
6413 and you read the result into a variable named "val", then you could
6414 access contents the "." operator on "val":
6415 sources = val.a
6416 some_count = val.b
6417
6418 output:
6419 Renders the value contents as a GN code block, reversing the input
6420 result above.
Brett Wilson796ed472018-07-16 15:11:09 -07006421
6422 "string"
Julie Hockett09171292018-07-31 14:35:10 -07006423 input: Return the file contents into a single string.
6424
6425 output:
6426 Render the value contents into a single string. The output is:
6427 a string renders with quotes, e.g. "str"
6428 an integer renders as a stringified integer, e.g. "6"
6429 a boolean renders as the associated string, e.g. "true"
6430 a list renders as a representation of its contents, e.g. "[\"str\", 6]"
6431 a scope renders as a GN code block of its values. If the Value was:
6432 Value val;
6433 val.a = [ "hello.cc", "world.cc" ];
6434 val.b = 26
6435 the resulting output would be:
6436 "{
6437 a = [ \"hello.cc\", \"world.cc\" ]
6438 b = 26
6439 }"
Brett Wilson796ed472018-07-16 15:11:09 -07006440
6441 "value"
Julie Hockett09171292018-07-31 14:35:10 -07006442 input:
6443 Parse the input as if it was a literal rvalue in a buildfile. Examples of
6444 typical program output using this mode:
6445 [ "foo", "bar" ] (result will be a list)
6446 or
6447 "foo bar" (result will be a string)
6448 or
6449 5 (result will be an integer)
Brett Wilson796ed472018-07-16 15:11:09 -07006450
Julie Hockett09171292018-07-31 14:35:10 -07006451 Note that if the input is empty, the result will be a null value which
6452 will produce an error if assigned to a variable.
6453
6454 output:
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08006455 Render the value contents as a literal rvalue. Strings render with
6456 escaped quotes.
Brett Wilson796ed472018-07-16 15:11:09 -07006457
6458 "json"
Julie Hockett09171292018-07-31 14:35:10 -07006459 input: Parse the input as a JSON and convert it to equivalent GN rvalue.
6460
6461 output: Convert the Value to equivalent JSON value.
6462
6463 The data type mapping is:
Brett Wilson796ed472018-07-16 15:11:09 -07006464 a string in JSON maps to string in GN
6465 an integer in JSON maps to integer in GN
6466 a float in JSON is unsupported and will result in an error
6467 an object in JSON maps to scope in GN
6468 an array in JSON maps to list in GN
6469 a boolean in JSON maps to boolean in GN
6470 a null in JSON is unsupported and will result in an error
6471
Julie Hockett09171292018-07-31 14:35:10 -07006472 Nota that the input dictionary keys have to be valid GN identifiers
6473 otherwise they will produce an error.
Brett Wilson796ed472018-07-16 15:11:09 -07006474
Julie Hockett09171292018-07-31 14:35:10 -07006475 "trim ..." (input only)
Brett Wilson796ed472018-07-16 15:11:09 -07006476 Prefixing any of the other transformations with the word "trim" will
6477 result in whitespace being trimmed from the beginning and end of the
6478 result before processing.
6479
6480 Examples: "trim string" or "trim list lines"
6481
6482 Note that "trim value" is useless because the value parser skips
6483 whitespace anyway.
6484```
6485### **Label patterns**
6486
6487```
6488 A label pattern is a way of expressing one or more labels in a portion of the
6489 source tree. They are not general regular expressions.
6490
6491 They can take the following forms only:
6492
6493 - Explicit (no wildcard):
6494 "//foo/bar:baz"
6495 ":baz"
6496
6497 - Wildcard target names:
6498 "//foo/bar:*" (all targets in the //foo/bar/BUILD.gn file)
6499 ":*" (all targets in the current build file)
6500
6501 - Wildcard directory names ("*" is only supported at the end)
6502 "*" (all targets)
6503 "//foo/bar/*" (all targets in any subdir of //foo/bar)
6504 "./*" (all targets in the current build file or sub dirs)
6505
Julie Hockette2a29402018-07-31 10:11:42 -07006506 Any of the above forms can additionally take an explicit toolchain
6507 in parenthesis at the end of the label pattern. In this case, the
6508 toolchain must be fully qualified (no wildcards are supported in the
6509 toolchain name).
Brett Wilson796ed472018-07-16 15:11:09 -07006510
Julie Hockette2a29402018-07-31 10:11:42 -07006511 "//foo:bar(//build/toolchain:mac)"
Brett Wilson796ed472018-07-16 15:11:09 -07006512 An explicit target in an explicit toolchain.
6513
6514 ":*(//build/toolchain/linux:32bit)"
6515 All targets in the current build file using the 32-bit Linux toolchain.
6516
6517 "//foo/*(//build/toolchain:win)"
6518 All targets in //foo and any subdirectory using the Windows
6519 toolchain.
6520```
6521### **About labels**
6522
6523```
6524 Everything that can participate in the dependency graph (targets, configs,
6525 and toolchains) are identified by labels. A common label looks like:
6526
6527 //base/test:test_support
6528
6529 This consists of a source-root-absolute path, a colon, and a name. This means
6530 to look for the thing named "test_support" in "base/test/BUILD.gn".
6531
6532 You can also specify system absolute paths if necessary. Typically such
6533 paths would be specified via a build arg so the developer can specify where
6534 the component is on their system.
6535
6536 /usr/local/foo:bar (Posix)
6537 /C:/Program Files/MyLibs:bar (Windows)
6538```
6539
6540#### **Toolchains**
6541
6542```
6543 A canonical label includes the label of the toolchain being used. Normally,
6544 the toolchain label is implicitly inherited from the current execution
6545 context, but you can override this to specify cross-toolchain dependencies:
6546
6547 //base/test:test_support(//build/toolchain/win:msvc)
6548
6549 Here GN will look for the toolchain definition called "msvc" in the file
6550 "//build/toolchain/win" to know how to compile this target.
6551```
6552
6553#### **Relative labels**
6554
6555```
6556 If you want to refer to something in the same buildfile, you can omit
6557 the path name and just start with a colon. This format is recommended for
6558 all same-file references.
6559
6560 :base
6561
6562 Labels can be specified as being relative to the current directory.
6563 Stylistically, we prefer to use absolute paths for all non-file-local
6564 references unless a build file needs to be run in different contexts (like a
6565 project needs to be both standalone and pulled into other projects in
6566 difference places in the directory hierarchy).
6567
6568 source/plugin:myplugin
6569 ../net:url_request
6570```
6571
6572#### **Implicit names**
6573
6574```
6575 If a name is unspecified, it will inherit the directory name. Stylistically,
6576 we prefer to omit the colon and name when possible:
6577
6578 //net -> //net:net
6579 //tools/gn -> //tools/gn:gn
6580```
6581### **Ninja build rules**
6582
6583#### **The "all" and "default" rules**
6584
6585```
6586 All generated targets (see "gn help execution") will be added to an implicit
6587 build rule called "all" so "ninja all" will always compile everything. The
6588 default rule will be used by Ninja if no specific target is specified (just
6589 typing "ninja"). If there is a target named "default" in the root build file,
6590 it will be the default build rule, otherwise the implicit "all" rule will be
6591 used.
6592```
6593
6594#### **Phony rules**
6595
6596```
6597 GN generates Ninja "phony" rules for targets in the default toolchain. The
6598 phony rules can collide with each other and with the names of generated files
6599 so are generated with the following priority:
6600
6601 1. Actual files generated by the build always take precedence.
6602
6603 2. Targets in the toplevel //BUILD.gn file.
6604
6605 3. Targets in toplevel directories matching the names of the directories.
6606 So "ninja foo" can be used to compile "//foo:foo". This only applies to
6607 the first level of directories since usually these are the most
6608 important (so this won't apply to "//foo/bar:bar").
6609
6610 4. The short names of executables if there is only one executable with that
6611 short name. Use "ninja doom_melon" to compile the
6612 "//tools/fruit:doom_melon" executable.
6613
6614 5. The short names of all targets if there is only one target with that
6615 short name.
6616
6617 6. Full label name with no leading slashes. So you can use
6618 "ninja tools/fruit:doom_melon" to build "//tools/fruit:doom_melon".
6619
6620 7. Labels with an implicit name part (when the short names match the
6621 directory). So you can use "ninja foo/bar" to compile "//foo/bar:bar".
6622
6623 These "phony" rules are provided only for running Ninja since this matches
6624 people's historical expectations for building. For consistency with the rest
6625 of the program, GN introspection commands accept explicit labels.
6626
6627 To explicitly compile a target in a non-default toolchain, you must give
6628 Ninja the exact name of the output file relative to the build directory.
6629```
6630### **nogncheck**: Skip an include line from checking.
6631
6632```
6633 GN's header checker helps validate that the includes match the build
6634 dependency graph. Sometimes an include might be conditional or otherwise
6635 problematic, but you want to specifically allow it. In this case, it can be
6636 whitelisted.
6637
6638 Include lines containing the substring "nogncheck" will be excluded from
6639 header checking. The most common case is a conditional include:
6640
6641 #if defined(ENABLE_DOOM_MELON)
6642 #include "tools/doom_melon/doom_melon.h" // nogncheck
6643 #endif
6644
6645 If the build file has a conditional dependency on the corresponding target
6646 that matches the conditional include, everything will always link correctly:
6647
6648 source_set("mytarget") {
6649 ...
6650 if (enable_doom_melon) {
6651 defines = [ "ENABLE_DOOM_MELON" ]
6652 deps += [ "//tools/doom_melon" ]
6653 }
6654
6655 But GN's header checker does not understand preprocessor directives, won't
6656 know it matches the build dependencies, and will flag this include as
6657 incorrect when the condition is false.
6658```
6659
6660#### **More information**
6661
6662```
6663 The topic "gn help check" has general information on how checking works and
6664 advice on fixing problems. Targets can also opt-out of checking, see
6665 "gn help check_includes".
6666```
Brett Wilson796ed472018-07-16 15:11:09 -07006667### **Runtime dependencies**
6668
6669```
6670 Runtime dependencies of a target are exposed via the "runtime_deps" category
6671 of "gn desc" (see "gn help desc") or they can be written at build generation
6672 time via write_runtime_deps(), or --runtime-deps-list-file (see "gn help
6673 --runtime-deps-list-file").
6674
6675 To a first approximation, the runtime dependencies of a target are the set of
6676 "data" files, data directories, and the shared libraries from all transitive
6677 dependencies. Executables, shared libraries, and loadable modules are
6678 considered runtime dependencies of themselves.
6679```
6680
6681#### **Executables**
6682
6683```
6684 Executable targets and those executable targets' transitive dependencies are
6685 not considered unless that executable is listed in "data_deps". Otherwise, GN
6686 assumes that the executable (and everything it requires) is a build-time
6687 dependency only.
6688```
6689
6690#### **Actions and copies**
6691
6692```
6693 Action and copy targets that are listed as "data_deps" will have all of their
6694 outputs and data files considered as runtime dependencies. Action and copy
6695 targets that are "deps" or "public_deps" will have only their data files
6696 considered as runtime dependencies. These targets can list an output file in
6697 both the "outputs" and "data" lists to force an output file as a runtime
6698 dependency in all cases.
6699
6700 The different rules for deps and data_deps are to express build-time (deps)
6701 vs. run-time (data_deps) outputs. If GN counted all build-time copy steps as
6702 data dependencies, there would be a lot of extra stuff, and if GN counted all
6703 run-time dependencies as regular deps, the build's parallelism would be
6704 unnecessarily constrained.
6705
6706 This rule can sometimes lead to unintuitive results. For example, given the
6707 three targets:
6708 A --[data_deps]--> B --[deps]--> ACTION
6709 GN would say that A does not have runtime deps on the result of the ACTION,
6710 which is often correct. But the purpose of the B target might be to collect
6711 many actions into one logic unit, and the "data"-ness of A's dependency is
6712 lost. Solutions:
6713
6714 - List the outputs of the action in its data section (if the results of
6715 that action are always runtime files).
6716 - Have B list the action in data_deps (if the outputs of the actions are
6717 always runtime files).
6718 - Have B list the action in both deps and data deps (if the outputs might be
6719 used in both contexts and you don't care about unnecessary entries in the
6720 list of files required at runtime).
6721 - Split B into run-time and build-time versions with the appropriate "deps"
6722 for each.
6723```
6724
6725#### **Static libraries and source sets**
6726
6727```
6728 The results of static_library or source_set targets are not considered
6729 runtime dependencies since these are assumed to be intermediate targets only.
6730 If you need to list a static library as a runtime dependency, you can
6731 manually compute the .a/.lib file name for the current platform and list it
6732 in the "data" list of a target (possibly on the static library target
6733 itself).
6734```
6735
6736#### **Multiple outputs**
6737
6738```
6739 Linker tools can specify which of their outputs should be considered when
6740 computing the runtime deps by setting runtime_outputs. If this is unset on
6741 the tool, the default will be the first output only.
6742```
6743### **How Source Expansion Works**
6744
6745```
6746 Source expansion is used for the action_foreach and copy target types to map
6747 source file names to output file names or arguments.
6748
6749 To perform source expansion in the outputs, GN maps every entry in the
6750 sources to every entry in the outputs list, producing the cross product of
6751 all combinations, expanding placeholders (see below).
6752
6753 Source expansion in the args works similarly, but performing the placeholder
6754 substitution produces a different set of arguments for each invocation of the
6755 script.
6756
6757 If no placeholders are found, the outputs or args list will be treated as a
6758 static list of literal file names that do not depend on the sources.
6759
6760 See "gn help copy" and "gn help action_foreach" for more on how this is
6761 applied.
6762```
6763
6764#### **Placeholders**
6765
6766```
6767 This section discusses only placeholders for actions. There are other
6768 placeholders used in the definition of tools. See "gn help tool" for those.
6769
6770 {{source}}
6771 The name of the source file including directory (*). This will generally
6772 be used for specifying inputs to a script in the "args" variable.
6773 "//foo/bar/baz.txt" => "../../foo/bar/baz.txt"
6774
6775 {{source_file_part}}
6776 The file part of the source including the extension.
6777 "//foo/bar/baz.txt" => "baz.txt"
6778
6779 {{source_name_part}}
6780 The filename part of the source file with no directory or extension. This
6781 will generally be used for specifying a transformation from a source file
6782 to a destination file with the same name but different extension.
6783 "//foo/bar/baz.txt" => "baz"
6784
6785 {{source_dir}}
6786 The directory (*) containing the source file with no trailing slash.
6787 "//foo/bar/baz.txt" => "../../foo/bar"
6788
6789 {{source_root_relative_dir}}
6790 The path to the source file's directory relative to the source root, with
6791 no leading "//" or trailing slashes. If the path is system-absolute,
6792 (beginning in a single slash) this will just return the path with no
6793 trailing slash. This value will always be the same, regardless of whether
6794 it appears in the "outputs" or "args" section.
6795 "//foo/bar/baz.txt" => "foo/bar"
6796
6797 {{source_gen_dir}}
6798 The generated file directory (*) corresponding to the source file's path.
6799 This will be different than the target's generated file directory if the
6800 source file is in a different directory than the BUILD.gn file.
6801 "//foo/bar/baz.txt" => "gen/foo/bar"
6802
6803 {{source_out_dir}}
6804 The object file directory (*) corresponding to the source file's path,
6805 relative to the build directory. this us be different than the target's
6806 out directory if the source file is in a different directory than the
6807 build.gn file.
6808 "//foo/bar/baz.txt" => "obj/foo/bar"
6809
6810 {{source_target_relative}}
6811 The path to the source file relative to the target's directory. This will
6812 generally be used for replicating the source directory layout in the
Robert Sesek252674d2019-05-10 14:08:52 -04006813 output directory. This can only be used in actions and bundle_data
6814 targets. It is an error to use in process_file_template where there is no
6815 "target".
Brett Wilson796ed472018-07-16 15:11:09 -07006816 "//foo/bar/baz.txt" => "baz.txt"
6817```
6818
6819#### **(*) Note on directories**
6820
6821```
6822 Paths containing directories (except the source_root_relative_dir) will be
6823 different depending on what context the expansion is evaluated in. Generally
6824 it should "just work" but it means you can't concatenate strings containing
6825 these values with reasonable results.
6826
6827 Details: source expansions can be used in the "outputs" variable, the "args"
6828 variable, and in calls to "process_file_template". The "args" are passed to a
6829 script which is run from the build directory, so these directories will
6830 relative to the build directory for the script to find. In the other cases,
6831 the directories will be source- absolute (begin with a "//") because the
6832 results of those expansions will be handled by GN internally.
6833```
6834
6835#### **Examples**
6836
6837```
6838 Non-varying outputs:
6839 action("hardcoded_outputs") {
6840 sources = [ "input1.idl", "input2.idl" ]
6841 outputs = [ "$target_out_dir/output1.dat",
6842 "$target_out_dir/output2.dat" ]
6843 }
6844 The outputs in this case will be the two literal files given.
6845
6846 Varying outputs:
6847 action_foreach("varying_outputs") {
6848 sources = [ "input1.idl", "input2.idl" ]
6849 outputs = [ "{{source_gen_dir}}/{{source_name_part}}.h",
6850 "{{source_gen_dir}}/{{source_name_part}}.cc" ]
6851 }
6852 Performing source expansion will result in the following output names:
6853 //out/Debug/obj/mydirectory/input1.h
6854 //out/Debug/obj/mydirectory/input1.cc
6855 //out/Debug/obj/mydirectory/input2.h
6856 //out/Debug/obj/mydirectory/input2.cc
6857```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08006858### **Available global switches**
Brett Wilson796ed472018-07-16 15:11:09 -07006859
6860```
Brett Wilsonb5a2ac62018-12-21 21:20:05 -08006861 Do "gn help --the_switch_you_want_help_on" for more. Individual commands may
6862 take command-specific switches not listed here. See the help on your specific
6863 command for more.
6864```
6865```
6866 * --args: Specifies build arguments overrides.
6867 * --color: Force colored output.
6868 * --dotfile: Override the name of the ".gn" file.
6869 * --fail-on-unused-args: Treat unused build args as fatal errors.
6870 * --markdown: Write help output in the Markdown format.
6871 * --nocolor: Force non-colored output.
6872 * -q: Quiet mode. Don't print output on success.
6873 * --root: Explicitly specify source root.
6874 * --runtime-deps-list-file: Save runtime dependencies for targets in file.
6875 * --script-executable: Set the executable used to execute scripts.
6876 * --threads: Specify number of worker threads.
6877 * --time: Outputs a summary of how long everything took.
6878 * --tracelog: Writes a Chrome-compatible trace log to the given file.
6879 * -v: Verbose logging.
6880 * --version: Prints the GN version number and exits.
Brett Wilson796ed472018-07-16 15:11:09 -07006881```
6882