1 <?xml version="1.0" encoding="UTF-8"?>
3 SPDX-FileCopyrightText: Copyright The SCons Foundation (https://scons.org)
4 SPDX-License-Identifier: MIT
5 SPDX-FileType: DOCUMENTATION
7 This file is processed by the bin/SConsDoc.py module.
11 <!ENTITY % version SYSTEM "../version.xml">
13 <!ENTITY % scons SYSTEM '../scons.mod'>
15 <!ENTITY % builders-mod SYSTEM '../generated/builders.mod'>
17 <!ENTITY % functions-mod SYSTEM '../generated/functions.mod'>
19 <!ENTITY % tools-mod SYSTEM '../generated/tools.mod'>
21 <!ENTITY % variables-mod SYSTEM '../generated/variables.mod'>
25 <reference xmlns="http://www.scons.org/dbxsd/v1.0"
26 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
27 xsi:schemaLocation="http://www.scons.org/dbxsd/v1.0 http://www.scons.org/dbxsd/v1.0/scons.xsd">
30 <title>SCons &buildversion;</title>
31 <subtitle>MAN page</subtitle>
33 <corpauthor>The SCons Development Team</corpauthor>
35 <!-- adding pubdate seems superfluous when copyright year is the same
36 and html rendering puts both of them at the top of the page -->
37 <pubdate>Released &builddate;</pubdate>
39 <year>©right_years;</year>
40 <holder>The SCons Foundation</holder>
43 <releaseinfo>Version &buildversion;</releaseinfo>
45 <mediaobject role="cover"><imageobject><imagedata fileref="cover.jpg" format="JPG"/></imageobject></mediaobject>
49 <title>SCons &buildversion;</title>
50 <subtitle>MAN page</subtitle>
52 <refentry id='scons1'>
54 <refentrytitle>SCONS</refentrytitle>
55 <manvolnum>1</manvolnum>
56 <refmiscinfo class='source'>SCons __VERSION__</refmiscinfo>
57 <refmiscinfo class='manual'>SCons __VERSION__</refmiscinfo>
59 <refnamediv id='name'>
60 <refname>scons</refname>
61 <refpurpose>a software construction tool</refpurpose>
63 <!-- body begins here -->
64 <refsynopsisdiv id='synopsis'>
66 <command>scons</command>
67 <arg choice='opt' rep='repeat'><replaceable>options</replaceable></arg>
68 <arg choice='opt' rep='repeat'><replaceable>name</replaceable>=<replaceable>val</replaceable></arg>
69 <arg choice='opt' rep='repeat'><replaceable>targets</replaceable></arg>
74 <refsect1 id='description'>
75 <title>DESCRIPTION</title>
77 &SCons; is an extensible open source build system that
78 orchestrates the construction of software
79 (and other tangible products such as documentation files)
81 component pieces must be built or rebuilt and invoking the necessary
82 commands to build them.
83 &SCons; offers many features to improve developer productivity
84 such as parallel builds, caching of build artifacts,
85 automatic dependency scanning,
86 and a database of information about previous builds so
87 details do not have to be recalculated each run.
90 <para>&scons; requires &Python; 3.7 or later to run;
91 there should be no other dependencies or requirements,
92 unless the experimental Ninja tool is used (requires the ninja package).
95 <emphasis>Changed in version 4.3.0:</emphasis>
96 support for &Python; 3.5 is removed.
97 The CPython project retired 3.5 in Sept 2020:
98 <ulink url="https://peps.python.org/pep-0478"/>.
101 <emphasis>Changed in version 4.8.0:</emphasis>
102 support for &Python; 3.6 is deprecated and will be removed
103 in a future &SCons; release.
104 The CPython project retired 3.6 in Sept 2021:
105 <ulink url="https://peps.python.org/pep-0494"/>.
108 <emphasis>Changed in version NEXT_RELEASE:</emphasis>
109 support for &Python; 3.6 is removed.
113 You set up an &SCons; build by writing a script
114 that describes things to build (<firstterm>targets</firstterm>), and,
115 if necessary, the rules to build those files (<firstterm>actions</firstterm>).
116 &SCons; comes with a collection of <firstterm>Builder</firstterm> methods
117 which supply premade Actions for building many common software components
118 such as executable programs, object files and libraries,
119 so that for many software projects,
120 only the targets and input files (<firstterm>sources</firstterm>)
121 need be specified in a call to a builder.
125 &SCons; operates at a level of abstraction above that of pure filenames.
126 For example if you specify a shared library target named "foo",
127 &SCons; keeps track of the actual operating system dependent filename
128 (such as <filename>libfoo.so</filename> on a GNU/Linux system
129 and <filename>foo.dll</filename> on Windows),
130 and gives you a handle to refer to that target in other steps,
131 so you don't have to use system-specific strings yourself.
132 &SCons; can also scan automatically for dependency information,
133 such as header files included by source code files
134 (for example, <literal>#include</literal>
135 preprocessor directives in C or C++ files),
136 so these <firstterm>implicit dependencies</firstterm> do not
137 have to be specified manually.
138 &SCons; supports the ability to define new scanners
139 to support additional input file types.
142 <para>Information about files involved in the build,
143 including a cryptographic hash of the contents of source files,
144 is cached for later reuse.
145 By default, this hash (the <firstterm>&contentsig;</firstterm>)
146 is used to decide if a file has changed since the last build,
147 although other algorithms can be used by selecting an appropriate
148 <firstterm>&f-link-Decider;</firstterm> function.
149 Implicit dependency files are also part of out-of-date computation.
150 The scanned implicit dependency information can optionally be
151 cached and used to speed up future builds.
152 A hash of each executed build action (the <firstterm>&buildsig;</firstterm>)
153 is also cached, so that changes to build instructions (changing flags, etc.)
154 or to the build tools themselves (e.g. a compiler upgrade)
155 can also trigger a rebuild.
159 &SCons; supports separated source and build
160 directories (also called "out-of-tree builds")
161 through the definition of
162 <firstterm>variant directories</firstterm>
163 Using a separated build directory helps keep
164 the source directory clean of artifacts when doing searches,
165 allows setting up differing builds ("variants") without conflicts,
166 and allows resetting the build by just removing the build directory
167 (note that SCons does have a "clean" mode as well).
168 See the &f-link-VariantDir; description for more details.
172 When invoked, &scons;
173 looks for a file describing the build configuration
174 in the current directory and reads that in.
175 The file is by default named &SConstruct;,
176 although some variants of that,
177 or a developer-chosen name, are also accepted
178 (see <xref linkend="sconscript_files"/>).
179 If found, the current directory
180 is set as the project top directory.
181 Certain command-line options specify alternate
182 places to look for &SConstruct;
184 <link linkend="opt-directory"><option>-C</option></link>,
185 <link linkend="opt-D"><option>-D</option></link>,
186 <link linkend="opt-up"><option>-u</option></link> and
187 <link linkend="opt-U"><option>-U</option></link>),
188 which will set the project top directory to the path found.
189 A path to the build configuration can also be
191 <link linkend="opt-f"><option>-f</option></link> option,
192 which leaves the current directory as the project top directory.
196 The build configuration may be split into multiple files:
197 the &SConstruct; file can specify additional
198 configuration files by calling the
199 &f-link-SConscript; function,
200 and any file thus invoked may
201 include further files in the same way.
203 these subsidiary files are named
205 although any name may be used.
206 As a result of this naming convention,
207 the term <firstterm>&SConscript; files</firstterm>
209 generically to the complete set of
210 configuration files for a project
211 (including the &SConstruct; file),
212 regardless of the actual file names or number of such files.
213 A hierarchical build is not recursive - all of
214 the SConscript files are processed in a single pass
215 so that &scons; has a picture of the complete
216 dependency tree when it begins considering what needs building.
217 Each SConscript file is processed in a separate context
218 so settings made in one script do not leak into another;
219 information can however be shared explicitly between scripts.
222 <para>Before reading the SConscript files,
224 looks for a <firstterm>site directory</firstterm> -
225 a directory named <filename>site_scons</filename>
226 is searched for in various system directories and in the
227 project top directory, or if the
228 <link linkend="opt-site-dir"><option>--site-dir</option></link>
229 option is given, checks only for that directory.
230 Found site directories are prepended
231 to the &Python; module search path (<varname>sys.path</varname>),
232 thus allowing modules in such directories to be imported in
233 the normal &Python; way in &SConscript; files.
234 For each found site directory,
235 (1) if it contains a file <filename>site_init.py</filename>
236 that file is evaluated,
237 and (2) if it contains a directory
238 <filename>site_tools</filename> the path to that directory
239 is prepended to the default toolpath.
241 <link linkend="opt-site-dir"><option>--site-dir</option></link>
243 <link linkend="opt-no-site-dir"><option>--no-site-dir</option></link>
244 options for details on default paths and
245 controlling the site directories.
249 &SConscript; files are written in the
250 <firstterm>&Python;</firstterm> programming language.
251 For many tasks, the simple syntax can be understood from examples,
252 so it is normally not necessary to be a &Python;
253 programmer to use &SCons; effectively.
254 &SConscript; files are executed in a context that makes
255 the facilities described in this manual page directly
256 available (that is, no need to <literal>import</literal>).
257 Standard &Python; scripting capabilities
258 such as flow control, data manipulation, and imported &Python; modules
259 are available to use in more complicated build configurations.
260 Other &Python; files can be made a part of the build system,
261 but they do not automatically have the &SCons; context and
262 need to import it if they need access (described later).
266 &SCons; reads and executes all of the included &SConscript; files
267 <emphasis>before</emphasis>
268 it begins building any targets.
269 Progress messages show this behavior
270 (the state change lines - those
271 beginning with the <literal>scons:</literal> tag -
272 may be suppressed using the
273 <link linkend="opt-Q"><option>-Q</option></link> option):
277 $ <userinput>scons foo.out</userinput>
278 scons: Reading SConscript files ...
279 scons: done reading SConscript files.
280 scons: Building targets ...
282 scons: done building targets.
287 To assure reproducible builds,
289 uses a restricted <firstterm>execution environment</firstterm>
290 for running external commands used to build targets,
291 rather than propagating the full environment
292 in effect at the time &scons; was called.
293 This helps avoid problems like picking up accidental
294 or malicious settings,
295 temporary debug values that are no longer needed,
296 or a developer having different settings than another
297 (or than the CI pipeline).
298 Environment variables needed for the proper
299 operation of such commands must be set in the
300 execution environment explicitly,
301 either by assigning the desired values,
302 or by picking those values individually or collectively
303 out of environment variables exposed by the &Python;
304 <systemitem>os.environ</systemitem> dictionary
305 (as external program inputs they should be validated
307 The execution environment for a given &consenv;
308 is its &cv-link-ENV; value.
309 A small number of environment variables are picked up automatically
310 by &scons; itself (see <xref linkend="environment"/>).
314 In particular, if a compiler or other external command
315 needed to build a target file
316 is not in &scons;' idea of a standard system location,
317 it will not be found at runtime unless
318 you explicitly add the location into the
319 execution environment's <varname>PATH</varname> element.
320 This is a particular consideration on Windows platforms,
321 where it is common for a command to install into an app-specific
322 location and depend on setting
323 <varname>PATH</varname> in order for them to be found,
324 which does not automatically work for &SCons;.
328 One example approach is to
329 extract the entire <envar>PATH</envar>
330 environment variable and set that into the
331 execution environment:
334 <programlisting language="python">
336 env = Environment(ENV={'PATH': os.environ['PATH']})
339 <para>Similarly, if the commands use specific
340 external environment variables that &scons;
341 does not recognize, they can be propagated into
342 the execution environment:</para>
344 <programlisting language="python">
349 'PATH': os.environ['PATH'],
350 'MODULEPATH': os.environ['MODULEPATH'],
351 'PKG_CONFIG_PATH': os.environ['PKG_CONFIG_PATH'],
356 <para>Or you can explicitly propagate the invoking user's
357 complete external environment:</para>
359 <programlisting language="python">
361 env = Environment(ENV=os.environ.copy())
364 <para>This comes at the expense of making your build
365 dependent on the user's environment being set correctly,
366 but it may be more convenient for some configurations.
367 It should not cause problems if done in a build setup which tightly
368 controls how the environment is set up before invoking
369 &scons;, as in many continuous
374 The above fragments are intended to illustrate a concept.
375 It is normally not a good idea to wipe out the entire
376 default value of the execution environment
377 (<literal>env["ENV"]</literal>),
378 as it may carry important information for the
379 execution of build commands.
383 is normally executed in a top-level directory containing an
384 &SConstruct; file (the project top directory).
385 When &scons; is invoked,
386 the command line (including the contents of the
387 <link linkend="v-SCONSFLAGS">&SCONSFLAGS;</link>
388 environment variable, if set) is processed.
389 Command-line options (see <xref linkend="options"/>) are consumed.
390 Any variable argument assignments are collected, and
391 remaining arguments are taken as targets to build.</para>
393 <para>Values of variables to be passed to the &SConscript; files
394 may be specified on the command line:</para>
397 <userinput>scons debug=1</userinput>
400 <para>These variables are available through the
401 <link linkend="v-ARGUMENTS">&ARGUMENTS;</link> dictionary,
402 and can be used in the &SConscript; files to modify
403 the build in any way:</para>
405 <programlisting language="python">
406 if ARGUMENTS.get("debug", ""):
407 env = Environment(CCFLAGS="-g")
412 <para>The command-line variable arguments are also available
413 in the <link linkend="v-ARGLIST">&ARGLIST;</link> list,
414 indexed by their order on the command line.
415 This allows you to process them in order rather than by name,
416 if necessary. Each &ARGLIST; entry is a tuple consisting
417 of the name and the value.
421 See <xref linkend="commandline_construction_variables"/>
422 for more information.
426 can maintain a cache of target (derived) files that can
427 be shared between multiple builds. When derived-file caching is enabled in an
428 &SConscript; file, any target files built by
431 to the cache. If an up-to-date target file is found in the cache, it
432 will be retrieved from the cache instead of being rebuilt locally.
433 Caching behavior may be disabled and controlled in other ways by the
434 <link linkend="opt-cache-force"><option>--cache-force</option></link>,
435 <link linkend="opt-cache-disable"><option>--cache-disable</option></link>,
436 <link linkend="opt-cache-readonly"><option>--cache-readonly</option></link>,
438 <link linkend="opt-cache-show"><option>--cache-show</option></link>
439 command-line options. The
440 <link linkend="opt-random"><option>--random</option></link>
441 option is useful to prevent multiple builds
442 from trying to update the cache simultaneously.</para>
444 <!-- The following paragraph reflects the default tool search orders -->
445 <!-- currently in SCons/Tool/__init__.py. If any of those search orders -->
446 <!-- change, this documentation should change, too. -->
450 searches for known programming tools
451 on various systems and initializes itself based on what is found.
452 On Windows systems which identify as <emphasis>win32</emphasis>,
454 searches in order for the
456 the MinGW tool chain,
457 the Intel compiler tools,
459 the LLVM/clang tools,
460 and the PharLap ETS compiler.
461 On Windows system which identify as <emphasis>cygwin</emphasis>
462 (that is, if &scons; is invoked from a cygwin shell),
463 the order changes to prefer the GCC toolchain over the MSVC tools.
464 <!-- Seems odd to still list OS/2 (though it lives in some form as ArcaOS -->
467 searches in order for the
470 and the &MSVC; tools,
471 On SGI IRIX, IBM AIX, Hewlett Packard HP-UX, and Oracle Solaris systems,
473 searches for the native compiler tools
474 (MIPSpro, Visual Age, aCC, and Forte tools respectively)
475 and the GCC tool chain.
476 On all other platforms,
477 including POSIX (Linux and UNIX) and macOS platforms,
480 for the GCC tool chain,
481 the LLVM/clang tools,
482 and the Intel compiler tools.
483 The default tool selection can be pre-empted
484 through the use of the <parameter>tools</parameter>
485 argument to &consenv; creation methods,
486 explicitly calling the &f-link-Tool; loader,
487 the through the setting of various setting of &consvars;.
490 <refsect2 id='target_selection'>
491 <title>Target Selection</title>
493 <para>&SCons; acts on the <firstterm>selected targets</firstterm>,
494 whether the requested operation is build, no-exec or clean.
495 Targets are selected as follows:
500 Targets specified on the command line.
501 These may be files, directories,
502 or phony targets defined using the &f-link-Alias; function.
503 Directory targets are scanned by &scons; for any targets
504 that may be found with a destination in or under that directory.
505 The targets listed on the command line are made available in the
506 <link linkend="v-COMMAND_LINE_TARGETS">&COMMAND_LINE_TARGETS;</link> list.
510 <para>If no targets are specified on the command line,
511 &scons; will select those targets
512 specified in the &SConscript; files via calls
513 to the &f-link-Default; function. These are
514 known as the <firstterm>default targets</firstterm>,
515 and are made available in the
516 <link linkend="v-DEFAULT_TARGETS">&DEFAULT_TARGETS;</link> list.
521 If no targets are selected by the previous steps,
522 &scons; selects the current directory for scanning,
523 unless command-line options which affect the directory
524 for target scanning are present
525 (<link linkend="opt-directory"><option>-C</option></link>,
526 <link linkend="opt-D"><option>-D</option></link>,
527 <link linkend="opt-up"><option>-u</option></link>,
528 <link linkend="opt-U"><option>-U</option></link>).
529 Since targets thus selected were not the result of
530 user instructions, this target list is not made available
531 for direct inspection; use the
532 <link linkend="opt-debug"><option>--debug=explain</option></link>
533 option if they need to be examined.
538 &scons; always adds to the selected targets any intermediate
539 targets which are necessary to build the specified ones.
540 For example, if constructing a shared library or dll from C
541 source files, &scons; will also build the object files which
542 will make up the library.
547 <para>To ignore the default targets specified
548 through calls to &Default; and instead build all
549 target files in or below the current directory
550 specify the current directory (<literal>.</literal>)
551 as a command-line target:</para>
554 <userinput>scons .</userinput>
557 <para>To build all target files,
558 including any files outside of the current directory,
559 supply a command-line target
560 of the root directory (on POSIX systems):</para>
563 <userinput>scons /</userinput>
566 <para>or the path name(s) of the volume(s) in which all the targets
567 should be built (on Windows systems):</para>
570 <userinput>scons C:\ D:\</userinput>
573 <para>A subset of a hierarchical tree may be built by
574 remaining at the project top directory
575 and specifying the subdirectory as the target to
579 <userinput>scons src/subdir</userinput>
582 <para>or by changing directory and invoking scons with the
583 <link linkend="opt-up"><option>-u</option></link>
584 option, which traverses up the directory
585 hierarchy until it finds the
587 file, and then builds
588 targets relatively to the current subdirectory (see
590 <link linkend="opt-D"><option>-D</option></link>
592 <link linkend="opt-U"><option>-U</option></link>
596 <userinput>cd src/subdir</userinput>
597 <userinput>scons -u .</userinput>
600 <para>In all cases, more files may be built than are
601 requested, as &scons; needs to make
602 sure any dependent files are built.</para>
604 <para>Specifying "cleanup" targets in &SConscript; files is
605 usually not necessary.
607 <link linkend="opt-clean"><option>-c</option></link>
608 flag removes all selected targets:
612 <userinput>scons -c .</userinput>
615 <para>to remove all target files in or under the current directory, or:</para>
618 <userinput>scons -c build export</userinput>
621 <para>to remove target files under <filename>build</filename>
622 and <filename>export</filename>.</para>
625 Additional files or directories to remove can be specified using the
626 &f-link-Clean; function in the &SConscript; files.
627 Conversely, targets that would normally be removed by the
629 invocation can be retained by calling the
630 &f-link-NoClean; function with those targets.</para>
633 supports building multiple targets in parallel via a
634 <link linkend="opt-jobs"><option>-j</option></link>
635 option that takes, as its argument, the number
636 of simultaneous tasks that may be spawned:</para>
639 <userinput>scons -j 4</userinput>
642 <para>builds four targets in parallel, for example.</para>
647 <refsect1 id='options'>
648 <title>OPTIONS</title>
652 supports the same command-line options as GNU &Make;
653 and many of those supported by <application>cons</application>.
656 <!-- The recommended approach of multiple <term> entries per <varlistentry> -->
657 <!-- (if needed) is not used for Options, because the default docbook -->
658 <!-- presentation format for a varlist has been changed in SCons from -->
659 <!-- csv to one-per-line to improve the display of Builders and -->
660 <!-- Functions/Methods in those sections. Do the csv manually. -->
662 <!-- Note: commented-out options are retained as they may be a model -->
663 <!-- for future development directions. Do not remove. -->
666 <varlistentry id="opt-b">
667 <term><option>-b</option></term>
669 <para>Ignored for compatibility with non-GNU versions of &Make;</para>
673 <varlistentry id="opt-clean">
676 <option>--clean</option>,
677 <option>--remove</option>
680 <para>Set <firstterm>clean</firstterm> mode.
681 Clean up by removing the selected targets,
682 well as any files or directories associated
683 with a selected target through calls to the &f-link-Clean; function.
684 Will not remove any targets which are marked for
685 preservation through calls to the &f-link-NoClean; function.
688 While clean mode removes targets rather than building them,
689 work which is done directly in &Python; code in &SConscript; files
690 will still be carried out. If it is important to avoid some
691 such work from taking place in clean mode, it should be protected.
692 An &SConscript; file can determine which mode
693 is active by querying &f-link-GetOption;, as in the call
694 <code>if GetOption("clean"):</code>
699 <varlistentry id="opt-cache-debug">
700 <term><option>--cache-debug=<replaceable>file</replaceable></option></term>
702 <para>Write debug information about
703 derived-file caching to the specified
704 <replaceable>file</replaceable>.
706 <replaceable>file</replaceable>
708 (<literal>-</literal>),
709 the debug information is printed to the standard output.
710 The printed messages describe what signature-file names
711 are being looked for in, retrieved from, or written to the
712 derived-file cache specified by &f-link-CacheDir;.</para>
716 <varlistentry id="opt-cache-disable">
718 <option>--cache-disable</option>,
719 <option>--no-cache</option>
722 <para>Disable derived-file caching.
724 will neither retrieve files from the cache
725 nor copy files to the cache. This option can
726 be used to temporarily disable the cache without
727 modifying the build scripts.
732 <varlistentry id="opt-cache-force">
734 <option>--cache-force</option>,
735 <option>--cache-populate</option>
738 <para>When using &f-link-CacheDir;,
739 populate a derived-file cache by copying any already-existing,
740 up-to-date derived files to the cache,
741 in addition to files built by this invocation.
742 This is useful to populate a new cache with
743 all the current derived files,
744 or to add to the cache any derived files
745 recently built with caching disabled via the
746 <option>--cache-disable</option>
751 <varlistentry id="opt-cache-readonly">
752 <term><option>--cache-readonly</option></term>
754 <para>Use the derived-file cache, if enabled, to retrieve files,
755 but do not not update the cache with any files actually
756 built during this invocation.
761 <varlistentry id="opt-cache-show">
762 <term><option>--cache-show</option></term>
764 <para>When using a derived-file cache, show the command
765 that would have been executed to build the file
766 (or the corresponding <literal>*COMSTR</literal>
768 even if the file is retrieved from cache.
769 Without this option, &scons; shows a cache retrieval message
770 if the file is fetched from cache.
771 This allows producing consistent output for build logs,
772 regardless of whether a target
773 file was rebuilt or retrieved from the cache.</para>
777 <varlistentry id="opt-config">
778 <term><option>--config=<replaceable>mode</replaceable></option></term>
780 <para>Control how the &f-link-Configure;
781 call should use or generate the
782 results of configuration tests.
783 <replaceable>mode</replaceable> should be one of
784 the following choices:</para>
786 <variablelist> <!-- nested list -->
788 <term><emphasis role="bold">auto</emphasis></term>
790 <para>&SCons; will use its normal dependency mechanisms
791 to decide if a test must be rebuilt or not.
792 This saves time by not running the same configuration tests
793 every time you invoke scons,
794 but will overlook changes in system header files
795 or external commands (such as compilers)
796 if you don't specify those dependencies explicitly.
797 This is the default behavior.</para>
802 <term><emphasis role="bold">force</emphasis></term>
804 <para>If this mode is specified,
805 all configuration tests will be re-run
806 regardless of whether the
807 cached results are out-of-date.
808 This can be used to explicitly
809 force the configuration tests to be updated
810 in response to an otherwise unconfigured change
811 in a system header file or compiler.</para>
816 <term><emphasis role="bold">cache</emphasis></term>
818 <para>If this mode is specified,
819 no configuration tests will be rerun
820 and all results will be taken from cache.
821 &scons; will report an error
822 if <option>--config=cache</option> is specified
823 and a necessary test does not
824 have any results in the cache.</para>
827 </variablelist> <!-- end nested list -->
832 <varlistentry id="opt-directory">
834 <option>-C <replaceable>directory</replaceable></option>,
835 <option>--directory=<replaceable>directory</replaceable></option>
838 <para>Run as if &scons; was started in
839 <replaceable>directory</replaceable>
840 instead of the current working directory.
841 That is, change directory before searching for the
849 file or doing anything else.
852 options are given, each subsequent non-absolute
853 <option>-C</option> <replaceable>directory</replaceable>
854 is interpreted relative to the preceding one.
856 <link linkend="opt-up"><option>-u</option></link>,
857 <link linkend="opt-U"><option>-U</option></link>
859 <link linkend="opt-D"><option>-D</option></link>
860 to change the &SConstruct; search behavior when this option is used.
867 <!-- Display dependencies while building target files. Useful for -->
868 <!-- figuring out why a specific file is being rebuilt, as well as -->
869 <!-- general debugging of the build process. -->
871 <varlistentry id="opt-D">
872 <term><option>-D</option></term>
874 <para>Works exactly the same way as the
875 <link linkend="opt-up"><option>-u</option></link>
876 option except for the way default targets are handled.
877 When this option is used and no targets are specified on the command line,
878 all default targets are built, whether or not they are below the current
883 <varlistentry id="opt-debug">
884 <term><option>--debug=<replaceable>type</replaceable>[<replaceable>,type</replaceable>...]</option></term>
886 <para>Debug the build process.
887 <replaceable>type</replaceable>
888 specifies the kind of debugging info to emit.
889 Multiple types may be specified, separated by commas.
890 The following types are recognized:</para>
892 <variablelist> <!-- nested list -->
894 <term><emphasis role="bold">action-timestamps</emphasis></term>
896 <para>Prints additional time profiling information. For
897 each command, shows the absolute start and end times.
898 This may be useful in debugging parallel builds.
899 Implies the <option>--debug=time</option> option.
901 <para><emphasis>New in version 3.1.</emphasis></para>
906 <term><emphasis role="bold">count</emphasis></term>
908 <para>Print how many objects are created
909 of the various classes used internally by SCons
910 before and after reading the &SConscript; files
911 and before and after building targets.
912 This is not supported when SCons is executed with the &Python;
915 or when the SCons modules
916 have been compiled with optimization
917 (that is, when executing from
918 <filename>*.pyo</filename>
924 <term><emphasis role="bold">duplicate</emphasis></term>
926 <para>Print a line for each unlink/relink (or copy) of a file in
927 a variant directory from its source file.
928 Includes debugging info for unlinking stale variant directory files,
929 as well as unlinking old targets before building them.</para>
934 <term><emphasis role="bold">explain</emphasis></term>
936 <para>Print an explanation of why &scons;
937 is deciding to (re-)build the targets
938 it selects for building.
944 <term><emphasis role="bold">findlibs</emphasis></term>
946 <para>Instruct the scanner that searches for libraries
947 to print a message about each potential library
948 name it is searching for,
949 and about the actual libraries it finds.</para>
954 <term><emphasis role="bold">includes</emphasis></term>
956 <para>Print the include tree after each top-level target is built.
957 This is generally used to find out what files are included by the sources
958 of a given derived file:</para>
961 $ <userinput>scons --debug=includes foo.o</userinput>
968 <term><emphasis role="bold">json</emphasis></term>
970 <para>Write info to a JSON file for any of the following debug options if they are enabled: <emphasis>memory</emphasis>,
971 <emphasis>count</emphasis>, <emphasis>time</emphasis>, <emphasis>action-timestamps</emphasis> </para>
972 <para>The default output file is <literal>scons_stats.json</literal></para>
973 <para>The file name/path can be modified by using &f-link-DebugOptions; for example <literal>DebugOptions(json='path/to/file.json')</literal></para>
976 $ <userinput>scons --debug=memory,json foo.o</userinput>
983 <term><emphasis role="bold">memoizer</emphasis></term>
985 <para>Prints a summary of hits and misses using the Memoizer,
986 an internal subsystem that counts
987 how often SCons uses cached values in memory
988 instead of recomputing them each time they're needed.</para>
993 <term><emphasis role="bold">memory</emphasis></term>
995 <para>Prints how much memory SCons uses
996 before and after reading the &SConscript; files
997 and before and after building targets.</para>
1002 <term><emphasis role="bold">objects</emphasis></term>
1004 <para>Prints a list of the various objects
1005 of the various classes used internally by SCons.</para>
1010 <term><emphasis role="bold">pdb</emphasis></term>
1012 <para>Run &scons; under control of the
1013 <systemitem>pdb</systemitem>
1014 &Python; debugger.</para>
1016 $ <userinput>scons --debug=pdb</userinput>
1017 > /usr/lib/python3.11/site-packages/SCons/Script/Main.py(869)_main()
1018 -> options = parser.values
1022 <para><systemitem>pdb</systemitem> will stop at the
1023 beginning of the &scons; main routine on startup.
1024 The search path (<systemitem>sys.path</systemitem>)
1025 at that point will include the location of the running &scons;,
1026 but not of the project itself.
1027 If you need to set breakpoints in your project files,
1028 you will either need to add to the path,
1029 or use absolute pathnames when referring to project files.
1030 A <filename>.pdbrc</filename> file in the project root
1031 can be used to add the current directory to the search path
1032 to avoid having to enter it by hand,
1035 <programlisting language="python">
1036 sys.path.append('.')
1039 Due to the implementation of the
1040 <systemitem>pdb</systemitem> module,
1041 the <command>break</command>,
1042 <command>tbreak</command>
1043 and <command>clear</command>
1044 commands only understand references to filenames
1045 which have a <filename>.py</filename> extension.
1046 (although the suffix itself can be omitted),
1047 <emphasis>except</emphasis> if you use an absolute path.
1048 As a special exception to that rule, the names
1049 &SConstruct; and &SConscript; are recognized without
1050 needing the <filename>.py</filename> extension.
1053 <emphasis>Changed in version 4.6.0</emphasis>:
1054 The names &SConstruct; and &SConscript; are now
1055 recognized without requiring
1056 <filename>.py</filename> suffix.
1059 <emphasis>Changed in version 4.8.0</emphasis>:
1060 The name <filename>SCsub</filename> is now recognized
1061 without requiring <filename>.py</filename> suffix.
1068 <term><emphasis role="bold">prepare</emphasis></term>
1070 <para>Print a line each time any target (internal or external)
1071 is prepared for building.
1073 prints this for each target it considers, even if that
1074 target is up-to-date (see also <option>--debug=explain</option>).
1075 This can help debug problems with targets that aren't being
1076 built; it shows whether
1078 is at least considering them or not.</para>
1083 <term><emphasis role="bold">presub</emphasis></term>
1085 <para>Print the raw command line used to build each target
1086 before the &consenv; variables are substituted.
1087 Also shows which targets are being built by this command.
1088 Output looks something like this:</para>
1091 $ <userinput>scons --debug=presub</userinput>
1092 Building myprog.o with action(s):
1093 $SHCC $SHCFLAGS $SHCCFLAGS $CPPFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES
1100 <term><emphasis role="bold">stacktrace</emphasis></term>
1102 <para>Prints an internal &Python; stack trace
1103 when encountering an otherwise unexplained error.</para>
1108 <term><emphasis role="bold">time</emphasis></term>
1110 <para>Prints various time profiling information:</para>
1113 <para>The time spent executing each individual build command</para>
1116 <para>The total build time (time SCons ran from beginning to end)</para>
1119 <para>The total time spent reading and executing &SConscript; files</para>
1122 <para>The total time SCons itself spent running
1123 (that is, not counting reading and executing &SConscript; files)</para>
1126 <para>The total time spent executing all build commands</para></listitem>
1128 <para>The elapsed wall-clock time spent executing those build commands</para>
1131 <para>The time spent processing each file passed to the &f-link-SConscript; function</para>
1137 is executed without the
1140 the elapsed wall-clock time will typically
1141 be slightly longer than the total time spent
1142 executing all the build commands,
1143 due to the SCons processing that takes place
1144 in between executing each command.
1148 <emphasis>with</emphasis>
1152 and your build configuration allows good parallelization,
1153 the elapsed wall-clock time should
1154 be significantly smaller than the
1155 total time spent executing all the build commands,
1156 since multiple build commands and
1157 intervening SCons processing
1158 should take place in parallel.)
1163 <term><emphasis role="bold">sconscript</emphasis></term>
1165 <para>Enables output indicating entering and exiting each SConscript file.</para>
1168 </variablelist> <!-- end nested list -->
1172 <varlistentry id="opt-diskcheck">
1173 <term><option>--diskcheck=<replaceable>type</replaceable></option></term>
1175 <para>Enable specific checks for
1176 whether or not there is a file on disk
1177 where the SCons configuration expects a directory
1179 when searching for source and include files.
1180 <replaceable>type</replaceable>
1181 can be an available diskcheck type or
1182 the special tokens <literal>all</literal> or <literal>none</literal>.
1183 A comma-separated string can be used to select multiple checks.
1184 The default setting is <literal>all</literal>.
1187 <para>Current available checks are:</para>
1188 <variablelist> <!-- nested list -->
1190 <term><emphasis role="bold">match</emphasis></term>
1192 <para>to check that files and directories on disk
1193 match SCons' expected configuration.</para>
1196 </variablelist> <!-- end nested list -->
1199 Disabling some or all of these checks
1200 can provide a performance boost for large configurations,
1201 or when the configuration will check for files and/or directories
1202 across networked or shared file systems,
1203 at the slight increased risk of an incorrect build
1204 or of not handling errors gracefully.
1210 <varlistentry id="opt-duplicate">
1211 <term><option>--duplicate=<replaceable>ORDER</replaceable></option></term>
1213 <para>There are three ways to duplicate files in a build tree: hard links,
1214 soft (symbolic) links and copies. The default policy is to
1215 prefer hard links to soft links to copies. You can specify a
1216 different policy with this option.
1217 <replaceable>ORDER</replaceable>
1219 <emphasis>hard-soft-copy</emphasis>
1221 <emphasis>soft-hard-copy</emphasis>,
1222 <emphasis>hard-copy</emphasis>,
1223 <emphasis>soft-copy</emphasis>
1225 <emphasis>copy</emphasis>.
1226 &SCons; will attempt to duplicate files using
1227 the mechanisms in the specified order.</para>
1232 <!-- \-e, \-\-environment\-overrides -->
1233 <!-- Variables from the execution environment override construction -->
1234 <!-- variables from the SConscript files. -->
1236 <varlistentry id="opt-enable-virtualenv">
1237 <term><option>--enable-virtualenv</option></term>
1239 <para>Import virtualenv-related variables to SCons.</para>
1243 <varlistentry id="opt-experimental">
1245 <option>--experimental=<replaceable>feature</replaceable></option>
1248 <para>Enable experimental features and/or tools.
1249 <replaceable>feature</replaceable> can be an available feature name or
1250 the special tokens <literal>all</literal> or <literal>none</literal>.
1251 A comma-separated string can be used to select multiple features.
1252 The default setting is <literal>none</literal>.</para>
1253 <para>Current available features are:
1254 <literal>ninja</literal> (<emphasis>New in version 4.2</emphasis>),
1255 <literal>legacy_sched</literal> (<emphasis>New in version 4.6.0</emphasis>).
1258 No Support offered for any features or tools enabled by this flag.
1260 <para><emphasis>New in version 4.2 (experimental).</emphasis></para>
1264 <varlistentry id="opt-sconstruct">
1266 <option>-f <replaceable>file</replaceable></option>,
1267 <option>--file=<replaceable>file</replaceable></option>,
1268 <option>--makefile=<replaceable>file</replaceable></option>,
1269 <option>--sconstruct=<replaceable>file</replaceable></option>
1273 <replaceable>file</replaceable>
1274 as the initial &SConscript; file.
1277 options may be specified,
1280 will read all of the specified files.
1285 <varlistentry id="opt-help">
1287 <option>-h</option>,
1288 <option>--help</option>
1291 <para>Print a local help message for this project,
1292 if one is defined in the &SConscript; files
1293 (see the &f-link-Help; function),
1294 plus a line that refers to the standard &SCons; help message.
1295 If no local help message is defined,
1296 prints the standard &SCons; help message
1297 (as for the <option>-H</option> option)
1298 plus help for any local options defined through &f-link-AddOption;.
1299 Exits after displaying the appropriate message.</para>
1301 Note that use of this option requires &SCons; to process
1302 the &SConscript; files, so syntax errors may cause
1303 the help message not to be displayed.
1308 <varlistentry id="opt-hash-chunksize">
1310 <option>--hash-chunksize=<replaceable>KILOBYTES</replaceable></option>
1313 <para>Set the block size used when computing &contentsigs; to
1314 <replaceable>KILOBYTES</replaceable>.
1315 This value determines the size of the chunks which are read in at once when
1316 computing signature hashes. Files below that size are fully stored in memory
1317 before performing the signature computation while bigger files are read in
1318 block-by-block. A huge block-size leads to high memory consumption while a very
1319 small block-size slows down the build considerably.</para>
1321 <para>The default value is to use a chunk size of 64 kilobytes, which should
1322 be appropriate for most uses.</para>
1324 <para><emphasis>New in version 4.1.</emphasis></para>
1328 <varlistentry id="opt-hash-format">
1330 <option>--hash-format=<replaceable>ALGORITHM</replaceable></option>
1333 <para>Set the hashing algorithm used by SCons to
1334 <replaceable>ALGORITHM</replaceable>.
1335 This value determines the hashing algorithm used in generating
1336 &contentsigs;, &buildsigs; and &CacheDir; keys.</para>
1338 <para>The supported list of values are:
1339 <parameter>md5</parameter>,
1340 <parameter>sha1</parameter>
1341 and <parameter>sha256</parameter>.
1342 However, the &Python; interpreter used to run &scons; must have the corresponding
1343 support available in the <systemitem>hashlib</systemitem> module
1344 to use the specified algorithm.</para>
1346 <para>If this option is omitted,
1347 the first supported hash format found is selected.
1348 Typically, this is MD5, however, on a FIPS-compliant system
1349 using a version of &Python; older than 3.9,
1350 SHA1 or SHA256 is chosen as the default.
1351 &Python; 3.9 and onwards clients always default to MD5, even in FIPS mode.
1354 <para>Specifying this option changes the name of the SConsign database.
1355 The default database is <filename>.sconsign.dblite</filename>.
1356 In the presence of this option,
1357 <replaceable>ALGORITHM</replaceable> is
1358 included in the name to indicate the difference,
1359 even if the argument is <parameter>md5</parameter>.
1360 For example, <option>--hash-format=sha256</option> uses a SConsign
1361 database named <filename>.sconsign_sha256.dblite</filename>.
1364 <para><emphasis>New in version 4.1.</emphasis></para>
1368 <varlistentry id="opt-H">
1370 <option>-H</option>,
1371 <option>--help-options</option>
1374 <para>Print the standard help message about &SCons;
1375 command-line options and exit.</para>
1379 <varlistentry id="opt-ignore-errors">
1381 <option>-i</option>,
1382 <option>--ignore-errors</option>
1385 <para>Ignore all errors from commands executed to rebuild files.</para>
1390 <varlistentry id="opt-include-dir">
1392 <option>-I <replaceable>directory</replaceable></option>,
1393 <option>--include-dir=<replaceable>directory</replaceable></option>
1397 <replaceable>directory</replaceable>
1399 imported &Python; modules. If several
1402 are used, the directories are searched in the order specified.</para>
1406 <varlistentry id="opt-ignore-virtualenv">
1407 <term><option>--ignore-virtualenv</option></term>
1409 <para>Suppress importing virtualenv-related variables to SCons.</para>
1413 <varlistentry id="opt-implicit-cache">
1414 <term><option>--implicit-cache</option></term>
1416 <para>Cache implicit dependencies.
1419 to use the implicit (scanned) dependencies
1420 from the last time it was run
1421 instead of scanning the files for implicit dependencies.
1422 This can significantly speed up SCons,
1423 but with the following limitations:</para>
1426 will not detect changes to implicit dependency search paths
1427 (e.g. &cv-link-CPPPATH;, &cv-link-LIBPATH;)
1428 that would ordinarily
1429 cause different versions of same-named files to be used.</para>
1432 will miss changes in the implicit dependencies
1433 in cases where a new implicit
1434 dependency is added earlier in the implicit dependency search path
1435 (e.g. &cv-link-CPPPATH;, &cv-link-LIBPATH;)
1436 than a current implicit dependency with the same name.</para>
1440 <varlistentry id="opt-implicit-deps-changed">
1441 <term><option>--implicit-deps-changed</option></term>
1443 <para>Forces SCons to ignore the cached implicit dependencies. This causes the
1444 implicit dependencies to be rescanned and recached. This implies
1445 <option>--implicit-cache</option>.</para>
1449 <varlistentry id="opt-implicit-deps-unchanged">
1450 <term><option>--implicit-deps-unchanged</option></term>
1452 <para>Force SCons to ignore changes in the implicit dependencies.
1453 This causes cached implicit dependencies to always be used.
1455 <option>--implicit-cache</option>.</para>
1459 <varlistentry id="opt-install-sandbox">
1460 <term><option>--install-sandbox=<replaceable>sandbox_path</replaceable></option></term>
1463 When using the &Install; builders, prepend
1464 <replaceable>sandbox_path</replaceable>
1465 to the installation paths such that all installed files will be placed
1466 under that directory. This option is unavailable if
1467 one of &b-link-Install;, &b-link-InstallAs; or
1468 &b-link-InstallVersionedLib; is not used in the &SConscript; files.
1473 <varlistentry id="opt-interactive">
1474 <term><option>--interactive</option></term>
1476 <para>Starts SCons in interactive mode.
1477 The &SConscript; files are read once and a
1478 <computeroutput>scons>>></computeroutput>
1480 Targets may now be rebuilt by typing commands at interactive prompt
1481 without having to re-read the &SConscript; files
1482 and re-initialize the dependency graph from scratch.</para>
1484 <para>SCons interactive mode supports the following commands:</para>
1488 <term><userinput>build <parameter>[OPTIONS] [TARGETS] ...</parameter></userinput></term>
1490 <para>Builds the specified
1491 <parameter>TARGETS</parameter>
1492 (and their dependencies)
1495 <parameter>OPTIONS</parameter>.
1496 <emphasis role="bold">b</emphasis>
1498 <emphasis role="bold">scons</emphasis>
1500 <emphasis role="bold">build</emphasis>.
1503 <para>The following SCons command-line options affect the
1504 <emphasis role="bold">build</emphasis>
1507 <literallayout class="monospaced">
1509 --cache-disable, --no-cache
1510 --cache-force, --cache-populate
1517 -n, --no-exec, --just-print, --dry-run, --recon
1519 -s, --silent, --quiet
1520 --taskmastertrace=FILE
1524 <para>Any other SCons command-line options that are specified
1526 but have no effect on the
1527 <emphasis role="bold">build</emphasis>
1529 (mainly because they affect how the &SConscript; files are read,
1530 which only happens once at the beginning of interactive mode).</para>
1535 <term><userinput>clean <parameter>[OPTIONS] [TARGETS] ...</parameter></userinput></term>
1537 <para>Cleans the specified
1538 <parameter>TARGETS</parameter>
1539 (and their dependencies)
1541 <parameter>OPTIONS</parameter>.
1542 <emphasis role="bold">c</emphasis>
1544 This command is itself a synonym for
1545 <userinput>build --clean</userinput></para>
1550 <term><userinput>exit</userinput></term>
1552 <para>Exits SCons interactive mode.
1553 You can also exit by terminating input
1554 (<keycombo action="simul">
1555 <keycap>Ctrl</keycap>
1558 UNIX or Linux systems,
1559 (<keycombo action="simul">
1560 <keycap>Ctrl</keycap>
1563 on Windows systems).</para>
1568 <term><userinput>help <parameter>[COMMAND]</parameter></userinput></term>
1570 <para>Provides a help message about
1571 the commands available in SCons interactive mode.
1573 <emphasis>COMMAND</emphasis>
1575 <emphasis role="bold">h</emphasis>
1577 <emphasis role="bold">?</emphasis>
1578 are synonyms.</para>
1583 <term><userinput>shell <parameter>[COMMANDLINE]</parameter></userinput></term>
1585 <para>Executes the specified
1586 <parameter>COMMANDLINE</parameter>
1589 <parameter>COMMANDLINE</parameter>
1591 executes the interactive command interpreter
1593 <envar>SHELL</envar>
1594 environment variable
1595 (on UNIX and Linux systems)
1597 <envar>COMSPEC</envar>
1598 environment variable
1599 (on Windows systems).
1600 <emphasis role="bold">sh</emphasis>
1602 <emphasis role="bold">!</emphasis>
1603 are synonyms.</para>
1608 <term><userinput>version</userinput></term>
1610 <para>Prints SCons version information.</para>
1615 <para>An empty line repeats the last typed command.
1616 Command-line editing can be used if the
1617 <emphasis role="bold">readline</emphasis>
1618 module is available.</para>
1621 $ <userinput>scons --interactive</userinput>
1622 scons: Reading SConscript files ...
1623 scons: done reading SConscript files.
1624 scons>>> build -n prog
1625 scons>>> exit
1630 <varlistentry id="opt-jobs">
1632 <option>-j <replaceable>N</replaceable></option>,
1633 <option>--jobs=<replaceable>N</replaceable></option>
1636 <para>Specifies the maximum number of concurrent jobs (commands) to run.
1637 If there is more than one
1639 option, the last one is effective.</para>
1643 <!-- is specified without an argument, -->
1645 <!-- will not limit the number of -->
1646 <!-- simultaneous jobs. -->
1650 <varlistentry id="opt-keep-going">
1652 <option>-k</option>,
1653 <option>--keep-going</option>
1656 <para>Continue as much as possible after an error. The target that
1657 failed and those that depend on it will not be remade, but other
1658 targets specified on the command line will still be processed.</para>
1663 <!-- .RI \-l " N" ", \-\-load\-average=" N ", \-\-max\-load=" N -->
1664 <!-- No new jobs (commands) will be started if -->
1665 <!-- there are other jobs running and the system load -->
1666 <!-- average is at least -->
1668 <!-- (a floating\-point number). -->
1671 <!-- \-\-list\-derived -->
1672 <!-- List derived files (targets, dependencies) that would be built, -->
1673 <!-- but do not build them. -->
1674 <!-- [XXX This can probably go away with the right -->
1675 <!-- combination of other options. Revisit this issue.] -->
1678 <!-- \-\-list\-actions -->
1679 <!-- List derived files that would be built, with the actions -->
1680 <!-- (commands) that build them. Does not build the files. -->
1681 <!-- [XXX This can probably go away with the right -->
1682 <!-- combination of other options. Revisit this issue.] -->
1685 <!-- \-\-list\-where -->
1686 <!-- List derived files that would be built, plus where the file is -->
1687 <!-- defined (file name and line number). Does not build the files. -->
1688 <!-- [XXX This can probably go away with the right -->
1689 <!-- combination of other options. Revisit this issue.] -->
1691 <varlistentry id="opt-m">
1692 <term><option>-m</option></term>
1694 <para>Ignored for compatibility with non-GNU versions of &Make;.</para>
1698 <varlistentry id="opt-max-drift">
1699 <term><option>--max-drift=<replaceable>SECONDS</replaceable></option></term>
1701 <para>Set the maximum expected drift in the modification time of files to
1702 <replaceable>SECONDS</replaceable>.
1703 This value determines how long a file must be unmodified
1704 before its cached &contentsig;
1705 will be used instead of
1706 calculating a new &contentsig; (hash)
1707 of the file's contents.
1708 The default value is 2 days, which means a file must have a
1709 modification time of at least two days ago in order to have its
1710 cached &contentsig; used.
1711 A negative value means to never cache the
1712 &contentsig; and to ignore the cached value if there already is one.
1713 A value of 0 means to always use the cached signature,
1714 no matter how old the file is.</para>
1719 <term><option>--md5-chunksize=<replaceable>KILOBYTES</replaceable></option></term>
1721 <para>A deprecated synonym for
1722 <link linkend="opt-hash-chunksize"><option>--hash-chunksize</option></link>.
1725 <para><emphasis>Changed in version 4.2:</emphasis> deprecated.</para>
1729 <varlistentry id="opt-no-exec">
1731 <option>-n</option>,
1732 <option>--no-exec</option>,
1733 <option>--just-print</option>,
1734 <option>--dry-run</option>,
1735 <option>--recon</option>
1738 <para>Set <firstterm>no-exec</firstterm> mode.
1739 Print the commands that would be executed to build
1740 any out-of-date targets, but do not execute those commands.
1744 Only target building is suppressed - any work in the build
1745 system that is done directly (in regular &Python; code)
1746 will still be carried out. You can add guards around
1747 code which should not be executed in no-exec mode by
1748 checking the value of the option at run time with &f-link-GetOption;:
1750 <programlisting language="python">
1751 if not GetOption("no_exec"):
1752 # run regular instructions
1755 <para>The output is a best effort, as &SCons; cannot always precisely
1756 determine what would be built. For example, if a file generated
1757 by a builder action is also used as a source in the build,
1758 that file is not available to scan for dependencies at all
1759 in an unbuilt tree, and may contain out-of-date information in a
1760 previously built tree.
1763 &SCons; cannot perform &f-link-Configure; checks in no-exec mode,
1764 as they would make changes to the filesystem
1765 (see &cv-link-CONFIGUREDIR; and &cv-link-CONFIGURELOG;).
1766 It can use stored information from a previous build,
1767 if it is not out-of-date,
1768 so a "priming" build may make subsequent no-exec runs
1774 <varlistentry id="opt-no-site-dir">
1775 <term><option>--no-site-dir</option></term>
1777 <para>Do not read site directories.
1778 Neither the standard site directories
1779 (<filename>site_scons</filename>)
1780 nor the path specified via a previous
1781 <option>--site-dir</option> option are
1782 added to the module search path <varname>sys.path</varname>,
1783 searched for a <filename>site_init.py</filename> file,
1784 or have their <filename>site_tools</filename>
1785 directory included in the tool search path.
1786 Can be overridden by a subsequent
1787 <option>--site-dir</option> option.
1793 <!-- .RI \-o " file" ", \-\-old\-file=" file ", \-\-assume\-old=" file -->
1794 <!-- Do not rebuild -->
1797 <!-- not rebuild anything due to changes in the contents of -->
1800 <!-- .RI \-\-override " file" -->
1801 <!-- Read values to override specific build environment variables -->
1802 <!-- from the specified -->
1807 <!-- Print the data base (construction environments, -->
1808 <!-- Builder and Scanner objects) that are defined -->
1809 <!-- after reading the SConscript files. -->
1810 <!-- After printing, a normal build is performed -->
1811 <!-- as usual, as specified by other command\-line options. -->
1812 <!-- This also prints version information -->
1813 <!-- printed by the -->
1817 <!-- To print the database without performing a build do: -->
1820 <!-- scons \-p \-q -->
1823 <varlistentry id="opt-package-type">
1824 <term><option>--package-type=<replaceable>type</replaceable></option></term>
1827 of package to create when using the &b-link-Package; builder.
1828 Multiple types can be specified by using a comma-separated string,
1829 in which case &SCons; will try to build for all of those package types.
1830 Note this option is only available if the &t-link-packaging; tool
1836 <varlistentry id="opt-profile">
1837 <term><option>--profile=<replaceable>file</replaceable></option></term>
1839 <para>Run &SCons; under the &Python; profiler
1840 and save the results to <replaceable>file</replaceable>.
1841 The results may be analyzed using the &Python;
1842 <systemitem>pstats</systemitem> module.</para>
1846 <varlistentry id="opt-question">
1848 <option>-q</option>,
1849 <option>--question</option></term>
1851 <para>Do not run any commands, or print anything. Just return an exit
1852 status that is zero if the specified targets are already up-to-date,
1853 non-zero otherwise.</para>
1857 <varlistentry id="opt-Q">
1858 <term><option>-Q</option></term>
1860 <para>Suppress status messages about
1861 reading &SConscript; files,
1863 and entering directories.
1864 Commands that are executed
1865 to rebuild target files are still printed.</para>
1870 <!-- \-r, \-R, \-\-no\-builtin\-rules, \-\-no\-builtin\-variables -->
1871 <!-- Clear the default construction variables. Construction -->
1872 <!-- environments that are created will be completely empty. -->
1874 <varlistentry id="opt-random">
1875 <term><option>--random</option></term>
1877 <para>Build dependencies in a random order. This is useful when
1878 building multiple trees simultaneously with caching enabled,
1879 to prevent multiple builds from simultaneously trying to build
1880 or retrieve the same target files.</para>
1884 <varlistentry id="opt-silent">
1886 <option>-s</option>,
1887 <option>--silent</option>,
1888 <option>--quiet</option>
1891 <para>Silent. Do not print commands that are executed to rebuild
1893 Also suppresses SCons status messages.</para>
1897 <varlistentry id="opt-no-keep-going">
1899 <option>-S</option>,
1900 <option>--no-keep-going</option>,
1901 <option>--stop</option>
1904 <para>Ignored for compatibility with GNU &Make;</para>
1908 <varlistentry id="opt-site-dir">
1909 <term><option>--site-dir=<replaceable>path</replaceable></option></term>
1911 <para>Use <replaceable>path</replaceable> as the site directory
1912 rather than searching the list of default site directories.
1913 This directory will be prepended to
1914 <varname>sys.path</varname>,
1916 <filename><replaceable>path</replaceable>/site_init.py</filename>
1917 will be loaded if it exists, and
1918 <filename><replaceable>path</replaceable>/site_tools</filename>
1919 will be included in the tool search path.
1920 The option is not additive - if given more than once,
1921 the last <replaceable>path</replaceable> wins.
1924 <para>The default set of site directories searched when
1925 <option>--site-dir</option>
1926 is not specified depends on the system platform, as follows.
1927 Users or system administrators can tune site-specific or
1928 project-specific &SCons; behavior by setting up a
1929 site directory in one or more of these locations.
1930 Directories are examined in the order given, from most
1931 generic ("system" directories) to most specific (in the current project),
1932 so the last-executed <filename>site_init.py</filename> file is
1933 the most specific one, giving it the chance to override
1934 everything else), and the directories are prepended to the paths, again so
1935 the last directory examined comes first in the resulting path.</para>
1939 <term>Windows:</term>
1941 <literallayout class="monospaced">
1942 %ALLUSERSPROFILE%/scons/site_scons
1943 %LOCALAPPDATA%/scons/site_scons
1944 %APPDATA%/scons/site_scons
1945 %USERPROFILE%/.scons/site_scons
1949 Note earlier versions of the documentation listed a different
1950 path for the "system" site directory, this path is still checked
1951 but its use is discouraged:
1953 <literallayout class="monospaced">
1954 %ALLUSERSPROFILE%/Application Data/scons/site_scons
1960 <term>Mac OS X:</term>
1962 <literallayout class="monospaced">
1963 /Library/Application Support/SCons/site_scons
1964 /opt/local/share/scons/site_scons (for MacPorts)
1965 /sw/share/scons/site_scons (for Fink)
1966 $HOME/Library/Application Support/SCons/site_scons
1967 $HOME/.scons/site_scons
1974 <term>Solaris:</term>
1976 <literallayout class="monospaced">
1977 /opt/sfw/scons/site_scons
1978 /usr/share/scons/site_scons
1979 $HOME/.scons/site_scons
1986 <term>Linux, HPUX, and other Posix-like systems:</term>
1988 <literallayout class="monospaced">
1989 /usr/share/scons/site_scons
1990 $HOME/.scons/site_scons
2000 <varlistentry id="opt-stack-size">
2001 <term><option>--stack-size=<replaceable>KILOBYTES</replaceable></option></term>
2003 <para>Set the size stack used to run threads to
2004 <replaceable>KILOBYTES</replaceable>.
2005 This value determines the stack size of the threads used to run jobs.
2006 These threads execute the actions of the builders for the
2007 nodes that are out-of-date.
2008 This option has no effect unless the number of concurrent
2009 build jobs is larger than one (as set by <option>-j N</option> or
2010 <option>--jobs=N</option> on the command line or &SetOption; in a script).
2013 Using a stack size that is too small may cause stack overflow errors.
2014 This usually shows up as segmentation faults that cause scons to abort
2015 before building anything. Using a stack size that is too large will
2016 cause scons to use more memory than required and may slow down the entire
2018 The default value is to use a stack size of 256 kilobytes, which should
2019 be appropriate for most uses. You should not need to increase this value
2020 unless you encounter stack overflow errors.</para>
2024 <varlistentry id="opt-touch">
2026 <option>-t</option>,
2027 <option>--touch</option>
2030 <para>Ignored for compatibility with GNU &Make;.
2031 (Touching a file to make it
2032 appear up-to-date is unnecessary when using &scons;.)</para>
2036 <varlistentry id="opt-taskmastertrace">
2037 <term><option>--taskmastertrace=<replaceable>file</replaceable></option></term>
2039 <para>Prints trace information to the specified
2040 <replaceable>file</replaceable>
2041 about how the internal Taskmaster object
2042 evaluates and controls the order in which Nodes are built.
2044 <emphasis role="bold">-</emphasis>
2045 may be used to specify the standard output.</para>
2049 <varlistentry id="opt-tree">
2050 <term><option>--tree=<replaceable>type</replaceable>[<replaceable>,type</replaceable>...]</option></term>
2052 <para>Prints a tree of the dependencies
2053 after each top-level target is built.
2054 This prints out some or all of the tree,
2057 <replaceable>type</replaceable>
2060 <variablelist> <!-- nested list -->
2062 <term><emphasis role="bold">all</emphasis></term>
2064 <para>Print the entire dependency tree
2065 after each top-level target is built.
2066 This prints out the complete dependency tree,
2067 including implicit dependencies and ignored dependencies.</para>
2072 <term><emphasis role="bold">derived</emphasis></term>
2074 <para>Restricts the tree output to only derived (target) files,
2075 not source files.</para>
2080 <term><emphasis role="bold">linedraw</emphasis></term>
2082 <para>Draw the tree output using Unicode line-drawing characters
2083 instead of plain ASCII text. This option acts as a modifier
2084 to the selected <replaceable>type</replaceable>(s). If
2085 specified alone, without any <replaceable>type</replaceable>,
2086 it behaves as if <emphasis role="bold">all</emphasis>
2089 <para><emphasis>New in version 4.0.</emphasis></para>
2094 <term><emphasis role="bold">status</emphasis></term>
2096 <para>Prints status information for each displayed node.</para>
2101 <term><emphasis role="bold">prune</emphasis></term>
2103 <para>Prunes the tree to avoid repeating dependency information
2104 for nodes that have already been displayed.
2105 Any node that has already been displayed
2106 will have its name printed in
2107 <emphasis role="bold">[square brackets]</emphasis>,
2108 as an indication that the dependencies
2109 for that node can be found by searching
2110 for the relevant output higher up in the tree.</para>
2113 </variablelist> <!-- end nested list -->
2115 <para>Multiple <replaceable>type</replaceable>
2116 choices may be specified, separated by commas:</para>
2119 # Prints only derived files, with status information:
2120 <userinput>scons --tree=derived,status</userinput>
2122 # Prints all dependencies of target, with status information
2123 # and pruning dependencies of already-visited Nodes:
2124 <userinput>scons --tree=all,prune,status target</userinput>
2129 <varlistentry id="opt-up">
2131 <option>-u</option>,
2132 <option>--up</option>,
2133 <option>--search-up</option>
2136 <para>Walks up the directory structure until an
2137 &SConstruct;, &Sconstruct;, &sconstruct;, &SConstruct.py;,
2138 &Sconstruct.py; or &sconstruct.py;
2139 file is found, and uses that
2140 as the project top directory.
2141 If no targets are specified on the command line,
2142 only targets at or below the
2143 current directory will be built.</para>
2147 <varlistentry id="opt-U">
2148 <term><option>-U</option></term>
2150 <para>Works exactly the same way as the
2152 option except for the way default targets are handled.
2153 When this option is used and no targets are specified on the command line,
2154 all default targets that are defined in the &SConscript; file(s) in the current
2155 directory are built, regardless of what directory the resultant targets end
2160 <varlistentry id="opt-version">
2162 <option>-v</option>,
2163 <option>--version</option>
2168 version, copyright information,
2169 list of authors, and any other relevant information.
2174 <varlistentry id="opt-print-directory">
2176 <option>-w</option>,
2177 <option>--print-directory</option>
2180 <para>Print a message containing the working directory before and
2181 after other processing.</para>
2185 <varlistentry id="opt-no-print-directory">
2186 <term><option>--no-print-directory</option></term>
2188 <para>Turn off -w, even if it was turned on implicitly.</para>
2192 <varlistentry id="opt-warn">
2194 <option>--warn=<replaceable>type</replaceable></option>,
2195 <option>--warn=no-<replaceable>type</replaceable></option>
2198 <para>Enable or disable (with the prefix "no-") warnings
2199 (<option>--warning</option> is a synonym).
2200 <replaceable>type</replaceable>
2201 specifies the type of warnings to be enabled or disabled:</para>
2203 <variablelist> <!-- nested list -->
2205 <term><emphasis role="bold">all</emphasis></term>
2207 <para>All warnings.</para>
2212 <term><emphasis role="bold">cache-version</emphasis></term>
2214 <para>Warnings about the derived-file cache directory
2215 specified by &f-link-CacheDir; not using
2216 the latest configuration information.
2217 These warnings are enabled by default.</para>
2222 <term><emphasis role="bold">cache-write-error</emphasis></term>
2224 <para>Warnings about errors trying to
2225 write a copy of a built file to a specified
2226 derived-file cache specified by &f-link-CacheDir;.
2227 These warnings are disabled by default.</para>
2232 <term><emphasis role="bold">cache-cleanup-error</emphasis></term>
2234 <para>Warnings about errors when a file retrieved
2235 from the derived-file cache could not be removed.
2241 <term><emphasis role="bold">corrupt-sconsign</emphasis></term>
2243 <para>Warnings about unfamiliar signature data in
2244 <filename>.sconsign</filename>
2246 These warnings are enabled by default.</para>
2251 <term><emphasis role="bold">dependency</emphasis></term>
2253 <para>Warnings about dependencies.
2254 These warnings are disabled by default.</para>
2259 <term><emphasis role="bold">deprecated</emphasis></term>
2261 <para>Warnings about use of
2262 currently deprecated features.
2263 These warnings are enabled by default.
2264 Not all deprecation warnings can be disabled with the
2265 <option>--warn=no-deprecated</option> option as some
2266 deprecated features which are late in the deprecation
2267 cycle may have been designated as mandatory warnings,
2268 and these will still display.
2269 Warnings for certain deprecated features
2270 may also be enabled or disabled individually;
2276 <term><emphasis role="bold">duplicate-environment</emphasis></term>
2278 <para>Warnings about attempts to specify a build
2279 of a target with two different &consenvs;
2280 that use the same action.
2281 These warnings are enabled by default.</para>
2286 <term><emphasis role="bold">fortran-cxx-mix</emphasis></term>
2288 <para>Warnings about linking
2289 Fortran and C++ object files in a single executable,
2290 which can yield unpredictable behavior with some compilers.</para>
2295 <term><emphasis role="bold">future-reserved-variable</emphasis></term>
2297 <para>Warnings about construction variables which
2298 are currently allowed,
2299 but will become reserved variables in a future release.
2305 <term><emphasis role="bold">future-deprecated</emphasis></term>
2307 <para>Warnings about features
2308 that will be deprecated in the future.
2309 Such warnings are disabled by default.
2310 Enabling future deprecation warnings is
2311 recommended for projects that redistribute
2312 SCons configurations for other users to build,
2313 so that the project can be warned as soon as possible
2314 about to-be-deprecated features
2315 that may require changes to the configuration.</para>
2320 <term><emphasis role="bold">link</emphasis></term>
2322 <para>Warnings about link steps.</para>
2327 <term><emphasis role="bold">misleading-keywords</emphasis></term>
2329 <para>Warnings about the use of two commonly
2331 <parameter>targets</parameter>
2333 <parameter>sources</parameter>
2334 to &f-link-Builder; calls. The correct spelling is the
2335 singular form, even though
2336 <parameter>target</parameter>
2338 <parameter>source</parameter>
2339 can themselves refer to lists of names or nodes.</para>
2344 <term><emphasis role="bold">tool-qt-deprecated</emphasis></term>
2346 <para>Warnings about the &t-link-qt; tool being deprecated.
2347 These warnings are disabled by default for the first
2348 phase of deprecation. Enable to be reminded about use
2349 of this tool module.
2350 <emphasis>New in version 4.3.</emphasis>
2355 <!--varlistentry> Removed in 4.6.0
2356 <term><emphasis role="bold">missing-sconscript</emphasis></term>
2358 <para>Warnings about missing &SConscript; files.
2359 These warnings are enabled by default.</para>
2364 <term><emphasis role="bold">no-object-count</emphasis></term>
2366 <para>Warnings about the
2367 <option>--debug=object</option>
2368 feature not working when
2370 is run with the &Python;
2372 option or from optimized &Python; (<filename>.pyo</filename>) modules.</para>
2374 Note the "no-" prefix is part of the name of this warning.
2375 Add another "-no" to disable.
2381 <term><emphasis role="bold">no-parallel-support</emphasis></term>
2383 <para>Warnings about the version of &Python;
2384 not being able to support parallel builds when the
2387 These warnings are enabled by default.</para>
2389 Note the "no-" prefix is part of the name of this warning.
2390 Add another "-no" to disable.
2396 <term><emphasis role="bold">python-version</emphasis></term>
2398 <para>Warnings about running
2399 &SCons; using a version of &Python; that has been deprecated.
2400 These warnings are enabled by default.</para>
2405 <term><emphasis role="bold">reserved-variable</emphasis></term>
2407 <para>Warnings about attempts to set the
2408 reserved &consvar; names
2409 &cv-CHANGED_SOURCES;,
2410 &cv-CHANGED_TARGETS;,
2415 &cv-UNCHANGED_SOURCES;
2417 &cv-UNCHANGED_TARGETS;.
2418 These warnings are disabled by default.</para>
2423 <term><emphasis role="bold">stack-size</emphasis></term>
2425 <para>Warnings about requests to set the stack size
2426 that could not be honored.
2427 These warnings are enabled by default.</para>
2432 <term><emphasis role="bold">target-not-built</emphasis></term>
2434 <para>Warnings about a build rule not building the
2435 expected targets. These warnings are disabled by default.</para>
2438 </variablelist> <!-- end nested list -->
2443 <!-- \-\-warn\-undefined\-variables -->
2444 <!-- Warn when an undefined variable is referenced. -->
2447 <!-- .RI \-\-write\-filenames= file -->
2448 <!-- Write all filenames considered into -->
2452 <!-- .RI \-W " file" ", \-\-what\-if=" file ", \-\-new\-file=" file ", \-\-assume\-new=" file -->
2453 <!-- Pretend that the target -->
2456 <!-- modified. When used with the -->
2458 <!-- option, this -->
2459 <!-- show you what would be rebuilt if you were to modify that file. -->
2462 <!-- ... what? XXX -->
2464 <varlistentry id="opt-repository">
2466 <option>-Y <replaceable>repository</replaceable></option>,
2467 <option>--repository=<replaceable>repository</replaceable></option>,
2468 <option>--srcdir=<replaceable>repository</replaceable></option>
2472 Search <replaceable>repository</replaceable>
2473 for any input and target
2474 files not found in the local directory hierarchy.
2475 Multiple <option>-Y</option>
2476 options may be specified,
2477 with repositories searched in the given order.
2478 See &f-link-Repository; for more information.
2485 <refsect1 id='sconscript_file_reference'>
2486 <title>SCONSCRIPT FILE REFERENCE</title>
2488 <refsect2 id='sconscript_files'>
2489 <title>SConscript Files</title>
2491 The build configuration is described by one or more files,
2492 known as &SConscript; files.
2493 There must be at least one file for a valid build
2494 (&scons; will quit if it does not find one).
2495 &scons; by default looks for this file by the name
2496 <filename>SConstruct</filename>
2497 in the directory from which you run &scons;,
2498 though if necessary, also looks for alternative file names
2499 &Sconstruct;, &sconstruct;, &SConstruct.py;, &Sconstruct.py;
2500 and &sconstruct.py; in that order.
2501 A different file name (which can include a pathname part)
2502 may be specified via the <option>-f</option> option.
2503 Except for the &SConstruct; file,
2504 these files are not searched for automatically;
2505 you add additional configuration files to the build
2506 by calling the &f-link-SConscript; function.
2507 This allows parts of the build to be conditionally
2508 included or excluded at run-time depending on how &scons; is invoked.
2512 Each &SConscript; file in a build configuration is invoked
2513 independently in a separate context.
2514 This provides necessary isolation so that different parts of
2515 the build don't accidentally step on each other.
2516 You have to be explicit about sharing information,
2517 by using the &f-link-Export; function or the &exports; argument
2518 to the &f-link-SConscript; function, as well as the &f-link-Return; function
2519 in a called &SConscript; file, and consume shared information by using the
2520 &f-link-Import; function.
2524 The following sections describe the various &SCons; facilities
2525 that can be used in &SConscript; files. Quick links:
2528 <simplelist type="vert">
2529 <member><link linkend='construction_environments'>Construction Environments</link></member>
2530 <member><link linkend='tools'>Tools</link></member>
2531 <member><link linkend='builder_methods'>Builder Methods</link></member>
2532 <member><link linkend='env_methods'>Functions and Environment Methods</link></member>
2533 <member><link linkend='sconscript_variables'>SConscript Variables</link></member>
2534 <member><link linkend='construction_variables'>Construction Variables</link></member>
2535 <member><link linkend='configure_contexts'>Configure Contexts</link></member>
2536 <member><link linkend='commandline_construction_variables'>Command-Line Construction Variables</link></member>
2537 <member><link linkend='node_objects'>Node Objects</link></member>
2542 <refsect2 id='construction_environments'>
2543 <title>Construction Environments</title>
2545 <para>A <firstterm>&ConsEnv;</firstterm> is the basic means by which
2546 you communicate build information to
2548 A new &consenv; is created using the
2549 &f-link-Environment;
2552 <programlisting language="python">
2556 <para>&Consenv; attributes called
2557 <firstterm>&ConsVars;</firstterm> may be set
2558 either by specifying them as keyword arguments when the object is created
2559 or by assigning them a value after the object is created.
2560 These two are nominally equivalent:</para>
2562 <programlisting language="python">
2563 env = Environment(FOO='foo')
2567 <!--TODO: how can the user tell which settings are init-only? -->
2568 <para>Note that certain settings which affect tool detection are
2569 referenced only when the tools are initialized,
2570 so you need either to supply them as part of the call to
2571 &f-link-Environment;, or defer tool initialization.
2572 For example, initializing the &MSVC; version you wish to use:
2575 <programlisting language="python">
2576 # initializes msvc to v14.1
2577 env = Environment(MSVC_VERSION="14.1")
2580 # msvc tool was initialized to default, does not reinitialize
2581 env['MSVC_VERSION'] = "14.1"
2583 env = Environment(tools=[])
2584 env['MSVC_VERSION'] = "14.1"
2585 # msvc tool initialization was deferred, so will pick up new value
2589 <para>As a convenience,
2590 &consvars; may also be set or modified by the
2591 <parameter>parse_flags</parameter>
2592 keyword argument during object creation,
2593 which has the effect of the
2594 &f-link-env-MergeFlags;
2595 method being applied to the argument value
2596 after all other processing is completed.
2597 This is useful either if the exact content of the flags is unknown
2598 (for example, read from a control file)
2599 or if the flags need to be distributed to a number of &consvars;.
2600 &f-link-env-ParseFlags; describes how these arguments
2601 are distributed to &consvars;.
2604 <programlisting language="python">
2605 env = Environment(parse_flags='-Iinclude -DEBUG -lm')
2608 <para>This example adds 'include' to
2609 the &cv-link-CPPPATH; &consvar;,
2611 &cv-link-CPPDEFINES;,
2617 An existing &consenv; can be duplicated by calling the &f-link-env-Clone;
2618 method. Without arguments, it will be a copy with the same
2619 settings. Otherwise, &f-env-Clone; takes the same arguments as
2620 &f-link-Environment;, and uses the arguments to create a modified copy.
2624 &SCons; provides a special &consenv; called the
2625 <firstterm>&DefEnv;</firstterm>.
2626 The &defenv; is used only for global functions, that is,
2627 construction activities called without the context of a regular &consenv;.
2628 See &f-link-DefaultEnvironment; for more information.
2631 <para>By default, a new &consenv; is
2632 initialized with a set of builder methods
2633 and &consvars; that are appropriate
2634 for the current platform.
2635 The optional <parameter>platform</parameter> keyword argument may be
2636 used to specify that the &consenv; should
2637 be initialized for a different platform:</para>
2639 <programlisting language="python">
2640 env = Environment(platform='cygwin')
2643 <para>Specifying a platform initializes the appropriate
2644 &consvars; in the environment
2645 to use and generate file names with prefixes
2646 and suffixes appropriate for that platform.</para>
2649 <literal>win32</literal>
2651 <varname>SystemDrive</varname>
2653 <varname>SystemRoot</varname>
2654 variables from the user's external environment
2656 <varname>ENV</varname>
2658 This is so that any executed commands
2659 that use sockets to connect with other systems
2660 will work on Windows systems.</para>
2662 <para>The <parameter>platform</parameter> argument may be
2663 a string value representing
2664 one of the pre-defined platforms
2665 (<literal>aix</literal>,
2666 <literal>cygwin</literal>,
2667 <literal>darwin</literal>,
2668 <literal>hpux</literal>,
2669 <literal>irix</literal>,
2670 <literal>os2</literal>,
2671 <literal>posix</literal>,
2672 <literal>sunos</literal> or
2673 <literal>win32</literal>),
2674 or a callable platform object
2675 returned by a call to &f-link-Platform;
2676 selecting a pre-defined platform,
2677 or it may be a user-supplied callable,
2678 in which case the &Environment; method
2679 will call it to update
2680 the new &consenv;:</para>
2682 <programlisting language="python">
2683 def my_platform(env):
2684 env['VAR'] = 'xyzzy'
2686 env = Environment(platform=my_platform)
2690 Note that supplying a non-default platform or custom
2691 function for initialization
2692 may bypass settings that should happen for the host system
2693 and should be used with care.
2694 It is most useful in the case where the platform is an alternative for
2695 the one that would be auto-detected,
2696 such as <literal>platform="cygwin"</literal>
2697 on a system which would otherwise
2698 identify as <literal>win32</literal>.
2702 The optional <parameter>tools</parameter> and <parameter>toolpath</parameter>
2703 keyword arguments affect the way tools available to the environment are initialized.
2704 See <xref linkend="tools"/> for details.
2708 The optional <parameter>variables</parameter> keyword argument
2709 allows passing a <classname>Variables</classname> object which will be used in the
2710 initialization of the &consenv;
2711 See <xref linkend="commandline_construction_variables"/> for details.
2716 <refsect2 id='tools'>
2717 <title>Tools</title>
2720 &SCons; has many included tool modules
2721 (more properly, <firstterm>tool specification modules</firstterm>)
2722 which are used to help initialize the &consenv; prior to building,
2723 and more can be written to suit a particular purpose,
2724 or added from external sources (a repository of
2725 contributed tools is available).
2726 More information on writing custom tools can be found in the
2727 <link linkend='extending_scons'>Extending SCons</link> section
2728 and specifically <link linkend='tool_modules'>Tool Modules</link>.
2732 An &SCons; tool is only responsible for setup.
2733 For example, if an &SConscript; file declares
2734 the need to construct an object file from
2735 a C-language source file by calling the
2736 &b-link-Object; builder, then a tool module representing
2737 an available C compiler needs to have run first,
2738 to set up that builder and all the &consvars;
2739 it needs in the associated &consenv;.
2740 The tool itself is not called in the process of the build.
2741 Tool setup happens when a &consenv; is constructed,
2742 and in the basic case needs no intervention -
2743 platform-specific lists of default tools are used
2744 to examine the specific capabilities of that platform and
2745 configure the environment,
2746 skipping those tools which are not applicable.
2750 If necessary, a specific set of tools to
2751 initialize in an environment during creation
2752 may be specified using the optional keyword argument
2753 <parameter>tools</parameter>.
2754 <parameter>tools</parameter> must be a list,
2755 even if there are one (or zero) tools.
2756 This is useful to override the defaults,
2757 to specify non-default built-in tools,
2758 and to cause added tools to be called:
2761 <programlisting language="python">
2762 env = Environment(tools=['msvc', 'lex'])
2766 The <parameter>tools</parameter> argument overrides
2767 the default tool list, it does not add to it, so be
2768 sure to include all the tools you need.
2769 For example, if you are building a c/c++ program,
2770 you must specify a tool for at least a compiler and a linker,
2771 as in <literal>tools=['clang', 'link']</literal>.
2775 If the <parameter>tools</parameter> argument is omitted,
2776 or if <parameter>tools</parameter> includes
2777 the reserved name <literal>'default'</literal>,
2778 then &SCons; will auto-detect usable tools,
2779 using the search path from the execution environment
2780 (that is, <varname><replaceable>env</replaceable>['ENV']['PATH']</varname>)
2781 for looking up any external programs,
2782 and the platform name in effect
2783 to determine the default tools for that platform.
2784 Note the contents of &PATH; from the external environment
2785 <varname>os.environ</varname> is <emphasis>not</emphasis> used.
2786 Changing the <varname>PATH</varname> in the execution environment
2787 after the &consenv; is constructed will not cause the tools to
2792 Tools can also be directly called by using the &f-link-Tool;
2796 <para>&SCons; supports the following tool specifications out of the box:</para>
2798 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
2799 <!-- '\" BEGIN GENERATED TOOL DESCRIPTIONS -->
2801 <!-- '\" The descriptions below of the various SCons Tools are generated -->
2802 <!-- '\" from the .xml files located together with the various Python -->
2803 <!-- '\" tool modules in the build engine directory -->
2805 <!-- '\" BEGIN GENERATED TOOL DESCRIPTIONS -->
2806 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
2807 <xsi:include xmlns:xsi="http://www.w3.org/2001/XInclude" href="../generated/tools.gen"/>
2808 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
2809 <!-- '\" END GENERATED TOOL DESCRIPTIONS -->
2811 <!-- '\" The descriptions above of the various SCons Tools are generated -->
2812 <!-- '\" from the .xml files located together with the various Python -->
2813 <!-- '\" tool modules in the build engine directory -->
2815 <!-- '\" END GENERATED TOOL DESCRIPTIONS -->
2816 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
2820 <refsect2 id='builder_methods'>
2821 <title>Builder Methods</title>
2823 <para>You tell &SCons; what to build
2824 by calling <firstterm>Builders</firstterm>,
2825 functions which take particular action(s)
2826 to produce target(s) of a particular type
2827 (conventionally hinted at by the builder name, e.g. &Program;)
2828 from the specified source files.
2829 A builder call is a declaration: &SCons; enters the
2830 specified relationship into its internal dependency node graph,
2831 and only later makes the decision on whether anything is actually built,
2832 since this depends on command-line options,
2833 target selection rules, and whether the target(s) are
2834 out-of-date with respect to the sources.
2839 provides a number of builders, and you can also write your own
2840 (see <link linkend='builder_objects'>Builder Objects</link>).
2841 Builders are created dynamically at run-time,
2842 often (though not always) by tools which determine
2843 whether the external dependencies for the builder are satisfied,
2844 and which perform the necessary setup
2845 (see <link linkend='tools'>Tools</link>).
2846 Builders are attached to a &consenv; as methods.
2847 The available builder methods are registered as
2848 key-value pairs in the
2849 &cv-link-BUILDERS; attribute of the &consenv;,
2850 so the available builders can be examined.
2851 This example displays them for debugging purposes:
2854 <programlisting language="python">
2856 print("Builders:", list(env['BUILDERS']))
2860 Builder methods take two required arguments:
2861 <parameter>target</parameter>
2863 <parameter>source</parameter>.
2864 The <parameter>target</parameter> and
2865 <parameter>source</parameter> arguments
2866 can be specified either as positional arguments,
2867 in which case <parameter>target</parameter> comes first, or as
2868 keyword arguments, using <parameter>target=</parameter>
2869 and <parameter>source=</parameter>.
2870 Although both arguments are nominally required,
2871 if there is a single source and the target can be inferred
2872 the <parameter>target</parameter> argument can be omitted (see below).
2873 Builder methods also take a variety of
2874 keyword arguments, described below.
2877 <para>Because long lists of file names
2878 can lead to a lot of quoting in a builder call,
2880 supplies a &f-link-Split;
2882 and a same-named environment method
2883 that splits a single string
2885 strings of white-space characters as the delimiter
2886 (similar to the &Python; string <function>split</function>
2887 method, but succeeds even if the input isn't a string).</para>
2890 The following are equivalent examples of calling the
2891 &Program; builder method:
2894 <programlisting language="python">
2895 env.Program('bar', ['bar.c', 'foo.c'])
2896 env.Program('bar', Split('bar.c foo.c'))
2897 env.Program('bar', env.Split('bar.c foo.c'))
2898 env.Program(source=['bar.c', 'foo.c'], target='bar')
2899 env.Program(target='bar', source=Split('bar.c foo.c'))
2900 env.Program(target='bar', source=env.Split('bar.c foo.c'))
2901 env.Program('bar', source='bar.c foo.c'.split())
2905 Sources and targets can be specified as a scalar or as a list,
2906 composed of either strings or nodes (more on nodes below).
2907 When specifying path strings,
2908 &Python; follows the POSIX pathname convention:
2909 if a string begins with the operating system pathname separator
2910 (on Windows both the slash and backslash separator are accepted,
2911 and any leading drive specifier is ignored for
2912 the determination) it is considered an absolute path,
2913 otherwise it is a relative path.
2914 If the path string contains no separator characters,
2915 it is searched for as a file in the current directory. If it
2916 contains separator characters, the search follows down
2917 from the starting point, which is the top of the directory tree for
2918 an absolute path and the current directory for a relative path.
2919 The "current directory" in this context is the directory
2920 of the &SConscript; file currently being processed.
2924 &SCons; also recognizes a third way to specify
2925 path strings: if the string begins with
2926 the <emphasis role="bold">#</emphasis> character it is
2927 <firstterm>top-relative</firstterm> - it works like a relative path, but the
2928 search follows down from the project top directory rather than
2929 from the current directory. The <emphasis role="bold">#</emphasis>
2930 can optionally be followed by a pathname separator,
2931 which is ignored if found in that position.
2932 Top-relative paths only work in places where &scons; will
2933 interpret the path (see some examples below). To be
2934 used in other contexts the string will need to be converted
2935 to a relative or absolute path first.
2938 <para>Examples:</para>
2940 <programlisting language="python">
2941 # The comments describing the targets that will be built
2942 # assume these calls are in a SConscript file in the
2943 # a subdirectory named "subdir".
2945 # Builds the program "subdir/foo" from "subdir/foo.c":
2946 env.Program('foo', 'foo.c')
2948 # Builds the program "/tmp/bar" from "subdir/bar.c":
2949 env.Program('/tmp/bar', 'bar.c')
2951 # An initial '#' or '#/' are equivalent; the following
2952 # calls build the programs "foo" and "bar" (in the
2953 # top-level SConstruct directory) from "subdir/foo.c" and
2954 # "subdir/bar.c", respectively:
2955 env.Program('#foo', 'foo.c')
2956 env.Program('#/bar', 'bar.c')
2958 # Builds the program "other/foo" (relative to the top-level
2959 # SConstruct directory) from "subdir/foo.c":
2960 env.Program('#other/foo', 'foo.c')
2962 # This will not work, only SCons interfaces understand '#',
2963 # os.path.exists is pure Python:
2964 if os.path.exists('#inc/foo.h'):
2965 env.Append(CPPPATH='#inc')
2968 <para>When the target shares the same base name
2969 as the source and only the suffix varies,
2970 and if the builder method has a suffix defined for the target file type,
2971 then the target argument may be omitted completely,
2974 will deduce the target file name from
2975 the source file name.
2976 The following examples all build the
2978 <emphasis role="bold">bar</emphasis>
2981 <emphasis role="bold">bar.exe</emphasis>
2982 (on Windows systems)
2983 from the <filename>bar.c</filename> source file:</para>
2985 <programlisting language="python">
2986 env.Program(target='bar', source='bar.c')
2987 env.Program('bar', source='bar.c')
2988 env.Program(source='bar.c')
2989 env.Program('bar.c')
2993 <parameter>srcdir</parameter>
2994 keyword argument specifies that
2995 all source file strings that are not absolute paths
2996 or top-relative paths
2997 shall be interpreted relative to the specified
2998 <parameter>srcdir</parameter>.
2999 The following example will build the
3000 <filename>build/prog</filename>
3002 <filename>build/prog.exe</filename>
3004 program from the files
3005 <filename>src/f1.c</filename>
3007 <filename>src/f2.c</filename>:
3010 <programlisting language="python">
3011 env.Program('build/prog', ['f1.c', 'f2.c'], srcdir='src')
3015 <parameter>parse_flags</parameter>
3016 keyword argument causes behavior similar to the
3017 &f-link-env-MergeFlags; method, where the argument value is
3018 broken into individual settings and merged into the appropriate &consvars;.
3021 <programlisting language="python">
3022 env.Program('hello', 'hello.c', parse_flags='-Iinclude -DEBUG -lm')
3025 <para>This example adds 'include' to
3026 the &cv-link-CPPPATH; &consvar;,
3028 &cv-link-CPPDEFINES;,
3034 <parameter>chdir</parameter>
3036 specifies that the Builder's action(s)
3038 after changing directory.
3040 <parameter>chdir</parameter>
3042 a path string or a directory Node,
3043 scons will change to the specified directory.
3045 <parameter>chdir</parameter>
3046 is not a string or Node
3048 then &scons; will change to the
3049 target file's directory.</para>
3053 &Python; only keeps one current directory
3054 location even if there are multiple threads.
3055 This means that use of the
3056 <parameter>chdir</parameter>
3059 <emphasis>not</emphasis>
3063 because individual worker threads spawned
3064 by &SCons; interfere with each other
3065 when they start changing directory.</para>
3067 <programlisting language="python">
3068 # scons will change to the "sub" subdirectory
3069 # before executing the "cp" command.
3071 target='sub/dir/foo.out',
3072 source='sub/dir/foo.in',
3073 action="cp dir/foo.in dir/foo.out",
3077 # Because chdir is not a string, scons will change to the
3078 # target's directory ("sub/dir") before executing the
3080 env.Command('sub/dir/foo.out', 'sub/dir/foo.in', "cp foo.in foo.out", chdir=True)
3084 <para>Note that &SCons; will
3085 <emphasis>not</emphasis>
3086 automatically modify
3088 &consvars; like &cv-link-TARGET;
3089 and &cv-link-SOURCE;
3090 when using the <parameter>chdir</parameter>
3091 keyword argument--that is,
3092 the expanded file names
3093 will still be relative to
3094 the project top directory,
3095 and consequently incorrect
3096 relative to the chdir directory.
3097 If you use the <parameter>chdir</parameter> keyword argument,
3098 you will typically need to supply a different
3101 <literal>${TARGET.file}</literal>
3103 <literal>${SOURCE.file}</literal>
3104 to use just the filename portion of the
3105 target and source.</para>
3107 <para>Keyword arguments that are not specifically
3108 recognized are treated as &consvar;
3109 <firstterm>overrides</firstterm>,
3110 which replace or add those variables on a limited basis.
3112 will only be in effect when building the target of the builder call,
3113 and will not affect other parts of the build.
3114 For example, if you want to specify
3115 some libraries needed by just one program:</para>
3117 <programlisting language="python">
3118 env.Program('hello', 'hello.c', LIBS=['gl', 'glut'])
3121 <para>or generate a shared library with a non-standard suffix:</para>
3123 <programlisting language="python">
3128 LIBSUFFIXES=['.ocx'],
3132 <para>Note that both the &cv-link-SHLIBSUFFIX;
3133 and &cv-link-LIBSUFFIXES;
3134 &consvars; must be set if you want &scons; to search automatically
3135 for dependencies on the non-standard library names;
3136 see the descriptions of these variables for more information.</para>
3138 <para>Although the builder methods defined by
3141 methods of a &consenv; object,
3142 many may also be called without an explicit environment:</para>
3144 <programlisting language="python">
3145 Program('hello', 'hello.c')
3146 SharedLibrary('word', 'word.cpp')
3149 <para>If called this way, the builder will internally use the
3150 &DefEnv; that consists of the tools and values that
3152 has determined are appropriate for the local system.</para>
3154 <para>Builder methods that can be called without an explicit
3155 environment (indicated in the listing of builders below
3156 without a leading <varname>env.</varname>)
3157 may be called from custom &Python; modules that you
3158 import into an &SConscript; file by adding the following
3159 to the &Python; module:</para>
3161 <programlisting language="python">
3162 from SCons.Script import *
3166 A builder <emphasis>may</emphasis> add additional targets
3167 beyond those requested
3168 if an attached <firstterm>Emitter</firstterm> chooses to do so
3169 (see <xref linkend="builder_objects"/> for more information.
3170 &cv-link-PROGEMITTER; is an example).
3171 For example, the GNU linker takes a command-line argument
3172 <option>-Map=<replaceable>mapfile</replaceable></option>,
3173 which causes it to produce a linker map file in addition
3174 to the executable file actually being linked.
3175 If the &b-link-Program; builder's emitter is configured
3176 to add this mapfile if the option is set,
3177 then two targets will be returned when you only provided for one.
3182 builder methods always return a <classname>NodeList</classname>,
3183 a list-like object whose elements are Nodes.
3184 Nodes are the internal representation of build targets or sources
3185 (see <xref linkend="node_objects"/> for more information).
3186 The returned <classname>NodeList</classname> object
3187 can be passed to other builder methods as source(s)
3188 or to other &SCons; functions or methods
3189 where a path string would normally be accepted.
3193 to add a specific preprocessor define
3194 when compiling one specific object file
3195 but not the others:</para>
3197 <programlisting language="python">
3198 bar_obj_list = env.StaticObject('bar.c', CPPDEFINES='-DBAR')
3199 env.Program("prog", ['foo.c', bar_obj_list, 'main.c'])
3202 <para>Using a Node as in this example
3203 makes for a more portable build
3204 by avoiding having to specify
3205 a platform-specific object suffix
3206 when calling the &b-link-Program; builder method.
3209 <para>The <classname>NodeList</classname> object
3210 is also convenient to pass to the &f-link-Default; function,
3211 for the same reason of avoiding a platform-specific name:
3214 <programlisting language="python">
3215 tgt = env.Program("prog", ["foo.c", "bar.c", "main.c"])
3219 <para>Builder calls will automatically "flatten"
3220 lists passed as source and target, so they are free to
3221 contain elements which are themselves lists, such as
3222 <varname>bar_obj_list</varname>
3223 returned by the &b-link-StaticObject; call.
3224 If you need to manipulate a list of lists returned by builders
3225 directly in &Python; code,
3226 you can either build a new list by hand:</para>
3228 <programlisting language="python">
3229 foo = Object('foo.c')
3230 bar = Object('bar.c')
3231 objects = ['begin.o'] + foo + ['middle.o'] + bar + ['end.o']
3236 <para>Or you can use the &f-link-Flatten;
3237 function supplied by &SCons;
3238 to create a list containing just the Nodes,
3239 which may be more convenient:</para>
3241 <programlisting language="python">
3242 foo = Object('foo.c')
3243 bar = Object('bar.c')
3244 objects = Flatten(['begin.o', foo, 'middle.o', bar, 'end.o'])
3249 <para>Since builder calls return
3250 a list-like object, not an actual &Python; list,
3251 it is not appropriate to use the &Python; add
3252 operator (<literal>+</literal> or <literal>+=</literal>)
3253 to append builder results to a &Python; list.
3254 Because the list and the object are different types,
3255 &Python; will not update the original list in place,
3256 but will instead create a new <classname>NodeList</classname> object
3257 containing the concatenation of the list
3258 elements and the builder results.
3259 This will cause problems for any other &Python; variables
3260 in your SCons configuration
3261 that still hold on to a reference to the original list.
3262 Instead, use the &Python; list
3263 <function>extend</function>
3264 method to make sure the list is updated in-place.
3267 <programlisting language="python">
3270 # Do NOT use += here:
3271 # object_files += Object('bar.c')
3273 # It will not update the object_files list in place.
3275 # Instead, use the list extend method:
3276 object_files.extend(Object('bar.c'))
3279 <para>The path name for a Node's file may be used
3280 by passing the Node to &Python;'s built-in
3281 <function>str</function>
3284 <programlisting language="python">
3285 bar_obj_list = env.StaticObject('bar.c', CPPDEFINES='-DBAR')
3286 print("The path to bar_obj is:", str(bar_obj_list[0]))
3289 <para>Note that because the Builder call returns a
3290 <classname>NodeList</classname>,
3291 you have to access the first element in the list
3292 (<literal>bar_obj_list[0]</literal> in the example)
3293 to get at the Node that actually represents
3294 the object file.</para>
3297 When trying to handle errors that may occur in a builder method,
3298 consider that the corresponding Action is executed at a different
3299 time than the &SConscript; file statement calling the builder.
3300 It is not useful to wrap a builder call in a
3301 <systemitem>try</systemitem> block,
3302 since success in the builder call is not the same as
3303 the builder itself succeeding.
3304 If necessary, a Builder's Action should be coded to exit with
3305 a useful exception message indicating the problem in the &SConscript; files -
3306 programmatically recovering from build errors is rarely useful.
3310 The following builder methods are predefined in the
3311 &SCons; core software distribution.
3312 Depending on the setup of a particular
3313 &consenv; and on the type and software
3314 installation status of the underlying system,
3315 not all builders may be available in that
3317 Since the function calling signature is the same for all builders:
3319 <programlisting language="python">
3320 <function>Buildername</function>(<parameter>target, source, [key=val, ...]</parameter>)
3323 it is omitted in this listing for brevity.
3326 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
3327 <!-- '\" BEGIN GENERATED BUILDER DESCRIPTIONS -->
3329 <!-- '\" The descriptions below of the various SCons Builders are generated -->
3330 <!-- '\" from the .xml files located together with the various Python -->
3331 <!-- '\" builder modules in the build engine directory -->
3333 <!-- '\" BEGIN GENERATED BUILDER DESCRIPTIONS -->
3334 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
3335 <xsi:include xmlns:xsi="http://www.w3.org/2001/XInclude" href="../generated/builders.gen"/>
3336 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
3337 <!-- '\" END GENERATED BUILDER DESCRIPTIONS -->
3339 <!-- '\" The descriptions abocve of the various SCons Builders are generated -->
3340 <!-- '\" from the .xml files located together with the various Python -->
3341 <!-- '\" builder modules in the build engine directory -->
3343 <!-- '\" END GENERATED BUILDER DESCRIPTIONS -->
3344 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
3348 targets of builder methods automatically depend on their sources.
3349 An explicit dependency can
3350 be specified using the
3351 &f-link-env-Depends;
3352 method of a &consenv; (see below).</para>
3357 source files for various programming languages,
3358 so the dependencies do not need to be specified explicitly.
3359 By default, SCons can
3362 Fortran source files with
3363 <filename>.F</filename>
3364 (POSIX systems only),
3365 <filename>.fpp</filename>,
3367 <filename>.FPP</filename>
3369 and assembly language files with
3370 <filename>.S</filename>
3371 (POSIX systems only),
3372 <filename>.spp</filename>,
3374 <filename>.SPP</filename>
3376 for C preprocessor dependencies.
3377 SCons also has default support
3378 for scanning D source files,
3379 You can also write your own Scanners
3380 to add support for additional source file types.
3381 These can be added to the default
3382 Scanner object used by the
3383 &b-link-Object;, &b-link-StaticObject; and &b-link-SharedObject;
3384 Builders by adding them
3386 <classname>SourceFileScanner</classname>
3388 See <xref linkend="scanner_objects"/>
3389 for more information about
3390 defining your own Scanner objects
3392 <classname>SourceFileScanner</classname>
3397 <refsect2 id='env_methods'>
3398 <title>&SCons; Functions and Environment Methods</title>
3401 &SCons; provides a variety of &consenv; methods
3402 and global functions to manipulate the build configuration.
3403 Often, a &consenv; method and a global function with
3404 the same name exist for convenience.
3405 In this section, both forms are shown if the function can be called
3407 The documentation style for these is as follows:
3410 <programlisting language="python">
3411 <function>Function</function>(<parameter>arguments, [optional arguments, ...]</parameter>) # Global function
3412 <replaceable>env</replaceable>.<methodname>Function</methodname>(<parameter>arguments, [optional arguments, ...]</parameter>) # Environment method
3416 In these function signatures,
3417 arguments in brackets (<literal>[]</literal>) are optional,
3418 and ellipses (<literal>...</literal>) indicate possible repetition.
3419 Positional vs. keyword arguments are usually detailed
3420 in the following text, not in the signature itself.
3421 The &Python; positional-only (<literal>/</literal>)
3422 and keyword-only (<literal>*</literal>) markers are not used.
3426 When the &Python; <literal>keyword=value</literal> style is shown,
3427 it can have two meanings.
3428 If the keyword argument is known to the function,
3429 the value is the default for that argument if it is omitted.
3430 If the keyword is unknown to the function,
3431 some methods treat it as a &consvar; assignment;
3432 otherwise an exception is raised for an unknown argument.
3436 A global function and a same-named &consenv; method
3437 have the same base functionality,
3438 with two key differences:
3444 &Consenv; methods that change the environment
3445 act on the environment instance from which they are called,
3446 while the corresponding global function acts on
3447 a special “hidden” &consenv; called the Default Environment.
3448 In some cases, the global function may take
3449 an initial argument giving the object to operate on.
3454 String-valued arguments
3455 (including strings in list-valued arguments)
3456 are subject to construction variable expansion
3457 by the environment method form;
3458 variable expansion is not immediately performed in the global function.
3459 For example, <userinput>Default('$MYTARGET')</userinput>
3460 adds <computeroutput>'$MYTARGET'</computeroutput> to the
3461 list of default targets,
3462 while if the value in <parameter>env</parameter> of
3463 <literal>MYTARGET</literal> is <literal>'mine'</literal>,
3464 <userinput>env.Default('$MYTARGET'</userinput> adds
3465 <computeroutput>'mine'</computeroutput>
3466 to the default targets.
3467 For more details on &consvar; expansion, see the
3468 <link linkend="construction_variables">&Consvars;</link> section.
3474 Global functions are automatically in scope inside &SConscript; files.
3475 If your project adds &Python; modules that you include
3476 via the &Python; <literal>import</literal> statement
3477 from an &SConscript; file,
3478 such code will need to add the functions
3479 to that module’s global scope explicitly.
3480 You can do that by adding the following import to the &Python; module:
3481 <userinput>from SCons.Script import *</userinput>.
3485 &SCons; provides the following &consenv; methods and global functions.
3486 The list can be augmented on a project basis using &f-link-AddMethod;
3490 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
3491 <!-- '\" BEGIN GENERATED FUNCTION DESCRIPTIONS -->
3493 <!-- '\" The descriptions below of the various SCons Tools are generated -->
3494 <!-- '\" from the .xml files located together with the various Python -->
3495 <!-- '\" modules in the build engine directory -->
3497 <!-- '\" BEGIN GENERATED FUNCTION DESCRIPTIONS -->
3498 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
3499 <xsi:include xmlns:xsi="http://www.w3.org/2001/XInclude" href="../generated/functions.gen"/>
3500 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
3501 <!-- '\" END GENERATED FUNCTION DESCRIPTIONS -->
3503 <!-- '\" The descriptions above of the various SCons Tools are generated -->
3504 <!-- '\" from the .xml files located together with the various Python -->
3505 <!-- '\" modules in the build engine directory -->
3507 <!-- '\" END GENERATED FUNCTION DESCRIPTIONS -->
3508 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
3512 <refsect2 id='sconscript_variables'>
3513 <title>SConscript Variables</title>
3515 <para>In addition to the global functions and methods,
3517 supports a number of variables
3518 that can be used for run-time queries in &SConscript; files
3519 to affect how you want the build to be performed.</para>
3522 <varlistentry id="v-ARGLIST">
3523 <term>&ARGLIST;</term>
3526 <emphasis>variable</emphasis>=<emphasis>value</emphasis>
3527 build variable arguments specified on the command line.
3528 Each element in the list is a tuple
3529 consisting of the variable and its value.
3531 <emphasis>variable</emphasis>
3533 <emphasis>value</emphasis>
3534 elements of the tuple
3536 subscripting for elements
3537 <emphasis role="bold">[0]</emphasis>
3539 <emphasis role="bold">[1]</emphasis>
3540 of the tuple, or, more readably, by using tuple unpacking.
3543 <programlisting language="python">
3544 print("first variable, value =", ARGLIST[0][0], ARGLIST[0][1])
3545 print("second variable, value =", ARGLIST[1][0], ARGLIST[1][1])
3546 var, value = ARGLIST[2]
3547 print("third variable, value =", var, value)
3548 for var, value in ARGLIST:
3549 # process variable and value
3553 The values obtained from &ARGLIST;
3554 (or from <link linkend="v-ARGUMENTS">&ARGUMENTS;</link>)
3555 are always strings since they originate from outside the &SCons; process.
3556 As "untrusted data",
3557 they should be validated before usage,
3558 and may need conversion to an appropriate type.
3563 <varlistentry id="v-ARGUMENTS">
3564 <term>&ARGUMENTS;</term>
3566 <para>A dictionary of all the
3567 <emphasis>variable</emphasis>=<emphasis>value</emphasis>
3568 build variable arguments specified on the command line.
3569 The dictionary is in command-line order,
3570 so if a given variable has
3571 more than one value assigned to it
3572 on the command line,
3573 the last (right-most) value is
3574 the one saved in the &ARGUMENTS;
3577 <para>Example:</para>
3579 <programlisting language="python">
3580 if ARGUMENTS.get("debug", ""):
3581 env = Environment(CCFLAGS="-g")
3587 See also <link linkend="v-ARGLIST">&ARGLIST;</link>.
3592 <varlistentry id="v-BUILD_TARGETS">
3593 <term>&BUILD_TARGETS;</term>
3595 <para>A list of the targets which
3597 has been asked to build.
3598 The contents will be either those targets listed
3599 on the command line, or, if none, those targets set
3600 via calls to the &f-link-Default; function.
3602 <emphasis>not</emphasis>
3603 contain any dependent targets that &scons;
3604 selects for building as a result of making the sure the
3605 specified targets are up to date, if those targets
3606 did not appear on the command line.
3607 The list is empty if neither
3608 command line targets nor &Default; calls are present.
3611 The elements of this list may be strings
3612 <emphasis>or</emphasis>
3613 nodes, so you should run the list through the &Python;
3614 <function>str</function>
3615 function to make sure any Node path names
3616 are converted to strings.</para>
3618 <para>Because this list may be taken from the
3619 list of targets specified using the
3621 the contents of the list may change
3622 on each successive call to &Default;.
3623 See <link linkend="v-DEFAULT_TARGETS">&DEFAULT_TARGETS;</link>
3624 for additional information.</para>
3626 <para>Example:</para>
3628 <programlisting language="python">
3629 if 'foo' in BUILD_TARGETS:
3630 print("Don't forget to test the `foo' program!")
3631 if 'special/program' in BUILD_TARGETS:
3632 SConscript('special')
3637 <varlistentry id="v-COMMAND_LINE_TARGETS">
3638 <term>&COMMAND_LINE_TARGETS;</term>
3640 <para>A list of the targets explicitly specified on
3641 the command line. If there are command line targets,
3642 this list has the same contents as
3643 <link linkend="v-BUILD_TARGETS">&BUILD_TARGETS;</link>.
3644 If there are no targets specified on the command line,
3645 this list is empty. The elements of this list are strings.
3646 This can be used, for example,
3647 to take specific actions only
3648 when a certain target(s) are explicitly requested for building.</para>
3650 <para>Example:</para>
3652 <programlisting language="python">
3653 if 'foo' in COMMAND_LINE_TARGETS:
3654 print("Don't forget to test the `foo' program!")
3655 if 'special/program' in COMMAND_LINE_TARGETS:
3656 SConscript('special')
3661 <varlistentry id="v-DEFAULT_TARGETS">
3662 <term>&DEFAULT_TARGETS;</term>
3664 <para>A list of the target
3665 <emphasis>nodes</emphasis>
3666 that have been specified using the
3668 function. If there are no command line
3669 targets, this list will have the same contents as
3670 <link linkend="v-BUILD_TARGETS">&BUILD_TARGETS;</link>.
3671 Since the elements of the list are nodes,
3672 you need to call the &Python;
3673 <function>str</function>
3674 function on them to get the path name for each Node.</para>
3676 <para>Example:</para>
3678 <programlisting language="python">
3679 print(str(DEFAULT_TARGETS[0]))
3680 if 'foo' in [str(t) for t in DEFAULT_TARGETS]:
3681 print("Don't forget to test the `foo' program!")
3684 <para>The contents of the
3686 list changes on each successive call to the
3687 &Default; function:</para>
3689 <programlisting language="python">
3690 print([str(t) for t in DEFAULT_TARGETS]) # originally []
3692 print([str(t) for t in DEFAULT_TARGETS]) # now a node ['foo']
3694 print([str(t) for t in DEFAULT_TARGETS]) # now a node ['foo', 'bar']
3696 print([str(t) for t in DEFAULT_TARGETS]) # back to []
3699 <para>Consequently, be sure to use
3701 only after you've made all of your
3703 or else simply be careful of the order
3704 of these statements in your &SConscript; files
3705 so that you don't look for a specific
3706 default target before it's actually been added to the list.</para>
3712 These variables may be accessed from custom &Python; modules that you
3713 import into an &SConscript; file by adding the following
3714 to the &Python; module:</para>
3716 <programlisting language="python">
3717 from SCons.Script import *
3722 <refsect2 id='construction_variables'>
3723 <title>Construction Variables</title>
3724 <!-- XXX From Gary Ruben, 23 April 2002: -->
3725 <!-- I think it would be good to have an example with each construction -->
3726 <!-- variable description in the documentation. -->
3728 <!-- CC The C compiler -->
3729 <!-- Example: env["CC"] = "c68x" -->
3730 <!-- Default: env["CC"] = "cc" -->
3732 <!-- CCCOM The command line ... -->
3734 <!-- To generate the compiler line c68x \-ps \-qq \-mr \-o $TARGET $SOURCES -->
3735 <!-- env["CC"] = "c68x" -->
3736 <!-- env["CFLAGS"] = "\-ps \-qq \-mr" -->
3737 <!-- env["CCCOM"] = "$CC $CFLAGS \-o $TARGET $SOURCES -->
3739 <!-- (I dunno what this is ;\-) -->
3742 <firstterm>&ConsVars;</firstterm> are key-value pairs
3743 used to store information in a &consenv; that
3744 is needed needed for builds using that environment.
3745 &Consvar; naming must follow the same rules as
3746 &Python; identifier naming:
3747 the initial character must be an underscore or letter,
3748 followed by any number of underscores, letters, or digits.
3749 The convention is to use uppercase for all letters
3750 for easier visual identification.
3754 &Consvars; are used to hold many different types of information.
3755 For example, the &cv-link-CPPDEFINES; variable is how to tell a C/C++
3756 compiler about preprocessor macros you need for your build.
3757 The tool discovery that &SCons; performs will cause the
3758 &cv-link-CXX; variable to hold the name of the C++ compiler,
3759 if one was detected on the system, but you can give it a different
3760 value to force a compiler command of a different name to be used.
3761 Some variables contain lists of filename suffixes that are recognized
3762 by a particular compiler chain.
3763 &cv-link-BUILDERS; contains a mapping of configured
3764 Builder names (e.g. &b-link-Textfile;) to the actual Builder instance
3765 to call when that Builder is used.
3766 &Consvars; may include references to other &consvars;:
3767 the same tool which set up the C/C++ compiler will also set
3768 up an "action string", describing how to invoke that compiler,
3769 in &cv-link-CXXCOM;, which contains other &consvars;
3770 using <literal>$VARIABLE</literal> syntax.
3771 These references will be expanded and replaced on use
3772 (see <link linkend="variable_substitution">Variable Substitution</link>).
3776 &Consvars; are referenced as if they were keys and values
3777 in a &Python; dictionary:
3780 <programlisting language="python">
3782 flags = env.get("CPPDEFINES", [])
3785 <para>&Consvars; can also be retrieved and set
3786 by using the &f-link-Dictionary;
3787 method of the &consenv; to create an actual
3790 <programlisting language="python">
3791 cvars = env.Dictionary()
3796 in the previous example, since <varname>cvars</varname>
3797 is an external copy, the value of &cv-CC; in the
3798 &consenv; itself is not changed by the assignment.
3801 <para>&Consvars; can set by passing them as keyword arguments
3802 when creating a new &consenv;:
3805 <programlisting language="python">
3806 env = Environment(CC="cc")
3809 <para>or when copying a &consenv; using the
3810 &f-link-Clone; method:</para>
3812 <programlisting language="python">
3813 env2 = env.Clone(CC="cl.exe")
3817 &Consvars; can also be supplied as keyword
3818 arguments to a builder, in which case those settings
3819 affect only the work done by that builder call,
3820 and not the &consenv; as a whole.
3821 This concept is called an <firstterm>override</firstterm>:
3824 <programlisting language="python">
3825 env.Program('hello', 'hello.c', LIBS=['gl', 'glut'])
3828 <para>Many useful &consvars; are automatically defined by
3829 &SCons;, tuned to the specific platform in use,
3830 and you can modify these or define any additional &consvars;
3831 for use in your own Builders, Scanners and other tools.
3832 Take care not to overwrite ones which &SCons; is using.
3833 The following is a list of predefined &consvars;.
3834 Pay attention to whether the values are ones
3835 you may be expected to set vs.
3836 ones that are set to expected values by
3837 internal tools and other initializations
3838 and probably should not be modified.
3841 <para>Note the actual list available
3842 at execution time will never include all of these, as the ones
3843 detected as not being applicable (wrong platform, necessary
3844 external command or files not installed, etc.) will not be set up.
3845 Correct build setups should be resilient to the possible
3846 absence of certain &consvars; before using them,
3847 for example by using a &Python; dictionary
3848 <function>get</function> method to retrieve the value and
3849 taking alternative action if the return indicates the variable is unset.
3850 The &f-link-env-Dump; method can be called to examine the
3851 &consvars; set in a particular environment.
3854 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
3855 <!-- '\" BEGIN GENERATED CONSTRUCTION VARIABLE DESCRIPTIONS -->
3857 <!-- '\" The descriptions below of the various SCons construction variables -->
3858 <!-- '\" are generated from the .xml files located together with the various -->
3859 <!-- '\" Python modules in the build engine directory -->
3861 <!-- '\" BEGIN GENERATED CONSTRUCTION VARIABLE DESCRIPTIONS -->
3862 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
3863 <xsi:include xmlns:xsi="http://www.w3.org/2001/XInclude" href="../generated/variables.gen"/>
3864 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
3865 <!-- '\" END GENERATED CONSTRUCTION VARIABLE DESCRIPTIONS -->
3867 <!-- '\" The descriptions above of the various SCons construction variables -->
3868 <!-- '\" are generated from the .xml files located together with the various -->
3869 <!-- '\" Python modules in the build engine directory -->
3871 <!-- '\" END GENERATED CONSTRUCTION VARIABLE DESCRIPTIONS -->
3872 <!-- '\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -->
3876 <refsect2 id='configure_contexts'>
3877 <title>Configure Contexts</title>
3881 <firstterm>&configure_context;</firstterm>,
3882 an integrated mechanism similar to the
3883 various <constant>AC_CHECK</constant> macros in GNU &Autoconf;
3884 for testing the existence of external items needed
3885 for the build, such as C header files, libraries, etc.
3886 The mechanism is portable across platforms.
3891 does not maintain an explicit cache of the tested values
3892 (this is different than &Autoconf;),
3893 but uses its normal dependency tracking to keep the checked values
3894 up to date. However, users may override this behavior with the
3895 <link linkend="opt-config"><option>--config</option></link>
3896 command line option.</para>
3900 <term><function>Configure</function>(<parameter>env, [custom_tests, conf_dir, log_file, config_h, clean, help]</parameter>)</term>
3901 <term><replaceable>env</replaceable>.<methodname>Configure</methodname>(<parameter>[custom_tests, conf_dir, log_file, config_h, clean, help]</parameter>)</term>
3903 <para>Create a &configure_context;, which tracks information
3904 discovered while running tests. The context includes a local &consenv;
3905 (available as <replaceable>context</replaceable>.<varname>env</varname>)
3906 which is used when running the tests and
3907 which can be updated with the check results.
3908 Only one context may be active
3909 at a time, but a new context can be created
3910 after the active one is completed.
3911 For the global function form, the required <parameter>env</parameter>
3912 describes the initial values for the context's local &consenv;;
3913 for the &consenv; method form the instance provides the values.
3916 <emphasis>Changed in version 4.0</emphasis>: raises an exception
3917 on an attempt to create a new context when there is an active context.
3919 <para><parameter>custom_tests</parameter>
3920 specifies a dictionary containing custom checks
3921 (see <link linkend="custom_checks">details below</link>).
3922 The default value is <constant>None</constant>,
3923 to indicate there are no custom checks in the &configure_context;.</para>
3925 <parameter>conf_dir</parameter>
3926 specifies a directory where the test cases are built.
3927 This directory is not used for building normal targets.
3928 The default value is
3929 <quote><filename>#/.sconf_temp</filename></quote>.</para>
3931 <parameter>log_file</parameter>
3932 specifies a file which collects the output from commands
3933 that are executed to check for the existence of header files, libraries, etc.
3934 The default is <quote><filename>#/config.log</filename></quote>.
3935 If you are using variant directories,
3936 you may want to place the log file for a given build
3937 under that build's variant directory.</para>
3939 <parameter>config_h</parameter>
3940 specifies a C header file where the results of tests
3941 will be written. The results will consist of lines like
3942 <literal>#define HAVE_STDIO_H</literal>,
3943 <literal>#define HAVE_LIBM</literal>, etc.
3944 Customarily, the name chosen is <quote><filename>config.h</filename></quote>.
3945 The default is to not write a
3946 <parameter>config_h</parameter>
3948 You can specify the same
3949 <parameter>config_h</parameter>
3950 file in multiple calls to &Configure;,
3951 in which case &SCons;
3952 will concatenate all results in the specified file.
3954 uses its normal dependency checking
3955 to decide if it's necessary to rebuild
3957 <parameter>config_h</parameter>
3959 This means that the file is not necessarily re-built each
3961 but is only rebuilt if its contents will have changed
3962 and some target that depends on the
3963 <parameter>config_h</parameter>
3964 file is being built.</para>
3965 <para>The <parameter>clean</parameter>
3967 <parameter>help</parameter>
3968 arguments can be used to suppress execution of the configuration
3970 <option>-c</option>/<option>--clean</option>
3972 <option>-H</option>/<option>-h</option>/<option>--help</option>
3973 options are used, respectively.
3974 The default behavior is always to execute
3975 &configure_context; tests,
3976 since the results of the tests may
3977 affect the list of targets to be cleaned
3979 If the configure tests do not affect these,
3980 then you may add the
3981 <option>clean=False</option>
3983 <option>help=False</option>
3986 to avoid unnecessary test execution.</para>
3991 <term><replaceable>context</replaceable>.<methodname>Finish</methodname>()</term>
3993 <para>This method must be called after configuration is done.
3994 Though required, this is not enforced except
3995 if &Configure; is called again while there is still an active context,
3996 in which case an exception is raised.
3997 &Finish; returns the environment as modified
3998 during the course of running the configuration checks.
3999 After this method is called, no further checks can be performed
4000 with this configuration context.
4001 However, you can create a new
4002 &configure_context; to perform additional checks.
4008 <para>Example of a typical Configure usage:</para>
4010 <programlisting language="python">
4012 conf = Configure(env)
4013 if not conf.CheckCHeader("math.h"):
4014 print("We really need math.h!")
4016 if conf.CheckLibWithHeader("qt", "qapp.h", "c++", "QApplication qapp(0,0);"):
4017 # do stuff for qt - usage, e.g.
4018 conf.env.Append(CPPDEFINES="WITH_QT")
4022 <para>A &configure_context;
4023 has the following predefined methods which
4024 can be used to perform checks. Where
4025 <parameter>language</parameter> is an optional parameter,
4026 it specifies the compiler to use for the check,
4027 currently a choice of C or C++.
4028 The spellings accepted for
4029 C are <quote>C</quote> or <quote>c</quote>;
4030 for C++ the value can be
4031 <quote>CXX</quote>, <quote>cxx</quote>, <quote>C++</quote>
4032 or <quote>c++</quote>.
4033 If <parameter>language</parameter> is omitted,
4034 <quote>C</quote> is assumed.
4039 <term><replaceable>context</replaceable>.<methodname>CheckHeader</methodname>(<parameter>header, [include_quotes, language]</parameter>)</term>
4042 <parameter>header</parameter>
4043 is usable in the specified <parameter>language</parameter>.
4044 <parameter>header</parameter>
4046 in which case the last item in the list
4047 is the header file to be checked,
4048 and the previous list items are
4050 <literal>#include</literal>
4051 lines should precede the
4052 header line being checked for.
4053 The optional argument
4054 <parameter>include_quotes</parameter>
4056 a two character string, where the first character denotes the opening
4057 quote and the second character denotes the closing quote.
4058 By default, both characters are <markup>"</markup> (double quote).
4060 <para>Returns a boolean indicating success or failure.</para>
4065 <term><replaceable>context</replaceable>.<methodname>CheckCHeader</methodname>(<parameter>header, [include_quotes]</parameter>)</term>
4068 <parameter>header</parameter>
4069 is usable when compiling a C language program.
4070 <parameter>header</parameter>
4072 in which case the last item in the list
4073 is the header file to be checked,
4074 and the previous list items are
4076 <literal>#include</literal>
4077 lines should precede the
4078 header line being checked for.
4079 The optional argument
4080 <parameter>include_quotes</parameter>
4082 a two character string, where the first character denotes the opening
4083 quote and the second character denotes the closing quote.
4084 By default, both characters are <markup>"</markup> (double quote).
4085 Note this is a wrapper around
4086 <function>CheckHeader</function>.
4087 Returns a boolean indicating success or failure.</para>
4092 <term><replaceable>context</replaceable>.<methodname>CheckCXXHeader</methodname>(<parameter>header, [include_quotes]</parameter>)</term>
4095 <parameter>header</parameter>
4096 is usable when compiling a C++ language program.
4097 <parameter>header</parameter>
4099 in which case the last item in the list
4100 is the header file to be checked,
4101 and the previous list items are
4103 <literal>#include</literal>
4104 lines should precede the
4105 header line being checked for.
4106 The optional argument
4107 <parameter>include_quotes</parameter>
4109 a two character string, where the first character denotes the opening
4110 quote and the second character denotes the closing quote.
4111 By default, both characters are <markup>"</markup> (double quote).
4112 Note this is a wrapper around
4113 <function>CheckHeader</function>.
4114 Returns a boolean indicating success or failure.</para>
4119 <term><replaceable>context</replaceable>.<methodname>CheckFunc</methodname>(<parameter>function_name, [header, language, funcargs]</parameter>)</term>
4121 <para>Checks if <parameter>function_name</parameter> is usable
4122 in the context's local environment, using the compiler
4123 specified by <parameter>language</parameter> - that is,
4124 can a check referencing it be compiled using the current values
4125 of &cv-link-CFLAGS;, &cv-link-CPPFLAGS;,
4126 &cv-link-LIBS; or other relevant &consvars;.
4131 <parameter>header</parameter>
4132 argument is a string representing a code fragment
4133 to place at the top of the test program
4134 that will be compiled to check if the function exists.
4135 If omitted, the default stanza will be
4136 (with <parameter>function_name</parameter> appropriately substituted):
4139 <programlisting language="C">
4143 char function_name(void);
4147 If <parameter>header</parameter> is supplied, it should <emphasis>not</emphasis> include
4148 the standard header file that declares <parameter>function_name</parameter> and it
4149 <emphasis>should</emphasis> include a dummy prototype similar to the default case. If
4150 this is not possible, the optional <parameter>funcargs</parameter> argument can be used
4151 to specify a string containing an argument list with the same number and type of
4152 arguments as the prototype. The arguments can simply be constant values of the correct
4153 type. Modern C/C++ compilers reject implicit function declarations and may also reject
4154 function calls whose arguments are not type compatible with the prototype.
4158 <emphasis>Changed in version 4.7.0: added the <parameter>funcargs</parameter>.</emphasis>
4161 <para>Returns a boolean indicating success or failure.</para>
4166 <term><replaceable>context</replaceable>.<methodname>CheckLib</methodname>(<parameter>[library, symbol, header, language, autoadd=True, append=True, unique=False]</parameter>) </term>
4169 <parameter>library</parameter>
4171 <parameter>symbol</parameter> by compiling a simple stub program
4172 with the compiler selected by <parameter>language</parameter>,
4173 and optionally adds that library to the context.
4174 If supplied, the text of <parameter>header</parameter> is included at the
4176 If <parameter>autoadd</parameter> is true (the default),
4177 and the library provides the specified
4178 <parameter>symbol</parameter> (as defined by successfully
4179 linking the stub program),
4180 it is added to the &cv-link-LIBS; &consvar; in the context.
4181 if <parameter>append</parameter> is true (the default),
4182 the library is appended, otherwise it is prepended.
4183 If <parameter>unique</parameter> is true,
4184 and the library would otherwise be added but is
4185 already present in &cv-link-LIBS; in the configure context,
4186 it will not be added again. The default is <literal>False</literal>.
4189 <parameter>library</parameter> can be a list of library names,
4190 or <constant>None</constant> (the default if the argument is omitted).
4191 If the former, <parameter>symbol</parameter> is checked against
4192 each library name in order, returning
4193 (and reporting success) on the first
4194 successful test; if the latter,
4195 it is checked with the current value of &cv-LIBS;
4196 (in this case no library name would be added).
4197 If <parameter>symbol</parameter>
4198 is omitted or <constant>None</constant>,
4199 then <function>CheckLib</function>
4201 you can link against the specified
4202 <parameter>library</parameter>,
4203 Note though it is legal syntax, it would
4204 not be very useful to call this method
4205 with <parameter>library</parameter>
4206 and <parameter>symbol</parameter> both
4207 omitted or <constant>None</constant> -
4208 at least one should be supplied.
4210 <para>Returns a boolean indicating success or failure.</para>
4212 <emphasis>Changed in version 4.5.0: added the
4213 <parameter>append</parameter> and <parameter>unique</parameter>
4214 parameters.</emphasis>
4220 <term><replaceable>context</replaceable>.<methodname>CheckLibWithHeader</methodname>(<parameter>library, header, [language, call, autoadd=True, append=True, unique=False]</parameter>)</term>
4223 <para>Provides an alternative to the
4224 <methodname>CheckLib</methodname> method
4225 for checking for libraries usable in a build.
4226 <parameter>library</parameter>
4227 specifies a library or list of libraries to check.
4228 <parameter>header</parameter>
4229 specifies a header to include in the test program,
4230 and <parameter>language</parameter> indicates the compiler to use.
4231 <parameter>header</parameter>
4233 in which case the last item in the list
4234 is the header file to be checked,
4235 and the previous list items are
4237 <literal>#include</literal>
4238 lines should precede the
4239 header line being checked for.
4241 (must be a valid expression, including a trailing semicolon)
4242 to serve as the test can be supplied in
4243 <parameter>call</parameter>;
4245 the default checks the ability to link against the specified
4246 <parameter>library</parameter>.
4247 If <parameter>autoadd</parameter> is true (the default),
4248 the first library that passes the check
4249 is added to the &cv-link-LIBS; &consvar; in the context
4250 and the method returns.
4251 If <parameter>append</parameter> is true (the default),
4252 the library is appended, otherwise prepended.
4253 If <parameter>unique</parameter> is true,
4254 and the library would otherwise be added but is
4255 already present in &cv-link-LIBS; in the configure context,
4256 it will not be added again. The default is <literal>False</literal>.
4258 <para>Returns a boolean indicating success or failure.</para>
4260 <emphasis>Changed in version 4.5.0: added the
4261 <parameter>append</parameter> and <parameter>unique</parameter>
4262 parameters.</emphasis>
4268 <term><replaceable>context</replaceable>.<methodname>CheckType</methodname>(<parameter>type_name, [includes, language]</parameter>)</term>
4270 <para>Checks for the existence of a type defined by
4271 <literal>typedef</literal>.
4272 <parameter>type_name</parameter>
4273 specifies the typedef name to check for.
4274 <parameter>includes</parameter>
4275 is a string containing one or more
4276 <literal>#include</literal>
4277 lines that will be inserted into the program
4278 that will be run to test for the existence of the type.
4281 <programlisting language="python">
4282 sconf.CheckType('foo_type', '#include "my_types.h"', 'C++')
4285 <para>Returns a boolean indicating success or failure.</para>
4290 <term><replaceable>context</replaceable>.<methodname>CheckTypeSize</methodname>(<parameter>type_name, [header, language, expect]</parameter>)</term>
4292 <para>Checks for the size of a type defined by
4293 <literal>typedef</literal>.
4294 <parameter>type_name</parameter>
4295 specifies the typedef name to check for.
4297 <parameter>header</parameter>
4298 argument is a string
4302 that will be compiled
4303 to check if the type exists;
4304 the default is empty.
4306 <parameter>expect</parameter>,
4307 is supplied, it should be an integer size;
4308 &CheckTypeSize; will fail unless
4309 <parameter>type_name</parameter> is actually
4311 Returns the size in bytes, or zero if the type was not found
4312 (or if the size did not match optional <parameter>expect</parameter>).</para>
4317 <programlisting language="python">
4318 CheckTypeSize('short', expect=2)
4321 <para>will return the size <literal>2</literal> only if short is
4322 actually two bytes.</para>
4327 <term><replaceable>context</replaceable>.<methodname>CheckCC</methodname>()</term>
4329 <para>Checks whether the C compiler
4330 (as defined by the &cv-link-CC; &consvar;) works,
4331 by trying to compile a small source file.
4332 This provides a more rigorous check:
4333 by default, &SCons; itself only detects if there is a program
4334 with the correct name, not if it is a functioning compiler.
4335 Returns a boolean indicating success or failure.</para>
4337 <para>The test program will be built with the
4338 same command line as the one used by the &b-link-Object; builder
4339 for C source files, so by setting relevant &consvars;
4340 it can be used to detect if particular compiler flags will
4341 be accepted or rejected by the compiler.
4343 <para>Returns a boolean indicating success or failure.</para>
4348 <term><replaceable>context</replaceable>.<methodname>CheckCXX</methodname>()</term>
4350 <para>Checks whether the C++ compiler
4351 (as defined by the &cv-link-CXX; &consvar;) works,
4352 by trying to compile a small source file.
4353 This provides a more rigorous check:
4354 by default, &SCons; itself only detects if there is a program
4355 with the correct name, not if it is a functioning compiler.
4356 Returns a boolean indicating success or failure.</para>
4358 <para>The test program will be built with the
4359 same command line as the one used by the &b-link-Object; builder
4360 for C++ source files, so by setting relevant &consvars;
4361 it can be used to detect if particular compiler flags will
4362 be accepted or rejected by the compiler.
4364 <para>Returns a boolean indicating success or failure.</para>
4369 <term><replaceable>context</replaceable>.<methodname>CheckSHCC</methodname>()</term>
4371 <para>Checks whether the shared-object C compiler (as defined by the
4372 &cv-link-SHCC; &consvar;) works
4373 by trying to compile a small source file.
4374 This provides a more rigorous check:
4375 by default, &SCons; itself only detects if there is a program
4376 with the correct name, not if it is a functioning compiler.
4377 Returns a boolean indicating success or failure.</para>
4379 <para>The test program will be built with the
4380 same command line as the one used by the &b-link-SharedObject; builder
4381 for C source files, so by setting relevant &consvars;
4382 it can be used to detect if particular compiler flags will
4383 be accepted or rejected by the compiler.
4384 Note this does not check whether a shared library/dll can
4387 <para>Returns a boolean indicating success or failure.</para>
4392 <term><replaceable>context</replaceable>.<methodname>CheckSHCXX</methodname>()</term>
4394 <para>Checks whether the shared-object C++ compiler (as defined by the
4395 &cv-link-SHCXX; &consvar;)
4396 works by trying to compile a small source file.
4397 This provides a more rigorous check:
4398 by default, &SCons; itself only detects if there is a program
4399 with the correct name, not if it is a functioning compiler.
4400 Returns a boolean indicating success or failure.</para>
4402 <para>The test program will be built with the
4403 same command line as the one used by the &b-link-SharedObject; builder
4404 for C++ source files, so by setting relevant &consvars;
4405 it can be used to detect if particular compiler flags will
4406 be accepted or rejected by the compiler.
4407 Note this does not check whether a shared library/dll can
4410 <para>Returns a boolean indicating success or failure.</para>
4415 <term><replaceable>context</replaceable>.<methodname>CheckProg</methodname>(<parameter>prog_name</parameter>)</term>
4418 <parameter>prog_name</parameter>
4419 exists in the path &SCons; will use at build time.
4420 (<replaceable>context</replaceable>.<varname>env['ENV']['PATH']</varname>).
4421 Returns a string containing the path to the program,
4422 or <constant>None</constant> on failure.</para>
4427 <term><replaceable>context</replaceable>.<methodname>CheckDeclaration</methodname>(<parameter>symbol, [includes, language]</parameter>)</term>
4429 <para>Checks if the specified
4430 <parameter>symbol</parameter>
4432 <parameter>includes</parameter>
4433 is a string containing one or more
4434 <literal>#include</literal>
4435 lines that will be inserted into the program
4436 that will be run to test for the existence of the symbol.
4438 <para>Returns a boolean indicating success or failure.</para>
4443 <term><replaceable>context</replaceable>.<methodname>CheckMember</methodname>(<parameter>aggregate_member,
4444 [header, language]</parameter>)
4447 <para>Checks for the existence of a member of the C/C++ struct or class.
4448 <parameter>aggregate_member</parameter>
4449 specifies the struct/class and member to check for.
4450 <parameter>header</parameter>
4451 is a string containing one or more
4452 <literal>#include</literal>
4453 lines that will be inserted into the program
4454 that will be run to test for the existence of the member.
4458 <programlisting language="python">
4459 sconf.CheckMember('struct tm.tm_sec', '#include <time.h>')
4463 Returns a boolean indicating success or failure.
4471 <term><replaceable>context</replaceable>.<methodname>Define</methodname>(<parameter>symbol, [value, comment]</parameter>)</term>
4473 <para>This method does not check for anything, but rather forces
4474 the definition of a preprocessor macro that will be added
4475 to the configuration header file.
4476 <parameter>name</parameter> is the macro's identifier.
4477 If <parameter>value</parameter> is given,
4478 it will be be used as the macro replacement value.
4479 If <parameter>value</parameter> is a string and needs to
4480 display with quotes, the quotes need to be included,
4481 as in <literal>'"string"'</literal>
4483 <parameter>comment</parameter> is given,
4484 it is inserted as a comment above the macro definition
4485 (suitable comment marks will be added automatically).
4486 This is analogous to using <constant>AC_DEFINE</constant> in &Autoconf;.
4489 <para>Examples:</para>
4491 <programlisting language="python">
4493 conf = Configure(env)
4495 # Puts the following line in the config header file:
4497 conf.Define("A_SYMBOL")
4499 # Puts the following line in the config header file:
4500 # #define A_SYMBOL 1
4501 conf.Define("A_SYMBOL", 1)
4505 <para>Examples of quoting string values:</para>
4507 <programlisting language="python">
4509 conf = Configure(env)
4511 # Puts the following line in the config header file:
4512 # #define A_SYMBOL YA
4513 conf.Define("A_SYMBOL", "YA")
4515 # Puts the following line in the config header file:
4516 # #define A_SYMBOL "YA"
4517 conf.Define("A_SYMBOL", '"YA"')
4521 <para>Example including comment:</para>
4523 <programlisting language="python">
4525 conf = Configure(env)
4527 # Puts the following lines in the config header file:
4528 # /* Set to 1 if you have a symbol */
4529 # #define A_SYMBOL 1
4530 conf.Define("A_SYMBOL", 1, "Set to 1 if you have a symbol")
4537 <para id="custom_checks" xreflabel="custom checks">
4538 You can define your own custom checks
4539 in addition to using the predefined checks.
4540 To enable custom checks,
4541 pass a dictionary to the &f-link-Configure; function
4542 as the <parameter>custom_tests</parameter> parameter.
4543 The dictionary maps the names of the checks
4544 to the custom check callables
4545 (either a &Python; function or an instance of a class implementing a
4546 <methodname>__call__</methodname> method).
4547 Each custom check will be called with a
4548 a <classname>CheckContext</classname>
4549 instance as the first parameter followed by the remaining arguments,
4550 which must be supplied by the user of the check.
4551 A <classname>CheckContext</classname> is not the same as
4552 a configure context; rather it is an instance of a class
4553 which contains a configure context
4554 (available as <replaceable>chk_ctx</replaceable>.<varname>sconf</varname>).
4555 A <classname>CheckContext</classname>
4556 provides the following methods which custom checks
4557 can make use of::</para>
4561 <term><replaceable>chk_ctx</replaceable>.<methodname>Message</methodname>(<parameter>text</parameter>)</term>
4564 <para>Displays <parameter>text</parameter>
4565 as an indicator of progress.
4566 For example: <computeroutput>Checking for library X...</computeroutput>.
4567 Usually called before the check is started.
4573 <term><replaceable>chk_ctx</replaceable>.<methodname>Result</methodname>(<parameter>res</parameter>)</term>
4576 <para>Displays a result message as an indicator of progress.
4577 If <parameter>res</parameter> is an integer,
4578 displays <computeroutput>yes</computeroutput>
4579 if <parameter>res</parameter> evaluates true
4580 or <computeroutput>no</computeroutput> if false.
4581 If <parameter>res</parameter> is a string,
4582 it is displayed as-is.
4583 Usually called after the check has completed.</para>
4588 <term><replaceable>chk_ctx</replaceable>.<methodname>TryCompile</methodname>(<parameter>text, extension=''</parameter>)</term>
4590 <para>Checks if a file containing <parameter>text</parameter>
4591 and given the specified <parameter>extension</parameter> (e.g.
4592 <literal>'.c'</literal>)
4593 can be compiled to an object file
4594 using the environment's &b-link-Object; builder.
4595 Returns a boolean indicating success or failure.</para>
4600 <term><replaceable>chk_ctx</replaceable>.<methodname>TryLink</methodname>(<parameter>text, extension=''</parameter>)</term>
4602 <para>Checks if a file containing <parameter>text</parameter>
4603 and given the specified <parameter>extension</parameter> (e.g.
4604 <literal>'.c'</literal>)
4605 can be compiled to an executable program
4606 using the environment's &b-link-Program; builder.
4607 Returns a boolean indicating success or failure.</para>
4612 <term><replaceable>chk_ctx</replaceable>.<methodname>TryRun</methodname>(<parameter>text, extension=''</parameter>)</term>
4614 <para>Checks if a file containing <parameter>text</parameter>
4615 and given the specified <parameter>extension</parameter> (e.g.
4616 <literal>'.c'</literal>)
4617 can be compiled to an excutable program
4618 using the environment's &b-link-Program; builder and subsequently executed.
4619 Execution is only attempted if the build succeeds.
4620 If the program executes successfully
4621 (that is, its return status is <literal>0</literal>),
4622 a tuple <literal>(True, outputStr)</literal>
4623 is returned, where <varname>outputStr</varname>
4624 is the standard output of the program.
4625 If the program fails execution
4626 (its return status is non-zero),
4627 then <literal>(False, '')</literal> is returned.</para>
4632 <term><replaceable>chk_ctx</replaceable>.<methodname>TryAction</methodname>(<parameter>action, [text, extension='']</parameter>)</term>
4634 <para>Checks if the specified
4635 <parameter>action</parameter>
4636 with an optional source file
4637 (contents <parameter>text</parameter>,
4638 given extension <parameter>extension</parameter>)
4640 <parameter>action</parameter>
4641 may be anything which can be converted to an
4642 <link linkend="action_objects">Action Object</link>.
4644 <literal>(True, outputStr)</literal>
4645 is returned, where <varname>outputStr</varname>
4646 is the content of the target file.
4648 <literal>(False, '')</literal>
4654 <term><replaceable>chk_ctx</replaceable>.<methodname>TryBuild</methodname>(<parameter>builder, [text, extension='']</parameter>)</term>
4656 <para>Low level implementation for testing specific builds;
4657 the methods above are based on this method.
4658 Given the Builder instance
4659 <parameter>builder</parameter>
4661 <parameter>text</parameter>
4662 of a source file with optional
4663 <parameter>extension</parameter>,
4664 returns a boolean indicating success or failure.
4666 <replaceable>chk_ctx</replaceable>.<varname>lastTarget</varname>
4667 is set to the build target node if the build was successful.</para>
4671 <para>Example of implementing and using custom checks:</para>
4673 <programlisting language="python">
4674 def CheckQt(chk_ctx, qtdir):
4675 chk_ctx.Message('Checking for qt ...')
4676 lastLIBS = chk_ctx.env['LIBS']
4677 lastLIBPATH = chk_ctx.env['LIBPATH']
4678 lastCPPPATH = chk_ctx.env['CPPPATH']
4679 chk_ctx.env.Append(LIBS='qt', LIBPATH=qtdir + '/lib', CPPPATH=qtdir + '/include')
4680 ret = chk_ctx.TryLink(
4682 #include <qapp.h>
4683 int main(int argc, char **argv) {
4684 QApplication qapp(argc, argv);
4690 chkctx.env.Replace(LIBS=lastLIBS, LIBPATH=lastLIBPATH, CPPPATH=lastCPPPATH)
4695 conf = Configure(env, custom_tests={'CheckQt': CheckQt})
4696 if not conf.CheckQt('/usr/lib/qt'):
4697 print('We really need qt!')
4704 <refsect2 id='commandline_construction_variables'>
4705 <title>Command-Line Construction Variables</title>
4708 &SCons; depends on information stored in &consvars; to
4709 control how targets are built.
4710 It is often necessary to pass
4711 specialized information at build time
4712 to override the variables in the build scripts.
4713 This can be done through variable-assignment arguments
4714 on the command line and/or in stored variable files.
4718 For the case where you want to specify new
4719 values for &consvars;,
4720 &SCons; provides a <firstterm>&Variables;</firstterm>
4721 object to simplify collecting those
4722 and updating a &consenv; with the values.
4723 This helps processing commands lines like this:
4727 <userinput>scons VARIABLE=foo OTHERVAR=bar</userinput>
4731 Variables supplied on the command line
4732 can always be manually processed by iterating the
4733 <link linkend="v-ARGUMENTS">&ARGUMENTS;</link> dictionary
4734 or the <link linkend="v-ARGLIST">&ARGLIST;</link> list,
4735 However, using a &Variables; object allows you to describe
4736 anticipated variables,
4737 perform necessary type conversion,
4738 validate that values meet defined constraints,
4739 and specify default values, help messages and aliases.
4740 This provides a somewhat similar interface to option handling
4741 (see &f-link-AddOption;).
4742 A &Variables; object also allows
4743 obtaining values from a saved variables file,
4744 or from a custom dictionary in an &SConscript; file.
4745 The processed variables can then be applied to the desired &consenv;.
4749 Conceptually, command-line targets control what to build,
4750 command-line variables (and variable files) control how to build,
4751 and command-line options control how &SCons; operates
4752 (although &SCons; does not enforce that separation).
4755 <para>To obtain an object for manipulating variables,
4756 call the &Variables; factory function:</para>
4759 <varlistentry id="v-Variables">
4760 <term><function>Variables</function>([<parameter>files, [args]]</parameter>)</term>
4762 <para>If <parameter>files</parameter> is a filename or list of filenames,
4763 they are executed as &Python; scripts
4764 to set saved variables when the
4765 <link linkend='v-Update'><function>Update</function></link>
4767 This allows the use of &Python; syntax in the assignments.
4768 A variables file can be the result of an previous call to the
4769 <link linkend='v-Save'>&Save;</link> method.
4770 If <parameter>files</parameter> is not specified,
4772 <parameter>files</parameter>
4774 <constant>None</constant>,
4775 then no files will be processed.
4776 Supplying <constant>None</constant> is required
4777 if there are no files but you want to specify
4778 <parameter>args</parameter> as a positional argument;
4779 or you can use keyword arguments to avoid that.
4780 If any of <parameter>files</parameter> is missing,
4781 it is silently skipped.
4785 Either of the following example file
4786 contents could be used to set an alternative C compiler:</para>
4788 <programlisting language="python">
4790 CC = os.environ.get('CC')
4794 <parameter>args</parameter>
4795 is specified, it must be a dictionary.
4796 The key-value pairs from <parameter>args</parameter>
4797 will be added to those obtained from
4798 <parameter>files</parameter>, if any.
4799 Keys from <parameter>args</parameter>
4800 take precedence over same-named keys from <parameter>files</parameter>.
4801 If omitted, the default is the
4802 <link linkend="v-ARGUMENTS">&ARGUMENTS;</link>
4803 dictionary that holds build variables
4804 specified on the command line.
4805 Using &ARGUMENTS; allows you to indicate that if a setting appears
4806 on both the command line and in the file(s),
4807 the command line setting is preferred.
4808 However, any dictionary can be passed.
4811 <programlisting language="python">
4812 vars = Variables('custom.py')
4813 vars = Variables('overrides.py', ARGUMENTS)
4814 vars = Variables(None, {FOO:'expansion', BAR:7})
4815 vars = Variables(args={FOO:'expansion', BAR:7})
4819 Calling &Variables; with no arguments is equivalent to:
4821 <programlisting language="python">
4822 vars = Variables(files=None, args=ARGUMENTS)
4830 A &Variables; object is a container for variable descriptions,
4831 added by calling the
4832 <link linkend='v-Add'><function>Add</function></link> or
4833 <link linkend='v-AddVariables'><function>AddVariables</function></link>
4835 A variable description consists of a name,
4836 a list of aliases for the name,
4837 a help message, a default value,
4838 and functions to validate and convert values.
4839 Processing of input sources is deferred until the
4840 <link linkend='v-Update'><function>Update</function></link>
4842 at which time the variables are added to the
4843 specified &consenv;,
4844 using the name as the &consvar; name;
4845 any aliases are not added.
4846 Variables from the input sources which do not match any
4847 names or aliases from the variable descriptions in this object are skipped,
4848 except that a dictionary of their names and values are made available in the
4849 <link linkend='v-unknown'><varname>unknown</varname></link>
4850 attribute of the &Variables; object.
4851 This list can also be obtained via the
4852 <link linkend='v-UnknownVariables'><function>UnknownVariables</function></link>
4854 If a variable description has a default value
4855 other than <literal>None</literal> and does not
4856 appear in the input sources,
4857 it is added to the &consenv; with its default value.
4858 A list of variables set from their defaults and
4859 not from the input sources is available as the
4860 <link linkend='v-defaulted'><varname>defaulted</varname></link>
4861 attribute of the &Variables; object.
4862 The unknown variables and defaulted information is
4863 not available until the &Update; method has run.
4867 Since the variables are eventually added as &consvars;,
4868 you should choose variable names which do not unintentionally change
4869 pre-defined &consvars; that your project will make use of
4870 (see <xref linkend="construction_variables"/> for a reference),
4871 since the specified values are assigned, not merged,
4872 to the respective &consvars;.
4876 The &Variables; subsystem does not directly support a way
4877 to define a variable the user <emphasis>must</emphasis> supply,
4878 but this can be simulated by using a validator function,
4879 and specifying a default value which the validator will reject,
4880 resulting in an invalid value error message
4881 (the convenience methods &EnumVariable; and
4882 &ListVariable; make this relatively straightforward).
4885 <para>A &Variables; object has the following methods:</para>
4888 <varlistentry id="v-Add">
4889 <term><replaceable>vars</replaceable>.<function>Add</function>(<parameter>key, [help, default, validator, converter, subst]</parameter>)</term>
4891 <para>Add a customizable &consvar; to the &Variables; object.
4892 <parameter>key</parameter>
4893 is either the name of the variable,
4894 or a sequence of strings, in which case
4895 the first item in the sequence is taken as the variable name,
4896 and any remaining values are considered aliases for the variable.
4897 <parameter>key</parameter> is mandatory,
4898 the other fields are optional.
4899 <parameter>help</parameter>
4900 is the help text for the variable
4901 (defaults to an empty string).
4902 <parameter>default</parameter>
4903 is the default value of the variable
4904 (defaults to <constant>None</constant>).
4905 The variable will be set to the value of
4906 <parameter>default</parameter> if it does
4907 not appear in the input sources,
4908 except if <parameter>default</parameter>
4909 is <literal>None</literal>,
4910 in which case it is not added to the &consenv;
4911 unless it has been set in the input sources.
4915 If the <parameter>validator</parameter> argument is supplied,
4916 it is a callback function to validate the value of the variable
4917 when the variables are processed
4918 (that is, when the <link linkend='v-Update'>&Update;</link>
4920 A validator function must accept three arguments:
4921 <parameter>key</parameter>,
4922 <parameter>value</parameter>
4923 and <parameter>env</parameter>,
4924 and should raise an exception (with a helpful error message)
4925 if <parameter>value</parameter> is invalid.
4926 No return value is expected from the validator.
4930 If the <parameter>converter</parameter> argument is supplied,
4931 it is a callback function to convert the value into
4932 one suitable for adding to the &consenv;.
4933 A converter function must accept the
4934 <parameter>value</parameter> argument,
4935 and may declare <parameter>env</parameter>
4936 as a second argument if it needs access to the
4937 &consenv; while validating - the function will be called appropriately.
4938 The converter is called before the validator;
4939 it must return a value, which is then passed to the
4940 <parameter>validator</parameter> (if any) for checking.
4941 In general, the converter should not fail,
4942 leaving validation checks to the validator,
4943 although if an operation is impossible to complete
4944 or there is no separate validator
4945 it can raise a <exceptionname>ValueError</exceptionname>.
4949 Substitution will be performed on the variable value
4950 before the converter and validator are called,
4951 unless the optional <parameter>subst</parameter> parameter
4952 is false (the default is <literal>True</literal>).
4953 Suppressing substitution may be useful if the variable value
4954 looks like a &consvar; reference (e.g. <literal>$VAR</literal>)
4955 and the validator and/or converter should see it unexpanded.
4959 As a special case, if <parameter>key</parameter>
4960 is a sequence and is the <emphasis>only</emphasis>
4961 argument to &Add;, it is unpacked into the five parameters
4962 <parameter>key</parameter>,
4963 <parameter>help</parameter>,
4964 <parameter>default</parameter>,
4965 <parameter>validator</parameter> and
4966 <parameter>converter</parameter>,
4967 with any missing members from the right filled in with
4968 the respective default values.
4970 to consume a tuple emitted by the convenience functions
4971 <link linkend='v-BoolVariable'>&BoolVariable;</link>,
4972 <link linkend='v-EnumVariable'>&EnumVariable;</link>,
4973 <link linkend='v-ListVariable'>&ListVariable;</link>,
4974 <link linkend='v-PackageVariable'>&PackageVariable;</link>
4976 <link linkend='v-PathVariable'>&PathVariable;</link>.
4979 <para>Examples:</para>
4981 <programlisting language="python">
4982 vars.Add('CC', help='The C compiler')
4984 def valid_color(key, val, env):
4985 if not val in ['red', 'blue', 'yellow']:
4986 raise Exception("Invalid color value '%s'" % val)
4988 vars.Add('COLOR', validator=valid_color)
4992 <emphasis>Changed in version 4.8.0:</emphasis>
4993 added the <parameter>subst</parameter> parameter.
4998 <varlistentry id="v-AddVariables">
4999 <term><replaceable>vars</replaceable>.<function>AddVariables</function>(<parameter>args</parameter>)</term>
5001 <para>A convenience method that adds
5002 one or more customizable &consvars;
5003 to a &Variables; object in one call;
5004 equivalent to calling
5005 <link linkend='v-Add'><function>Add</function></link>
5007 Each <parameter>args</parameter> member
5008 must be a tuple that contains the arguments
5009 for an individual call to the &Add; method
5010 using the "special case" form;
5011 the other calling styles (individual positional
5012 arguments and/or keyword arguments) are not supported.
5015 <programlisting language="python">
5018 ("CC", "The C compiler"),
5019 ("VALIDATE", "An option for testing validation", "notset", validator, None),
5026 <varlistentry id="v-FormatVariableHelpText">
5027 <term><replaceable>vars</replaceable>.<function>FormatVariableHelpText</function>(<parameter>env, opt, help, default, actual, aliases</parameter>)</term>
5029 <para>Returns a formatted string
5030 containing the printable help text
5031 for the single variable <parameter>opt</parameter>.
5032 All of the arguments must be supplied
5033 except <parameter>aliases</parameter>, which is optional.
5034 <parameter>env</parameter>
5035 is the &consenv; containing the variable values,
5036 (<parameter>env</parameter> is not used by the standard
5037 implementation of <function>FormatVariableHelpText</function>);
5038 <parameter>var</parameter>
5039 is the name of the variable;
5040 <parameter>help</parameter>
5041 is the text of the initial help message when the variable was
5042 added to the &Variables; object;
5043 <parameter>default</parameter>
5044 is the default value assigned when the variable was added
5045 to the &Variables; object;
5046 <parameter>actual</parameter>
5047 is the value as assigned in <parameter>env</parameter>
5048 (which may be the same as <parameter>default</parameter>,
5049 if none of the input sources assign to the variable);
5050 and <parameter>aliases</parameter>
5051 are any alias names for the variable,
5052 if omitted defaults to an empty list.
5056 <function>FormatVariableHelpText</function>
5057 is normally not called directly, but by
5058 &GenerateHelpText;, which does the work of
5059 obtaining the necessary values.
5060 You can patch in your own
5061 function that takes the same function signature
5062 in order to customize the appearance of variable help messages.
5066 <programlisting language="python">
5067 def my_format(env, var, help, default, actual):
5068 fmt = "\n%s: default=%s actual=%s (%s)\n"
5069 return fmt % (var, default, actual, help)
5071 vars.FormatVariableHelpText = my_format
5075 Note that &GenerateHelpText;
5076 will not put any blank lines or extra
5077 characters between the entries,
5078 so you must add those characters to the returned
5079 string if you want the entries separated.
5084 <varlistentry id="v-GenerateHelpText">
5085 <term><replaceable>vars</replaceable>.<function>GenerateHelpText</function>(<parameter>env, [sort]</parameter>)</term>
5088 Return a formatted string with the help text collected
5089 from all the variables configured in this &Variables; object.
5090 This string is suitable for passing in to the &f-link-Help; function.
5091 The generated string include an indication of the
5092 actual value in the environment given by <parameter>env</parameter>.
5097 <parameter>sort</parameter> parameter is set to
5098 a callable value, it is used as a comparison function to
5099 determine how to sort the added variables.
5100 This function must accept two arguments, compare them,
5101 and return a negative integer if the first is
5102 less-than the second, zero if equal, or a positive integer
5104 If <parameter>sort</parameter> is not callable,
5106 an alphabetical sort is performed.
5107 The default is <constant>False</constant> (unsorted).
5110 <programlisting language="python">
5111 Help(vars.GenerateHelpText(env))
5114 return (a > b) - (a < b)
5116 Help(vars.GenerateHelpText(env, sort=cmp))
5122 <varlistentry id="v-Save">
5123 <term><replaceable>vars</replaceable>.<function>Save</function>(<parameter>filename, env</parameter>)</term>
5125 <para>Saves the currently set variables into a script file named
5126 by <parameter>filename</parameter>.
5127 This provides a way to cache particular variable settings for reuse.
5128 Only variables that are set to non-default values are saved.
5129 You can load these saved variables on a subsequent run
5130 by passing <parameter>filename</parameter> to the
5131 <link linkend='v-Variables'>&Variables;</link> function,
5135 <programlisting language="python">
5137 vars = Variables(['variables.cache', 'custom.py'])
5140 vars.Save('variables.cache', env)
5146 <varlistentry id="v-UnknownVariables">
5147 <term><replaceable>vars</replaceable>.<function>UnknownVariables</function>()</term>
5149 <para>Returns a dictionary containing any
5150 variables that were specified in the
5151 <parameter>files</parameter> and/or
5152 <parameter>args</parameter> parameters
5153 when <link linkend='v-Variables'>&Variables;</link>
5154 was called, but the object was not actually configured for.
5155 This information is not available until the
5156 <link linkend='v-Update'><function>Update</function></link>
5160 <programlisting language="python">
5161 env = Environment(variables=vars)
5162 for key, value in vars.UnknownVariables():
5163 print("unknown variable: %s=%s" % (key, value))
5169 <varlistentry id="v-Update">
5170 <term><replaceable>vars</replaceable>.<function>Update</function>(<parameter>env, [args]</parameter>)</term>
5172 <para>Process the input sources recorded
5173 when the &Variables; object was initialized
5175 <parameter>env</parameter>
5176 with the customized &consvars;.
5177 The names of any variables in the input sources that are not
5178 configured in the &Variables; object
5179 are recorded and may be retrieved using the
5180 <link linkend='v-UnknownVariables'>&UnknownVariables;</link>
5185 <parameter>args</parameter>
5186 argument is provided, it must be a dictionary of variables,
5187 which will be used in place of the one saved when the
5188 <link linkend='v-Variables'>&Variables;</link> object
5192 <para>Normally, &Update; is not called directly,
5193 but rather invoked indirectly by passing the &Variables; object to
5194 the &f-link-Environment; function:</para>
5196 <programlisting language="python">
5197 env = Environment(..., variables=vars)
5205 A &Variables; object also makes available two data attributes
5206 that can be read for further information. These only have
5207 values if <link linkend='v-Update'><function>Update</function></link>
5212 <varlistentry id="v-defaulted">
5213 <term><replaceable>vars</replaceable>.<parameter>defaulted</parameter></term>
5216 A list of variable names that were set in the &consenv;
5217 from the default values in the variable descriptions -
5218 that is, variables that have a default value and were
5219 not defined in the input sources.
5224 <varlistentry id="v-unknown">
5225 <term><replaceable>vars</replaceable>.<parameter>unknown</parameter></term>
5228 A dictionary of variables that were specified in the input sources,
5229 but do not have matching variable definitions.
5230 This is the same information that is returned by the
5231 <link linkend='v-UnknownVariables'>&UnknownVariables;</link> method.
5236 <para><emphasis>Added in NEXT_RELEASE</emphasis>:
5237 the <parameter>defaulted</parameter> attribute.
5241 &SCons; provides five pre-defined variable types,
5242 accessible through factory functions that generate
5243 a tuple appropriate for directly passing to the
5244 <link linkend='v-Add'><function>Add</function></link> or
5245 <link linkend='v-AddVariables'><function>AddVariables</function></link>
5250 <varlistentry id="v-BoolVariable">
5251 <term><function>BoolVariable</function>(<parameter>key, help, default</parameter>)</term>
5254 Set up a Boolean variable named <parameter>key</parameter>.
5255 The variable will have a default value of
5256 <parameter>default</parameter>,
5257 and <parameter>help</parameter>
5258 will form the descriptive part of the help text.
5259 The variable will interpret the command-line values
5260 <userinput>y</userinput>,
5261 <userinput>yes</userinput>,
5262 <userinput>t</userinput>,
5263 <userinput>true</userinput>,
5264 <userinput>1</userinput>,
5265 <userinput>on</userinput>
5267 <userinput>all</userinput>
5269 and the command-line values
5270 <userinput>n</userinput>,
5271 <userinput>no</userinput>,
5272 <userinput>f</userinput>,
5273 <userinput>false</userinput>,
5274 <userinput>0</userinput>,
5275 <userinput>off</userinput>
5277 <userinput>none</userinput>
5282 <varlistentry id="v-EnumVariable">
5283 <term><function>EnumVariable</function>(<parameter>key, help, default, allowed_values, [map, ignorecase]</parameter>)</term>
5286 Set up a variable named <parameter>key</parameter>
5287 whose value may only be chosen from
5288 a specified list ("enumeration") of values.
5289 The variable will have a default value of
5290 <parameter>default</parameter>
5291 and <parameter>help</parameter>
5292 will form the descriptive part of the help text.
5293 Any value that is not in
5294 <parameter>allowed_values</parameter>
5295 will raise an error,
5296 except that the optional
5297 <parameter>map</parameter>
5298 argument is a dictionary
5299 that can be used to map additional names into
5300 a particular name in the
5301 <parameter>allowed_values</parameter> list.
5303 <parameter>ignorecase</parameter> is <literal>0</literal> (the default),
5304 the values are considered case-sensitive.
5305 If <parameter>ignorecase</parameter> is <literal>1</literal>,
5306 values will be matched
5308 If <parameter>ignorecase</parameter> is <literal>2</literal>,
5309 values will be matched
5311 and all input values will be
5312 converted to lower case.</para>
5316 <varlistentry id="v-ListVariable">
5317 <term><function>ListVariable</function>(<parameter>key, help, default, names, [map, validator]</parameter>)</term>
5320 Set up a variable named <parameter>key</parameter>
5321 whose value may be one or more choices
5322 from a specified list of values.
5323 The variable will have a default value of
5324 <parameter>default</parameter>,
5325 and <parameter>help</parameter>
5326 will form the descriptive part of the help text.
5327 Any value that is not in
5328 <parameter>names</parameter> or the special values
5329 <userinput>all</userinput> or
5330 <userinput>none</userinput>
5331 will raise an error.
5332 Use a comma separator to specify multiple values.
5333 <parameter>default</parameter> may be specified
5334 either as a string of comma-separated values,
5335 or as a &Python; list of values.
5339 <parameter>map</parameter>
5340 argument is a dictionary
5341 that can be used to convert
5342 input values into specific legal values
5344 <parameter>names</parameter>
5346 (Note that the additional values accepted through
5347 the use of a <parameter>map</parameter> are not
5348 reflected in the generated help message). </para>
5350 The optional <parameter>validator</parameter> argument
5351 can be used to specify a custom validator callback function,
5352 as described for <link linkend='v-Add'><function>Add</function></link>.
5353 The default is to use an internal validator routine.
5355 <para><emphasis>Added in 4.8.0</emphasis>:
5356 the <parameter>validator</parameter> parameter.
5361 <varlistentry id="v-PackageVariable">
5362 <term><function>PackageVariable</function>(<parameter>key, help, default</parameter>)</term>
5365 Set up a variable named <parameter>key</parameter>
5366 to help control a build component,
5367 such as a software package.
5368 The variable can be specified to disable, enable,
5369 or enable with a custom path.
5370 The resulting &consvar; will have a value of
5371 <literal>True</literal>, <literal>False</literal>, or a path string.
5372 Interpretation of this value is up to the consumer,
5373 but a path string must refer to an existing filesystem entry
5374 or the <function>PackageVariable</function> validator
5375 will raise an exception.
5379 Any of the (case-insensitive) strings
5380 <userinput>1</userinput>,
5381 <userinput>yes</userinput>,
5382 <userinput>true</userinput>,
5383 <userinput>on</userinput>,
5384 <userinput>enable</userinput>
5386 <userinput>search</userinput>
5388 to indicate the package is "enabled",
5389 and the (case-insensitive) strings
5390 <userinput>0</userinput>,
5391 <userinput>no</userinput>,
5392 <userinput>false</userinput>,
5393 <userinput>off</userinput>
5395 <userinput>disable</userinput>
5396 to indicate the package is "disabled".
5400 The <parameter>default</parameter> parameter
5401 can be either a path string or one of the enabling or disabling strings.
5402 <parameter>default</parameter> is produced if the variable is not specified,
5403 or if it is specified with one of the enabling strings,
5404 except that if <parameter>default</parameter> is one
5405 of the enabling strings, the boolean literal <literal>True</literal>
5406 is produced instead of the string.
5407 The <parameter>help</parameter> parameter
5408 specifies the descriptive part of the help text.
5413 <varlistentry id="v-PathVariable">
5414 <term><function>PathVariable</function>(<parameter>key, help, default, [validator]</parameter>)</term>
5417 Set up a variable named <parameter>key</parameter> to hold a path string.
5418 The variable will have a default value of
5419 <parameter>default</parameter>,
5420 and the <parameter>help</parameter> parameter
5421 will be used as the descriptive part of the help text.
5426 <parameter>validator</parameter> parameter
5427 describes a callback function which will be called to
5428 verify that the specified path is acceptable.
5430 following ready-made validators:</para>
5432 <variablelist> <!-- nested list -->
5434 <term><literal>PathVariable</literal>.<function>PathExists</function></term>
5436 <para>Verify that the specified path exists
5437 (this the default behavior if no
5438 <parameter>validator</parameter> is supplied).</para>
5443 <term><literal>PathVariable</literal>.<function>PathIsFile</function></term>
5445 <para>Verify that the specified path exists and is a regular file.</para>
5450 <term><literal>PathVariable</literal>.<function>PathIsDir</function></term>
5452 <para>Verify that the specified path exists and is a directory.</para>
5457 <term><literal>PathVariable</literal>.<function>PathIsDirCreate</function></term>
5459 <para>Verify that the specified path exists and is a directory;
5460 if it does not exist, create the directory.</para>
5465 <term><literal>PathVariable</literal>.<function>PathAccept</function></term>
5467 <para>Accept the specific path name argument without validation,
5468 suitable for when you want your users
5469 to be able to specify a directory path that will be
5470 created as part of the build process, for example.</para>
5473 </variablelist> <!-- end nested list -->
5476 You may supply your own
5477 <emphasis>validator</emphasis>
5479 which must accept three arguments:
5480 <parameter>key</parameter>,
5481 the name of the variable to be set;
5482 <parameter>val</parameter>,
5483 the specified value being checked;
5485 <parameter>env</parameter>,
5487 and should raise an exception
5488 if the specified value is not acceptable.</para>
5492 <para>These functions make it
5493 convenient to create a number
5494 of variables with consistent behavior
5495 in a single call to the
5496 <link linkend='v-AddVariables'><function>AddVariables</function></link>
5500 <programlisting language="python">
5504 help="compilation with -Wall and similar",
5509 help="debug output and symbols",
5511 allowed_values=("yes", "no", "full"),
5513 ignorecase=0, # case-sensitive
5517 help="libraries to build as shared libraries",
5523 help="use X11 installed here (yes = search some places)",
5528 help="where the root of Qt is installed",
5533 help="where the foo library is installed",
5535 validator=PathVariable.PathIsDir,
5542 <refsect2 id='node_objects'>
5543 <title>Node Objects</title>
5546 &SCons; represents objects that are the sources or targets of
5547 build operations as <firstterm>Nodes</firstterm>,
5548 which are internal data structures.
5549 There are a number of user-visible types of nodes:
5550 File Nodes, Directory Nodes, Value Nodes and Alias Nodes.
5551 Some of the node types have public attributes and methods,
5552 described below. Each of the node types has a global function
5553 and a matching environment method to create instances:
5554 &f-link-File;, &f-link-Dir;, &f-link-Value; and &f-link-Alias;.
5557 <refsect3 id='file_and_directory_nodes'>
5558 <title>Filesystem Nodes</title>
5561 The &f-link-File; and &f-link-Dir;
5562 functions/methods return
5563 File Nodes and Directory Nodes, respectively.
5564 Such <firstterm>Filesystem Nodes</firstterm>
5565 represent build components that correspond to an entry
5566 in the computer's filesystem,
5567 whether or not such an entry exists at the time the Node is created.
5568 You do not usually need to explicitly create filesystem Nodes,
5569 since when you supply a string as a target or source of a Builder,
5570 &SCons; will create the Nodes as needed to populate the
5572 Builders return the target Node(s) in the form of a list,
5573 which you can then make use of.
5574 However, since filesystem Nodes have some useful
5575 public attributes and methods
5576 that you can use in &SConscript; files,
5577 it is sometimes appropriate to create them manually,
5578 outside the regular context of a Builder call.
5581 The following attributes provide information about a Node:
5586 <term><replaceable>node</replaceable>.<varname>path</varname></term>
5588 <para>The build path
5589 of the given file or directory.
5590 This path is relative to the project top directory.
5591 The build path is the same as the source path if
5592 <emphasis>variant_dir</emphasis>
5593 is not being used.</para>
5598 <term><replaceable>node</replaceable>.<varname>abspath</varname></term>
5600 <para>The absolute build path of the given file or directory.</para>
5605 <term><replaceable>node</replaceable>.<varname>relpath</varname></term>
5607 <para>The build path of the given file or directory relative to
5608 the project top directory.</para>
5613 <term><replaceable>node</replaceable>.<function>srcnode</function>()</term>
5616 <function>srcnode</function>
5618 returns another File or Directory Node
5619 representing the source path of the given
5620 File or Directory Node.
5626 <para>Examples:</para>
5628 <programlisting language="python">
5629 # Get the current build dir's path, relative to top.
5632 # Current dir's absolute path
5635 # Current dir's path relative to the project top directory
5638 # Next line is always '.', because it is the top dir's path relative to itself.
5641 # Source path of the given source file.
5642 File('foo.c').srcnode().path
5644 # Builders return lists of File objects:
5645 foo = env.Program('foo.c')
5646 print("foo will be built in", foo[0].path)
5650 Filesystem Node objects have methods to create new
5651 Filesystem Nodes relative to the original Node.
5652 There are also times when you may need to refer to an entry
5653 in a filesystem without knowing in advance whether it's a
5654 file or a directory.
5655 For those situations,
5656 there is an <function>Entry</function> method of filesystem node objects,
5657 which returns a Node that can represent either a file or a directory.
5661 If the original Node is a Directory Node,
5662 these methods will place the new Node within the directory
5663 the original Node represents:
5668 <term><replaceable>node</replaceable>.<function>Dir</function>(<parameter>name</parameter>)</term>
5670 <para>Returns a directory Node
5671 <parameter>name</parameter>
5672 which is a subdirectory of
5673 the directory represented by
5674 <replaceable>node</replaceable>.</para>
5679 <term><replaceable>node</replaceable>.<function>File</function>(<parameter>name</parameter>)</term>
5681 <para>Returns a file Node
5682 <parameter>name</parameter>
5683 in the directory represented by
5684 <replaceable>node</replaceable>.</para>
5689 <term><replaceable>node</replaceable>.<function>Entry</function>(<parameter>name</parameter>)</term>
5691 <para>Returns an unresolved Node
5692 <parameter>name</parameter>
5693 in the directory represented by
5694 <replaceable>node</replaceable>.</para>
5700 If the original Node is a File Node,
5701 these methods will place the new Node in the same
5702 directory as the one the original Node represents:
5707 <term><replaceable>node</replaceable>.<function>Dir</function>(<parameter>name</parameter>)</term>
5709 <para>Returns a Node
5710 <parameter>name</parameter>
5711 for a directory in the parent directory of
5712 the file represented by
5713 <replaceable>node</replaceable>.</para>
5718 <term><replaceable>node</replaceable>.<function>File</function>(<parameter>name</parameter>)</term>
5720 <para>Returns a Node
5721 <parameter>name</parameter>
5722 for a file in the parent directory of
5723 the file represented by
5724 <replaceable>node</replaceable>.</para>
5729 <term><replaceable>node</replaceable>.<function>Entry</function>(<parameter>name</parameter>)</term>
5731 <para>Returns an unresolved Node
5732 <parameter>name</parameter>
5733 in the parent directory of
5734 the file represented by
5735 <replaceable>node</replaceable>.</para>
5740 <para>For example:</para>
5742 <programlisting language="python">
5743 # Get a Node for a file within a directory
5744 incl = Dir('include')
5745 f = incl.File('header.h')
5747 # Get a Node for a subdirectory within a directory
5748 dist = Dir('project-3.2.1')
5749 src = dist.Dir('src')
5751 # Get a Node for a file in the same directory
5752 cfile = File('sample.c')
5753 hfile = cfile.File('sample.h')
5757 html = docs.Dir('html')
5758 index = html.File('index.html')
5759 css = index.File('app.css')
5763 <refsect3 id='value_and_alias_nodes'>
5764 <title>Value and Alias Nodes</title>
5767 &SCons; provides two other Node types to represent
5768 object that will not have an equivalent filesystem entry.
5769 Such Nodes always need to be created explicitly.
5773 The &f-link-Alias; method returns an Alias Node.
5774 Aliases are virtual objects - they will not themselves result
5775 in physical objects being constructed, but are entered into
5776 the dependency graph related to their sources.
5777 An alias is checked for up to date by checking if
5778 its sources are up-to-date.
5779 An alias is built by making sure its sources have been built,
5780 and if any building took place,
5781 applying any Actions that are defined as part of the alias.
5785 An &f-link-Alias; call creates an entry in the alias namespace,
5786 which is used for disambiguation.
5787 If an alias source has a string valued name,
5788 it will be resolved to a filesystem entry Node,
5789 unless it is found in the alias namespace,
5790 in which case it is resolved to the matching alias Node.
5791 As a result, the order of &f-Alias; calls is significant.
5792 An alias can refer to another alias, but only if the
5793 other alias has previously been created.
5797 The &f-link-Value; method returns a Value Node.
5798 Value nodes are often used for generated data that
5799 will not have any corresponding filesystem entry,
5800 but will be used to determine whether a build target is out-of-date,
5801 or to include as part of a build Action.
5802 Common examples are timestamp strings,
5803 revision control version strings
5804 and other run-time generated strings.
5808 A Value Node can also be the target of a builder.
5815 <refsect1 id='extending_scons'>
5816 <title>EXTENDING SCONS</title>
5819 &SCons; is designed to be extensible through provided facilities,
5820 so changing the code of &SCons; itself is only rarely needed
5821 to customize its behavior.
5822 A number of the main operations use callable objects
5823 which can be supplemented by writing your own.
5824 Builders, Scanners and Tools each use a kind of plugin system,
5825 allowing you to easily drop in new ones.
5826 Information about creating
5827 <link linkend='builder_objects'>Builder Objects</link> and
5828 <link linkend='scanner_objects'>Scanner Objects</link>
5829 appear in the following sections.
5830 The instructions &SCons; actually uses to
5831 construct things are called Actions,
5832 and it is easy to create Action Objects and hand them
5833 to the objects that need to know about those actions
5834 (besides Builders, see &f-link-AddPostAction;,
5835 &f-link-AddPreAction; and &f-link-Alias; for some examples
5836 of other places that take Actions).
5837 <link linkend='action_objects'>Action Objects</link>
5838 are also described below.
5839 Adding new Tool modules is described in
5840 <link linkend='tool_modules'>Tool Modules</link>
5843 <refsect2 id='builder_objects'>
5844 <title>Builder Objects</title>
5847 can be extended to build different types of targets
5848 by adding new Builder objects
5850 <emphasis>In general</emphasis>,
5851 you should only need to add a new Builder object
5852 when you want to build a new type of file or other external target.
5853 For output file types &scons; already knows about,
5854 you can usually modify the behavior of premade Builders
5855 such as &b-link-Program;, &b-link-Object; or &b-link-Library;
5856 by changing the &consvars; they use
5857 (&cv-link-CC;, &cv-link-LINK;, etc.).
5858 In this manner you can, for example, change the compiler to use,
5859 which is simpler and less error-prone than writing a new builder.
5860 The documentation for each Builder lists which
5864 <para>Builder objects are created
5868 Once created, a builder is added to an environment
5869 by entering it in the &cv-link-BUILDERS; dictionary
5870 in that environment (some of the examples
5871 in this section illustrate this).
5872 Doing so automatically triggers &SCons; to add a method
5873 with the name of the builder to the environment.
5879 function accepts the following keyword arguments:</para>
5883 <term><parameter>action</parameter></term>
5885 <para>The command used to build the target from the source.
5886 <parameter>action</parameter>
5887 may be a string representing a template command line to execute,
5888 a list of strings representing the command
5889 to execute with its arguments
5890 (suitable for enclosing white space in an argument),
5892 mapping source file name suffixes to
5893 any combination of command line strings
5894 (if the builder should accept multiple source file extensions),
5895 a &Python; function,
5897 (see <link linkend='action_objects'>Action Objects</link>)
5898 or a list of any of the above.</para>
5900 <para>An action function must accept three arguments:
5901 <parameter>source</parameter>,
5902 <parameter>target</parameter> and
5903 <parameter>env</parameter>.
5904 <parameter>source</parameter> is a list of source nodes;
5905 <parameter>target</parameter> is a list of target nodes;
5906 <parameter>env</parameter> is the &consenv; to use for context.
5910 The <parameter>action</parameter>
5911 and <parameter>generator</parameter>
5912 arguments must not both be used for the same Builder.</para>
5917 <term><parameter>prefix</parameter></term>
5919 <para>The prefix to prepend to the target file name.
5920 <parameter>prefix</parameter> may be
5921 a string, a function (or other callable) that takes
5922 two arguments (a &consenv; and a list of sources)
5923 and returns a prefix string,
5924 or a dictionary specifying a mapping from a specific source suffix
5925 (of the first source specified)
5926 to a corresponding target prefix string. For the dictionary form, both the source
5927 suffix (key) and target prefix (value) specifications may use environment variable
5928 substitution, and the target prefix
5929 may also be a callable object. The default target prefix
5930 may be indicated by a dictionary entry with a key of <constant>None</constant>.</para>
5932 <programlisting language="python">
5933 b = Builder("build_it < $SOURCE > $TARGET", prefix="file-")
5935 def gen_prefix(env, sources):
5936 return "file-" + env['PLATFORM'] + '-'
5938 b = Builder("build_it < $SOURCE > $TARGET", prefix=gen_prefix)
5941 "build_it < $SOURCE > $TARGET",
5942 suffix={None: "file-", "$SRC_SFX_A": gen_prefix},
5949 <term><parameter>suffix</parameter></term>
5951 <para>The suffix to append to the target file name.
5952 Specified in the same manner as for <parameter>prefix</parameter> above.
5953 If the suffix is a string, then
5955 prepends a <literal>'.'</literal> to the suffix if it's not already there.
5956 The string returned by the callable object or obtained from the
5957 dictionary is untouched, and you need to manually prepend a <literal>'.'</literal>
5958 if one is required.</para>
5960 <programlisting language="python">
5961 b = Builder("build_it < $SOURCE > $TARGET", suffix="-file")
5963 def gen_suffix(env, sources):
5964 return "." + env['PLATFORM'] + "-file"
5966 b = Builder("build_it < $SOURCE > $TARGET", suffix=gen_suffix)
5968 "build_it < $SOURCE > $TARGET",
5969 suffix={None: ".sfx1", "$SRC_SFX_A": gen_suffix},
5976 <term><parameter>ensure_suffix</parameter></term>
5978 <para>If set to a true value,
5979 ensures that targets will end in
5980 <parameter>suffix</parameter>.
5981 Thus, the suffix will also be added to any target strings
5982 that have a suffix that is not already <parameter>suffix</parameter>.
5983 The default behavior (also indicated by a false value)
5984 is to leave unchanged
5985 any target string that looks like it already has a suffix.</para>
5987 <programlisting language="python">
5988 b1 = Builder("build_it < $SOURCE > $TARGET", suffix=".out")
5990 "build_it < $SOURCE > $TARGET", suffix=".out", ensure_suffix=True
5993 env['BUILDERS']['B1'] = b1
5994 env['BUILDERS']['B2'] = b2
5996 # Builds "foo.txt" because ensure_suffix is not set.
5997 env.B1('foo.txt', 'foo.in')
5999 # Builds "bar.txt.out" because ensure_suffix is set.
6000 env.B2('bar.txt', 'bar.in')
6007 <term><parameter>src_suffix</parameter></term>
6009 <para>The expected source file name suffix.
6010 <parameter>src_suffix</parameter>
6011 may be a string or a list of strings.</para>
6015 <varlistentry id="target_scanner">
6016 <term><parameter>target_scanner</parameter></term>
6018 <para>A Scanner object that
6019 will be invoked to find
6020 implicit dependencies for this target file.
6021 Use only to specify Scanner objects that find
6022 implicit dependencies
6023 based on the target file
6025 <emphasis>not</emphasis>
6026 for implicit dependencies based on source files
6027 (use <xref linkend="source_scanner"/> for those).
6028 See <xref linkend="scanner_objects"/>
6029 for information about creating your own Scanner objects.</para>
6033 <varlistentry id="source_scanner">
6034 <term><parameter>source_scanner</parameter></term>
6036 <para>A Scanner object that
6038 find implicit dependencies in
6040 used to build this target file.
6041 Use to specify a scanner to
6043 <literal>#include</literal>
6044 lines in source files.
6046 <classname>DirScanner</classname>
6047 Scanner object may be used to
6048 indicate that this Builder
6049 should scan directory trees
6050 for on-disk changes to files
6053 does not know about from other Builder or function calls.
6054 See <xref linkend="scanner_objects"/>
6055 for information about creating your own Scanner objects.</para>
6060 <term><parameter>target_factory</parameter></term>
6062 <para>A factory function that the Builder will use
6063 to turn any targets specified as strings into SCons Nodes.
6065 SCons assumes that all targets are files
6066 (that is, the default factory is &File;).
6067 Other useful <parameter>target_factory</parameter>
6068 values include &Dir;
6069 for when a Builder creates a directory target,
6071 for when a Builder can create either a file
6072 or directory target.</para>
6074 <para>Example:</para>
6076 <programlisting language="python">
6077 def my_mkdir(target, source, env):
6078 # target[0] will be a Dir node for 'new_directory'
6080 MakeDirectoryBuilder = Builder(action=my_mkdir, target_factory=Dir)
6082 env.Append(BUILDERS={'MakeDirectory': MakeDirectoryBuilder})
6083 env.MakeDirectory('new_directory', [])
6086 <para>Note that the call to the <function>MakeDirectory</function> Builder
6087 needs to specify an empty source list
6088 to make the filename string represent the builder's target.
6089 &SCons; assumes a single positional argument to a builder
6090 is the source, and would try to deduce the target name from it,
6091 which, in the absence of an automatically-added prefix or suffix,
6092 would lead to a matching target and source name
6093 and a circular dependency.</para>
6098 <term><parameter>source_factory</parameter></term>
6100 <para>A factory function that the Builder will use
6101 to turn any sources specified as strings into SCons Nodes.
6103 SCons assumes that all source are files
6104 (that is, the default factory is &File;).
6105 Other useful <parameter>source_factory</parameter>
6106 values include &Dir;
6107 for when a Builder uses a directory as a source,
6109 for when a Builder can use files
6110 or directories (or both) as sources.</para>
6112 <para>Example:</para>
6114 <programlisting language="python">
6115 def collect(target, source, env):
6116 # target[0] will default to a File node for 'archive' (no target_factory)
6117 # source[0] will be a Dir node for 'directory_name'
6119 CollectBuilder = Builder(action=collect, source_factory=Dir)
6121 env.Append(BUILDERS={'Collect': CollectBuilder})
6122 env.Collect('archive', 'directory_name')
6127 <varlistentry id="emitter_function">
6128 <term><parameter>emitter</parameter></term>
6130 <para>A function or list of functions to manipulate the target and source
6131 lists before dependencies are established
6132 and the target(s) are actually built.
6133 <parameter>emitter</parameter>
6134 can also be a string containing a &consvar; to expand
6135 to an emitter function or list of functions,
6136 or a dictionary mapping source file suffixes
6137 to emitter functions.
6138 (Only the suffix of the first source file
6139 is used to select the actual emitter function
6140 from an emitter dictionary.)</para>
6142 <para>A function passed as <parameter>emitter</parameter>
6143 must accept three arguments:
6144 <parameter>source</parameter>,
6145 <parameter>target</parameter> and
6146 <parameter>env</parameter>.
6147 <parameter>source</parameter> is a list of source nodes,
6148 <parameter>target</parameter> is a list of target nodes,
6149 <parameter>env</parameter> is the &consenv; to use for context.
6152 <para>An emitter must return a tuple containing two lists,
6153 the list of targets to be built by this builder,
6154 and the list of sources for this builder.</para>
6156 <para>Example:</para>
6158 <programlisting language="python">
6159 def e(target, source, env):
6160 return target + ['foo.foo'], source + ['foo.src']
6162 # Simple association of an emitter function with a Builder.
6163 b = Builder("my_build < $TARGET > $SOURCE", emitter=e)
6165 def e2(target, source, env):
6166 return target + ['bar.foo'], source + ['bar.src']
6168 # Simple association of a list of emitter functions with a Builder.
6169 b = Builder("my_build < $TARGET > $SOURCE", emitter=[e, e2])
6171 # Calling an emitter function through a construction variable.
6172 env = Environment(MY_EMITTER=e)
6173 b = Builder("my_build < $TARGET > $SOURCE", emitter='$MY_EMITTER')
6175 # Calling a list of emitter functions through a construction variable.
6176 env = Environment(EMITTER_LIST=[e, e2])
6177 b = Builder("my_build < $TARGET > $SOURCE", emitter='$EMITTER_LIST')
6179 # Associating multiple emitters with different file
6180 # suffixes using a dictionary.
6181 def e_suf1(target, source, env):
6182 return target + ['another_target_file'], source
6184 def e_suf2(target, source, env):
6185 return target, source + ['another_source_file']
6188 action="my_build < $TARGET > $SOURCE",
6189 emitter={'.suf1': e_suf1, '.suf2': e_suf2}
6196 <term><parameter>multi</parameter></term>
6198 <para>Specifies whether this builder is allowed to be called multiple times for
6199 the same target file(s). The default is <constant>False</constant>,
6200 which means the builder
6201 can not be called multiple times for the same target file(s). Calling a
6202 builder multiple times for the same target simply adds additional source
6203 files to the target; it is not allowed to change the environment associated
6204 with the target, specify additional environment overrides,
6205 or associate a different
6206 builder with the target.</para>
6211 <term><parameter>env</parameter></term>
6213 <para>A &consenv; that can be used
6214 to fetch source code using this Builder.
6215 (Note that this environment is
6216 <emphasis>not</emphasis>
6217 used for normal builds of normal target files,
6218 which use the environment that was
6219 used to call the Builder for the target file.)</para>
6223 <varlistentry id="generator_function">
6224 <term><parameter>generator</parameter></term>
6226 <para>A function that returns a list of actions that will be executed to build
6227 the target(s) from the source(s).
6228 The returned action(s) may be
6229 an Action object, or anything that
6230 can be converted into an Action object
6231 (see the next section).</para>
6233 <para>A function passed as <parameter>generator</parameter>
6234 must accept four arguments:
6235 <parameter>source</parameter>,
6236 <parameter>target</parameter>,
6237 <parameter>env</parameter> and
6238 <parameter>for_signature</parameter>.
6239 <parameter>source</parameter> is a list of source nodes,
6240 <parameter>target</parameter> is a list of target nodes,
6241 <parameter>env</parameter> is the &consenv; to use for context,
6242 and <parameter>for_signature</parameter> is
6243 a Boolean value that tells the function
6244 if it is being called for the purpose of generating a &buildsig;
6245 (as opposed to actually executing the command).
6246 Since the &buildsig; is used for rebuild determination,
6247 the function should omit those elements
6248 that do not affect whether a rebuild should be triggered
6249 if <parameter>for_signature</parameter> is true.
6252 <para>Example:</para>
6254 <programlisting language="python">
6255 def g(source, target, env, for_signature):
6256 return [["gcc", "-c", "-o"] + target + source]
6258 b = Builder(generator=g)
6263 <emphasis>generator</emphasis>
6265 <emphasis>action</emphasis>
6266 arguments must not both be used for the same Builder.</para>
6271 <term><parameter>src_builder</parameter></term>
6273 <para>Specifies a builder to use when a source file name suffix does not match
6274 any of the suffixes of the builder. Using this argument produces a
6275 multi-stage builder.</para>
6280 <term><parameter>single_source</parameter></term>
6282 <para>Specifies that this builder expects exactly one source file per call. Giving
6283 more than one source file without target files results in implicitly calling
6284 the builder multiple times (once for each source given). Giving multiple
6285 source files together with target files results in a
6286 <exceptionname>UserError</exceptionname> exception.</para>
6291 <term><parameter>source_ext_match</parameter></term>
6293 <para>When the specified
6294 <parameter>action</parameter>
6295 argument is a dictionary,
6296 the default behavior when a builder is passed
6297 multiple source files is to make sure that the
6298 extensions of all the source files match.
6299 If it is legal for this builder to be
6300 called with a list of source files with different extensions,
6301 this check can be suppressed by setting
6302 <parameter>source_ext_match</parameter>
6304 <constant>False</constant>
6305 or some other non-true value.
6306 In this case, &scons;
6307 will use the suffix of the first specified
6308 source file to select the appropriate action from the
6309 <parameter>action</parameter>
6312 <para>In the following example,
6314 <parameter>source_ext_match</parameter>
6317 from exiting with an error
6318 due to the mismatched suffixes of
6319 <filename>foo.in</filename>
6321 <filename>foo.extra</filename>.</para>
6323 <programlisting language="python">
6324 b = Builder(action={'.in': 'build $SOURCES > $TARGET'}, source_ext_match=False)
6325 env = Environment(BUILDERS={'MyBuild': b})
6326 env.MyBuild('foo.out', ['foo.in', 'foo.extra'])
6333 <term><parameter>env</parameter></term>
6335 <para>A &consenv; that can be used
6336 to fetch source code using this Builder.
6337 (Note that this environment is
6338 <emphasis>not</emphasis>
6339 used for normal builds of normal target files,
6340 which use the environment that was
6341 used to call the Builder for the target file.)</para>
6343 <programlisting language="python">
6344 b = Builder(action="build < $SOURCE > $TARGET")
6345 env = Environment(BUILDERS={'MyBuild' : b})
6346 env.MyBuild('foo.out', 'foo.in', my_arg='xyzzy')
6353 <term><parameter>chdir</parameter></term>
6355 <para>A directory from which scons
6360 <parameter>chdir</parameter>
6362 a string or a directory Node,
6363 scons will change to the specified directory.
6365 <parameter>chdir</parameter>
6366 is not a string or Node
6368 then scons will change to the
6369 target file's directory.</para>
6371 <para>Note that scons will
6372 <emphasis>not</emphasis>
6373 automatically modify
6376 <envar>$TARGET</envar>
6378 <envar>$SOURCE</envar>
6379 when using the <parameter>chdir</parameter>
6380 keyword argument--that is,
6381 the expanded file names
6382 will still be relative to the project top directory,
6383 and consequently incorrect
6384 relative to the chdir directory.
6385 Builders created using <parameter>chdir</parameter> keyword argument,
6386 will need to use &consvar;
6388 <literal>${TARGET.file}</literal>
6390 <literal>${SOURCE.file}</literal>
6391 to use just the filename portion of the
6392 targets and source.</para>
6394 <programlisting language="python">
6395 b = Builder(action="build < ${SOURCE.file} > ${TARGET.file}", chdir=True)
6396 env = Environment(BUILDERS={'MyBuild' : b})
6397 env.MyBuild('sub/dir/foo.out', 'sub/dir/foo.in')
6402 &Python; only keeps one current directory
6403 location even if there are multiple threads.
6404 This means that use of the
6405 <parameter>chdir</parameter>
6408 <emphasis>not</emphasis>
6412 because individual worker threads spawned
6413 by SCons interfere with each other
6414 when they start changing directory.</para>
6420 <para>Any additional keyword arguments supplied
6421 when a Builder object is created
6422 (that is, when the &f-link-Builder; function is called)
6423 will be set in the executing construction
6424 environment when the Builder object is called.
6425 The canonical example here would be
6426 to set a &consvar; to
6427 the repository of a source code system.</para>
6429 <para>Any such keyword arguments supplied
6430 when a Builder object is called
6431 will only be associated with the target
6432 created by that particular &f-Builder; call
6433 (and any other files built as a
6434 result of the call).
6435 These extra keyword arguments are passed to the
6436 following functions:
6437 <link linkend='generator_function'>command generator functions</link>,
6438 <link linkend='miscellaneous_action_functions'>function Actions</link>,
6440 <link linkend='emitter_function'>emitter functions</link>.
6445 <refsect2 id='action_objects'>
6446 <title>Action Objects</title>
6450 factory function will turn its
6451 <parameter>action</parameter>
6452 keyword argument into an appropriate
6453 internal Action object, as will
6454 the &f-link-Command; function.
6455 You can also explicitly create Action objects
6456 for passing to &f-Builder;, or other functions
6457 that take actions as arguments,
6458 by calling the &f-link-Action; factory function.
6459 This may more efficient when multiple
6460 Builder objects need to do the same thing
6461 rather than letting each of those Builder objects
6462 create a separate Action object.
6463 It also allows more flexible configuration
6464 of an Action object. For example, to control
6465 the message printed when the action is taken
6466 you need to create the action object using &f-Action;.
6470 &Action; factory function
6471 returns an appropriate object for the action
6472 represented by the type of the
6473 <parameter>action</parameter> argument
6474 (the first positional parameter):</para>
6478 <para>If <parameter>action</parameter> is already an Action object,
6479 the object is simply returned.</para>
6483 <para>If <parameter>action</parameter> is a string,
6484 a command-line Action is returned.
6485 If such a string begins with <literal>@</literal>,
6486 the command line is not printed.
6487 If the string begins with hyphen
6488 (<literal>-</literal>),
6489 the exit status from the specified command
6490 is ignored, allowing execution to continue
6491 even if the command reports failure:</para>
6493 <programlisting language="python">
6494 Action('$CC -c -o $TARGET $SOURCES')
6496 # Doesn't print the line being executed.
6497 Action('@build $TARGET $SOURCES')
6499 # Ignores return value
6500 Action('-build $TARGET $SOURCES')
6505 <para>If <parameter>action</parameter> is a list,
6506 then a list of Action objects is returned.
6507 An Action object is created as necessary
6508 for each element in the list.
6509 If an element within
6510 the list is itself a list,
6511 the embedded list is taken as the
6512 command and arguments to be executed via
6514 This allows white space to be enclosed
6515 in an argument rather than taken as a separator by defining
6516 a command in a list within a list:</para>
6518 <programlisting language="python">
6519 Action([['cc', '-c', '-DWHITE SPACE', '-o', '$TARGET', '$SOURCES']])
6524 <para>If <parameter>action</parameter> is a callable object,
6525 a Function Action is returned.
6526 The callable must accept three keyword arguments:
6527 <parameter>target</parameter>,
6528 <parameter>source</parameter> and
6529 <parameter>env</parameter>.
6530 <parameter>target</parameter>
6531 is a Node object representing the target file,
6532 <parameter>source</parameter>
6533 is a Node object representing the source file and
6534 <parameter>env</parameter>
6535 is the &consenv; used for building the target file.
6540 <parameter>target</parameter>
6542 <parameter>source</parameter>
6543 arguments may be lists of Node objects if there is
6544 more than one target file or source file.
6545 The actual target and source file name(s) may
6546 be retrieved from their Node objects
6547 via the built-in &Python; <function>str</function> function:</para>
6549 <programlisting language="python">
6550 target_file_name = str(target)
6551 source_file_names = [str(x) for x in source]
6554 <para>The function should return
6555 <literal>0</literal>
6557 <constant>None</constant>
6558 to indicate a successful build of the target file(s).
6559 The function may raise an exception
6560 or return a non-zero exit status
6561 to indicate an unsuccessful build.</para>
6563 <programlisting language="python">
6564 def build_it(target=None, source=None, env=None):
6565 # build the target from the source
6568 a = Action(build_it)
6574 <parameter>action</parameter>
6575 is not one of the above types,
6576 no action object is generated and &f-Action;
6577 returns <constant>None</constant>.</para>
6581 <para>The environment method form &f-link-env-Action;
6582 will expand &consvars; in any argument strings,
6584 <parameter>action</parameter>,
6585 at the time it is called,
6586 using the construction variables in the &consenv; through which
6587 it was called. The global function form &f-link-Action;
6588 delays variable expansion until
6589 the Action object is actually used.
6592 <para>The optional second argument to &f-Action;
6593 is used to control the output
6594 which is printed when the Action is actually performed.
6595 If this parameter is omitted,
6596 or if the value is an empty string,
6597 a default output depending on the type of the action is used.
6598 For example, a command-line action will print the executed command.
6599 The following argument types are accepted:
6604 <para>If the second argument is a string,
6605 or if the <parameter>cmdstr</parameter> keyword argument is supplied,
6606 the string defines what is printed.
6607 Substitution is performed on the string before it is printed.
6608 The string typically contains substitutable variables, notably
6609 <literal>$TARGET(S)</literal> and <literal>$SOURCE(S)</literal>,
6610 or consists of just a single variable
6611 which is optionally defined somewhere else.
6612 &SCons; itself heavily uses the latter variant.</para>
6616 <para>If the second argument is a function,
6617 or if the <parameter>strfunction</parameter> keyword argument is supplied,
6618 the function will be called to obtain the string
6619 to be printed when the action is performed.
6621 must accept three keyword arguments:
6622 <parameter>target</parameter>,
6623 <parameter>source</parameter> and
6624 <parameter>env</parameter>,
6625 with the same interpretation as for a callable
6626 <parameter>action</parameter> argument above.
6627 The function is responsible for handling any required substitutions.
6632 <para>If the second argument is <constant>None</constant>,
6633 or if <literal>cmdstr=None</literal> is supplied,
6634 output is suppressed entirely.</para>
6639 The <parameter>cmdstr</parameter> and
6640 <parameter>strfunction</parameter>
6641 keyword arguments may not both be supplied in a single call to &f-Action;
6645 Printing of action strings is affected by the setting of
6646 &cv-link-PRINT_CMD_LINE_FUNC;.
6649 <para>Examples:</para>
6651 <programlisting language="python">
6652 def build_it(target, source, env):
6653 # build the target from the source
6656 def string_it(target, source, env):
6657 return "building '%s' from '%s'" % (target[0], source[0])
6659 # Use a positional argument.
6660 f = Action(build_it, string_it)
6661 s = Action(build_it, "building '$TARGET' from '$SOURCE'")
6663 # Alternatively, use a keyword argument.
6664 f = Action(build_it, strfunction=string_it)
6665 s = Action(build_it, cmdstr="building '$TARGET' from '$SOURCE'")
6667 # You can provide a configurable variable.
6668 l = Action(build_it, '$STRINGIT')
6671 <para>Any additional positional arguments, if present,
6672 may either be &consvars; or lists of &consvars;
6673 whose values will be included in the signature of the Action
6675 when deciding whether a target should be rebuilt because the action changed.
6676 Such variables may also be specified using the
6677 <parameter>varlist</parameter>
6679 both positional and keyword forms may be present, and will be combined.
6680 This is necessary whenever you want a target to be rebuilt
6681 when a specific &consvar; changes.
6682 This is not often needed for a string action,
6683 as the expanded variables will normally be part of the command line,
6684 but may be needed if a &Python; function action uses
6685 the value of a &consvar; when generating the command line.</para>
6687 <programlisting language="python">
6688 def build_it(target, source, env):
6689 # build the target from the 'XXX' construction variable
6690 with open(target[0], 'w') as f:
6694 # Use positional arguments.
6695 a = Action(build_it, '$STRINGIT', ['XXX'])
6697 # Alternatively, use a keyword argument.
6698 a = Action(build_it, varlist=['XXX'])
6704 can be passed the following
6705 optional keyword arguments
6706 to modify the Action object's behavior:</para>
6710 <term><parameter>chdir</parameter></term>
6713 If <parameter>chdir</parameter> is true
6714 (the default is <constant>False</constant>),
6715 &SCons; will change directories before
6716 executing the action.
6717 If the value of <parameter>chdir</parameter>
6718 is a string or a directory Node,
6719 &SCons; will change to the specified directory.
6720 Otherwise, if <parameter>chdir</parameter> evaluates true,
6721 &SCons; will change to the
6722 target file's directory.</para>
6724 <para>Note that &SCons; will
6725 <emphasis>not</emphasis>
6726 automatically modify
6729 &cv-TARGET; and &cv-SOURCE;
6730 when using the <parameter>chdir</parameter>
6731 parameter - that is,
6732 the expanded file names
6733 will still be relative to
6734 the project top directory,
6735 and consequently incorrect
6736 relative to the chdir directory.
6737 Builders created using <parameter>chdir</parameter> keyword argument,
6738 will need to use &consvar;
6740 <literal>${TARGET.file}</literal>
6742 <literal>${SOURCE.file}</literal>
6743 to use just the filename portion of the
6744 targets and source. Example:</para>
6746 <programlisting language="python">
6747 a = Action("build < ${SOURCE.file} > ${TARGET.file}", chdir=True)
6752 <term><parameter>exitstatfunc</parameter></term>
6755 If provided, must be a callable which accepts a single parameter,
6756 the exit status (or return value)
6757 from the specified action,
6758 and which returns an arbitrary
6760 This can be used, for example,
6761 to specify that an Action object's
6762 return value should be ignored
6763 under special conditions
6764 and SCons should, therefore,
6765 consider that the action always succeeds. Example:</para>
6767 <programlisting language="python">
6768 def always_succeed(s):
6769 # Always return 0, which indicates success.
6772 a = Action("build < ${SOURCE.file} > ${TARGET.file}", exitstatfunc=always_succeed)
6777 <term><parameter>batch_key</parameter></term>
6780 If provided, indicates that the Action can create multiple target files
6781 by processing multiple independent source files simultaneously.
6782 (The canonical example is "batch compilation"
6783 of multiple object files
6784 by passing multiple source files
6785 to a single invocation of a compiler
6788 <parameter>batch_key</parameter>
6789 argument evaluates True and is not a callable object,
6790 the configured Action object will cause
6792 to collect all targets built with the Action object
6793 and configured with the same &consenv;
6794 into single invocations of the Action object's
6795 command line or function.
6796 Command lines will typically want to use the
6797 &cv-CHANGED_SOURCES; &consvar;
6798 (and possibly &cv-CHANGED_TARGETS; as well)
6799 to only pass to the command line those sources that
6800 have actually changed since their targets were built.
6803 <programlisting language="python">
6804 a = Action('build $CHANGED_SOURCES', batch_key=True)
6808 <parameter>batch_key</parameter>
6809 argument may also be
6811 that returns a key that
6812 will be used to identify different
6813 "batches" of target files to be collected
6816 <parameter>batch_key</parameter>
6817 function must accept four parameters:
6818 <parameter>action</parameter>,
6819 <parameter>env</parameter>,
6820 <parameter>target</parameter> and
6821 <parameter>source</parameter>.
6822 The first parameter, <parameter>action</parameter>,
6823 is the active action object.
6824 The second parameter, <parameter>env</parameter>,
6825 is the &consenv; configured for the target.
6826 The <parameter>target</parameter> and <parameter>source</parameter>
6827 parameters are the lists of targets and sources
6828 for the configured action.
6831 <para>The returned key should typically
6832 be a tuple of values derived from the arguments,
6833 using any appropriate logic to decide
6834 how multiple invocations should be batched.
6836 <parameter>batch_key</parameter>
6837 function may decide to return
6838 the value of a specific &consvar;
6839 from <parameter>env</parameter>
6842 to batch-build targets
6843 with matching values of that &consvar;,
6844 or perhaps return the
6845 &Python; <function>id</function>()
6846 of the entire &consenv;,
6850 all targets configured with the same &consenv;.
6852 <constant>None</constant>
6854 the particular target should
6855 <emphasis>not</emphasis>
6856 be part of any batched build,
6857 but instead will be built
6858 by a separate invocation of action's
6859 command or function.
6862 <programlisting language="python">
6863 def batch_key(action, env, target, source):
6864 tdir = target[0].dir
6865 if tdir.name == 'special':
6866 # Don't batch-build any target
6867 # in the special/ subdirectory.
6869 return (id(action), id(env), tdir)
6870 a = Action('build $CHANGED_SOURCES', batch_key=batch_key)
6876 <refsect3 id='miscellaneous_action_functions'>
6877 <title>Miscellaneous Action Functions</title>
6880 supplies Action functions
6881 that arrange for various common
6882 file and directory manipulations
6884 These are similar in concept to "tasks" in the
6886 although the implementation is slightly different.
6887 These functions do not actually
6888 perform the specified action
6889 at the time the function is called,
6890 but rather are factory functions which
6891 return an Action object
6892 that can be executed at the
6893 appropriate time.</para>
6896 There are two natural ways
6899 are intended to be used.</para>
6903 to perform the action
6904 at the time the &SConscript;
6908 global function:</para>
6910 <programlisting language="python">
6911 Execute(Touch('file'))
6915 you can use these functions
6916 to supply Actions in a list
6917 for use by the &f-link-env-Command; method.
6918 This can allow you to
6919 perform more complicated
6920 sequences of file manipulation
6922 on platform-specific
6926 <programlisting language="python">
6927 env = Environment(TMPBUILD='/tmp/builddir')
6933 Copy('$TMPBUILD', '${SOURCE.dir}'),
6934 "cd $TMPBUILD && make",
6935 Delete('$TMPBUILD'),
6942 <term><function>Chmod</function>(<parameter>dest, mode</parameter>)</term>
6944 <para>Returns an Action object that
6945 changes the permissions on the specified
6946 <parameter>dest</parameter>
6947 file or directory to the specified
6948 <parameter>mode</parameter>
6949 which can be octal or string, similar to the POSIX
6950 <command>chmod</command> command.
6953 <programlisting language="python">
6954 Execute(Chmod('file', 0o755))
6959 [Copy('$TARGET', '$SOURCE'), Chmod('$TARGET', 0o755)],
6962 Execute(Chmod('file', "ugo+w"))
6967 [Copy('$TARGET', '$SOURCE'), Chmod('$TARGET', "ugo+w")],
6972 The behavior of <function>Chmod</function> is limited on Windows
6973 and on WebAssembly platforms,
6974 see the notes in the &Python; documentation for
6975 <ulink url="https://docs.python.org/3/library/os.html#os.chmod">
6976 os.chmod</ulink>, which is the underlying function.
6983 <term><function>Copy</function>(<parameter>dest, src</parameter>)</term>
6985 <para>Returns an Action object
6987 <parameter>src</parameter>
6988 source file or directory to the
6989 <parameter>dest</parameter>
6990 destination file or directory.
6991 If <parameter>src</parameter> is a list,
6992 <parameter>dest</parameter> must be a directory
6993 if it already exists.
6996 <programlisting language="python">
6997 Execute(Copy('foo.output', 'foo.input'))
6999 env.Command('bar.out', 'bar.in', Copy('$TARGET', '$SOURCE'))
7006 <term><function>Delete</function>(<parameter>entry, [must_exist]</parameter>)</term>
7008 <para>Returns an Action that
7009 deletes the specified
7010 <parameter>entry</parameter>,
7011 which may be a file or a directory tree.
7012 If a directory is specified,
7013 the entire directory tree
7016 <parameter>must_exist</parameter>
7017 flag is set to a true value,
7018 then a &Python; error will be raised
7019 if the specified entry does not exist;
7020 the default is false,
7021 that is, the Action will silently do nothing
7022 if the entry does not exist.
7025 <programlisting language="python">
7026 Execute(Delete('/tmp/buildroot'))
7032 Delete('${TARGET.dir}'),
7037 Execute(Delete('file_that_must_exist', must_exist=True))
7044 <term><function>Mkdir</function>(<parameter>name</parameter>)</term>
7046 <para>Returns an Action
7047 that creates the directory
7048 <parameter>name</parameter>
7049 and all needed intermediate directories.
7050 <parameter>name</parameter> may also be a list
7051 of directories to create.
7054 <programlisting language="python">
7055 Execute(Mkdir('/tmp/outputdir'))
7061 Mkdir('/tmp/builddir'),
7062 Copy('/tmp/builddir/foo.in', '$SOURCE'),
7063 "cd /tmp/builddir && make",
7064 Copy('$TARGET', '/tmp/builddir/foo.out'),
7073 <term><function>Move</function>(<parameter>dest, src</parameter>)</term>
7075 <para>Returns an Action
7076 that moves the specified
7077 <parameter>src</parameter>
7078 file or directory to
7080 <parameter>dest</parameter>
7084 <programlisting language="python">
7085 Execute(Move('file.destination', 'file.source'))
7090 action=[MyBuildAction, Move('$TARGET', 'file_created_by_MyBuildAction')],
7098 <term><function>Touch</function>(<parameter>file</parameter>)</term>
7100 <para>Returns an Action
7101 that updates the modification time
7103 <parameter>file</parameter>.
7106 <programlisting language="python">
7107 Execute(Touch('file_to_be_touched'))
7109 env.Command('marker', 'input_file', action=[MyBuildAction, Touch('$TARGET')])
7117 <refsect3 id='variable_substitution'>
7118 <title>Variable Substitution</title>
7121 Before executing a command, &scons;
7122 performs parameter expansion (<firstterm>substitution</firstterm>)
7123 on the string that makes up the action part of the builder.
7124 The format of a substitutable parameter is
7125 <literal>${<replaceable>expression</replaceable>}</literal>.
7126 If <replaceable>expression</replaceable> refers to a variable,
7127 the braces in <literal>${<replaceable>expression</replaceable>}</literal>
7128 can be omitted <emphasis>unless</emphasis> the variable name is
7129 immediately followed by a character that could either be interpreted
7130 as part of the name, or is &Python; syntax such as
7131 <emphasis role="bold">[</emphasis> (for indexing/slicing)
7132 or <emphasis role="bold">.</emphasis> (for attribute access -
7133 see <link linkend="special_attributes">Special Attributes</link> below).
7137 If <replaceable>expression</replaceable> refers to a &consvar;,
7138 it (including the <literal>$</literal> or <literal>${ }</literal>)
7139 is replaced with the value of that variable in the
7140 &consenv; at the time of execution.
7141 If <replaceable>expression</replaceable> looks like
7142 a variable name but is not defined in the &consenv;
7143 it is replaced with an empty string.
7144 If <replaceable>expression</replaceable> refers to one of the
7145 <link linkend="special_variables">Special Variables</link>
7146 (see below) the corresponding value of the variable is substituted.
7147 <replaceable>expression</replaceable> may also be
7148 a &Python; expression to be evaluated.
7149 See <link linkend='python_code_substitution'>Python Code Substitution</link>
7150 below for a description.
7153 <para>&SCons; uses the following rules when converting &consvars; into
7154 command line strings:</para>
7158 <para>If the value is a string it is interpreted as space delimited
7159 command line arguments.</para>
7163 <para>If the value is a list it is interpreted as a list of command
7164 line arguments. Each element of the list is converted to a string.</para>
7168 <para>Anything that is not a list or string is converted to a string and
7169 interpreted as a single command line argument.</para>
7173 <para>Newline characters (<literal>\n</literal>) delimit lines.
7174 The newline parsing is done after
7175 all other parsing, so it is not possible for arguments (e.g. file names) to
7176 contain embedded newline characters.</para>
7180 <para>For a literal <emphasis role="bold">$</emphasis>
7181 use <emphasis role="bold">$$</emphasis>.
7182 For example, <literal>$$FOO</literal> will be left in the
7183 final string as <literal>$FOO</literal>.</para>
7188 When a build action is executed, a hash of the command line is
7189 saved, together with other information about the target(s) built
7190 by the action, for future use in rebuild determination.
7191 This is called the <firstterm>&buildsig;</firstterm>
7192 (or <firstterm>&build_action; signature</firstterm>).
7194 <emphasis role="bold">$(</emphasis>
7195 <replaceable>subexpression</replaceable>
7196 <emphasis role="bold">$)</emphasis>
7197 may be used to indicate parts of a command line
7198 that may change without
7199 causing a rebuild--that is,
7200 which are not to be included when calculating the &buildsig;.
7202 <emphasis role="bold">$(</emphasis>
7203 up to and including the matching
7204 <emphasis role="bold">$)</emphasis>
7205 will be removed from the command line
7206 before it is added to the &buildsig;
7208 <emphasis role="bold">$(</emphasis>
7210 <emphasis role="bold">$)</emphasis>
7211 will be removed before the command is executed.
7212 For example, the command line string:</para>
7214 <programlisting language="python">
7215 "echo Last build occurred $( $TODAY $). > $TARGET"
7218 <para>would execute the command:</para>
7221 echo Last build occurred $TODAY. > $TARGET
7224 <para>but the &buildsig; added to any target files would be computed from:</para>
7227 echo Last build occurred . > $TARGET
7230 <para>While &consvars; are normally directly substituted,
7231 if a &consvar; has a value which
7232 is a callable &Python; object
7233 (a function, or a class with a <literal>__call__</literal> method),
7234 that object is called during substitution.
7235 The callable must accept four arguments:
7236 <parameter>target</parameter>,
7237 <parameter>source</parameter>,
7238 <parameter>env</parameter> and
7239 <parameter>for_signature</parameter>.
7240 <parameter>source</parameter> is a list of source nodes,
7241 <parameter>target</parameter> is a list of target nodes,
7242 <parameter>env</parameter> is the &consenv; to use for context,
7243 and <parameter>for_signature</parameter> is
7244 a boolean value that tells the callable
7245 if it is being called for the purpose of generating a &buildsig;.
7246 Since the &buildsig; is used for rebuild determination,
7247 variable elements that do not affect whether
7248 a rebuild should be triggered
7249 should be omitted from the returned string
7250 if <parameter>for_signature</parameter> is true.
7251 See <emphasis role="bold">$(</emphasis>
7252 and <emphasis role="bold">$)</emphasis> above
7257 &SCons; will insert whatever
7258 the callable returns
7259 into the expanded string:
7262 <programlisting language="python">
7263 def foo(target, source, env, for_signature):
7266 # Will expand $BAR to "bar baz"
7267 env = Environment(FOO=foo, BAR="$FOO baz")
7270 <para>As a reminder, substitution happens when
7271 <literal>$BAR</literal> is actually used in a
7272 builder action. The value of <literal>env['BAR']</literal>
7273 will be exactly as it was set: <literal>"$FOO baz"</literal>.
7274 This can make debugging tricky,
7275 as the substituted result is not available at the time
7276 the &SConscript; files are being interpreted and
7277 thus not available to the <systemitem>print</systemitem> function.
7278 However, you can perform the substitution on demand
7279 by calling the &f-link-env-subst; method for this purpose.
7282 <para>You can use this feature to pass arguments to a
7283 callable variable by creating a callable class
7284 that stores passed arguments in the instance,
7286 (in the <methodname>__call__</methodname> method)
7287 when the instance is called.
7288 Note that in this case,
7289 the entire variable expansion must
7290 be enclosed by curly braces
7291 so that the arguments will
7292 be associated with the
7293 instantiation of the class:</para>
7295 <programlisting language="python">
7297 def __init__(self, arg):
7300 def __call__(self, target, source, env, for_signature):
7301 return self.arg + " bar"
7303 # Will expand $BAR to "my argument bar baz"
7304 env=Environment(FOO=foo, BAR="${FOO('my argument')} baz")
7309 <refsect3 id='special_variables'>
7310 <title>Substitution: Special Variables</title>
7313 Besides regular &consvars;, scons provides the following
7314 <firstterm>Special Variables</firstterm> for use in expanding commands:</para>
7318 <term>&cv-CHANGED_SOURCES;</term>
7320 <para>The file names of all sources of the build command
7321 that have changed since the target was last built.</para>
7326 <term>&cv-CHANGED_TARGETS;</term>
7328 <para>The file names of all targets that would be built
7329 from sources that have changed since the target was last built.</para>
7334 <term>&cv-SOURCE;</term>
7336 <para>The file name of the source of the build command,
7337 or the file name of the first source
7338 if multiple sources are being built.</para>
7343 <term>&cv-SOURCES;</term>
7345 <para>The file names of the sources of the build command.</para>
7350 <term>&cv-TARGET;</term>
7352 <para>The file name of the target being built,
7353 or the file name of the first target
7354 if multiple targets are being built.</para>
7359 <term>&cv-TARGETS;</term>
7361 <para>The file names of all targets being built.</para>
7366 <term>&cv-UNCHANGED_SOURCES;</term>
7368 <para>The file names of all sources of the build command
7370 <emphasis>not</emphasis>
7371 changed since the target was last built.</para>
7376 <term>&cv-UNCHANGED_TARGETS;</term>
7378 <para>The file names of all targets that would be built
7379 from sources that have
7380 <emphasis>not</emphasis>
7381 changed since the target was last built.</para>
7387 These names are reserved
7388 and may not be assigned to or used as &consvars;.
7389 &SCons; computes them in a context-dependent manner
7390 and they are not retrieved from a &consenv;.
7393 <para>For example, the following builder call:
7396 <programlisting language="python">
7397 env = Environment(CC='cc')
7400 source=['foo.c', 'bar.c'],
7401 action='@echo $CC -c -o $TARGET $SOURCES'
7405 <para>would produce the following output:</para>
7408 cc -c -o foo foo.c bar.c
7412 In the previous example, a string
7413 <code>${SOURCES[1]}</code>
7414 would expand to: <computeroutput>bar.c</computeroutput>.
7419 <refsect3 id='special_attributes'>
7420 <title>Substitution: Special Attributes
7422 <para>A variable name may
7424 modifiers appended within the enclosing curly braces
7425 to access properties of the interpolated string.
7426 These are known as <firstterm>special attributes</firstterm>.
7430 <member><parameter>base</parameter> -
7431 The base path of the file name,
7432 including the directory path
7433 but excluding any suffix.
7435 <member><parameter>dir</parameter> - The name of the directory in which the file exists.</member>
7436 <member><parameter>file</parameter> - The file name, minus any directory portion.</member>
7437 <member><parameter>filebase</parameter> - Like <parameter>file</parameter> but minus its suffix.</member>
7438 <member><parameter>suffix</parameter> - Just the file suffix.</member>
7439 <member><parameter>abspath</parameter> - The absolute path name of the file.</member>
7440 <member><parameter>relpath</parameter> - The path name of the file relative to the project top directory.</member>
7441 <member><parameter>posix</parameter> -
7442 The path with directories separated by forward slashes
7443 (<emphasis role="bold">/</emphasis>).
7444 Sometimes necessary on Windows systems
7445 when a path references a file on other (POSIX) systems.
7447 <member><parameter>windows</parameter> -
7448 The path with directories separated by backslashes
7449 (<emphasis role="bold"><literal>\\</literal></emphasis>).
7450 Sometimes necessary on POSIX-style systems
7451 when a path references a file on other (Windows) systems.
7452 <parameter>win32</parameter> is a (deprecated) synonym for
7453 <parameter>windows</parameter>.
7455 <member><parameter>srcpath</parameter> -
7456 The directory and file name to the source file linked to this file through
7458 If this file isn't linked,
7459 it just returns the directory and filename unchanged.
7461 <member><parameter>srcdir</parameter> -
7462 The directory containing the source file linked to this file through
7464 If this file isn't linked,
7465 it just returns the directory part of the filename.
7467 <member><parameter>rsrcpath</parameter> -
7468 The directory and file name to the source file linked to this file through
7470 If the file does not exist locally but exists in a Repository,
7471 the path in the Repository is returned.
7472 If this file isn't linked, it just returns the
7473 directory and filename unchanged.
7475 <member><parameter>rsrcdir</parameter> -
7476 The Repository directory containing the source file linked to this file through
7478 If this file isn't linked,
7479 it just returns the directory part of the filename.
7483 <para>For example, the specified target will
7484 expand as follows for the corresponding modifiers:</para>
7486 <literallayout class="monospaced">
7487 $TARGET => sub/dir/file.x
7488 ${TARGET.base} => sub/dir/file
7489 ${TARGET.dir} => sub/dir
7490 ${TARGET.file} => file.x
7491 ${TARGET.filebase} => file
7492 ${TARGET.suffix} => .x
7493 ${TARGET.abspath} => /top/dir/sub/dir/file.x
7494 ${TARGET.relpath} => sub/dir/file.x
7496 $TARGET => ../dir2/file.x
7497 ${TARGET.abspath} => /top/dir2/file.x
7498 ${TARGET.relpath} => ../dir2/file.x
7500 SConscript('src/SConscript', variant_dir='sub/dir')
7501 $SOURCE => sub/dir/file.x
7502 ${SOURCE.srcpath} => src/file.x
7503 ${SOURCE.srcdir} => src
7505 Repository('/usr/repository')
7506 $SOURCE => sub/dir/file.x
7507 ${SOURCE.rsrcpath} => /usr/repository/src/file.x
7508 ${SOURCE.rsrcdir} => /usr/repository/src
7512 Some modifiers can be combined, like
7513 <literal>${TARGET.srcpath.base)</literal>,
7514 <literal>${TARGET.file.suffix}</literal>, etc.
7519 <refsect3 id='python_code_substitution'>
7520 <title>Python Code Substitution</title>
7523 If a substitutable expression using the notation
7524 <literal>${<replaceable>expression</replaceable>}</literal>
7525 does not appear to match one of the other substitution patterns,
7526 it is evaluated as a &Python; expression.
7527 This uses &Python;'s <function>eval</function> function,
7528 with the <parameter>globals</parameter> parameter set to
7529 the current environment's set of &consvars;,
7530 and the result substituted in.
7531 So in the following case:</para>
7533 <programlisting language="python">
7535 'foo.out', 'foo.in', "echo ${COND==1 and 'FOO' or 'BAR'} > $TARGET"
7539 <para>the command executed will be either</para>
7542 echo FOO > foo.out
7548 echo BAR > foo.out
7551 <para>according to the current value of <literal>env['COND']</literal>
7552 when the command is executed.
7553 The evaluation takes place when the target is being
7554 built, not when the &SConscript; is being read. So if
7555 <literal>env['COND']</literal> is changed
7556 later in the &SConscript;, the final value will be used.</para>
7558 <para>Here's a more complete example. Note that all of
7559 <envar>COND</envar>,
7562 <envar>BAR</envar> are &consvars;,
7563 and their values are substituted into the final command.
7564 <envar>FOO</envar> is a list, so its elements are interpolated
7565 separated by spaces.</para>
7567 <programlisting language="python">
7570 env['FOO'] = ['foo1', 'foo2']
7571 env['BAR'] = 'barbar'
7573 'foo.out', 'foo.in', "echo ${COND==1 and FOO or BAR} > $TARGET"
7577 <para>will execute:</para>
7579 echo foo1 foo2 > foo.out
7583 In point of fact, &Python; expression evaluation is
7584 how the special attributes are substituted:
7585 they are simply attributes of the &Python; objects
7586 that represent &cv-TARGET;, &cv-SOURCES;, etc.,
7587 which &SCons; passes to <function>eval</function> which
7592 Use of the &Python; <function>eval</function> function
7593 is considered to have security implications, since,
7594 depending on input sources,
7595 arbitrary unchecked strings of code can be executed by the &Python; interpreter.
7596 Although &SCons; makes use of it in a somewhat restricted context,
7597 you should be aware of this issue when using the
7598 <literal>${python-expression-for-subst}</literal> form.
7603 <refsect2 id='scanner_objects'>
7604 <title>Scanner Objects</title>
7607 Scanner objects are used
7608 to scan specific file types for implicit dependencies,
7609 for example embedded preprocessor/compiler directives
7610 that cause other files to be included during processing.
7611 &SCons; has a number of pre-built Scanner objects,
7612 so it is usually only necessary to set up Scanners for new file types.
7613 You do this by calling the &f-link-Scanner; factory function.
7614 &f-Scanner; accepts the following arguments.
7615 Only <parameter>function</parameter> is required;
7616 the rest are optional:
7621 <term><parameter>function</parameter></term>
7624 A function which can process ("scan")
7625 a given Node (usually a file)
7626 and return a list of Nodes
7627 representing any implicit
7628 dependencies (usually files) which will be tracked
7630 The function must accept three required arguments,
7631 <parameter>node</parameter>,
7632 <parameter>env</parameter> and
7633 <parameter>path</parameter>,
7634 and an optional fourth,
7635 <parameter>arg</parameter>.
7636 <parameter>node</parameter> is
7637 the internal &SCons; node representing the file to scan,
7638 <parameter>env</parameter> is the &consenv; to use during
7639 the scan, and <parameter>path</parameter> is a tuple
7640 of directories that can be searched for files,
7641 as generated by the optional scanner
7642 <xref linkend="path_function"/>.
7643 If the <xref linkend="scanner-argument"/>
7644 parameter was supplied when the Scanner object was created,
7645 it is passed as the <parameter>arg</parameter> parameter
7646 to the scanner function when it is called.
7647 Since <parameter>argument</parameter> is optional,
7648 the scanner function <emphasis>may</emphasis> be
7649 called without an <parameter>arg</parameter> parameter.
7653 The scanner function can make use of
7654 <function>str</function>(<parameter>node</parameter>)
7655 to fetch the name of the file,
7656 <parameter>node</parameter>.<methodname>dir</methodname>
7657 to fetch the directory the file is in,
7658 <parameter>node</parameter>.<methodname>get_contents</methodname>()
7659 to fetch the contents of the file as bytes or
7660 <parameter>node</parameter>.<methodname>get_text_contents</methodname>()
7661 to fetch the contents of the file as text.
7665 The scanner function should account for any directories
7666 listed in the <parameter>path</parameter> parameter
7667 when determining the existence of possible dependencies.
7668 External tools such as the C/C++ preprocessor are given
7669 lists of directories to search for source file inclusion directives
7670 (e.g. <literal>#include "myheader.h"</literal>).
7671 That list is generated from the relevant path variable
7672 (e.g. &cv-link-CPPPATH; for C/C++). The Scanner can be
7673 directed to pass the same list on to the scanner function
7674 via the <parameter>path</parameter> parameter so it can
7675 search in the same places.
7676 The Scanner is enabled to pass this list via the
7677 <xref linkend="path_function"/> argument at Scanner creation time.
7681 Instead of a scanner function, you can supply a dictionary as the
7682 <parameter>function</parameter> parameter.
7683 The dictionary must map keys (such as file suffixes)
7684 to other Scanner objects.
7685 A Scanner created this way serves as a dispatcher:
7686 the Scanner's <xref linkend="skeys"/> parameter is
7687 automatically populated with the dictionary's keys,
7688 indicating that the Scanner handles Nodes which would be
7689 selected by those keys; the mapping is then used to pass
7690 the file on to a different Scanner that would not have been
7691 selected to handle that Node based on its
7692 own <parameter>skeys</parameter>.
7696 Note that the file to scan is
7697 <emphasis>not</emphasis>
7698 guaranteed to exist at the time the scanner is called -
7699 it could be a generated file which has not been generated yet -
7700 so the scanner function must be tolerant of that.
7704 While many scanner functions operate on source code files by
7705 looking for known patterns in the code, they can really
7706 do anything they need to.
7707 For example, the &b-link-Program; Builder is assigned a
7708 <xref linkend="target_scanner"/> which examines the
7709 list of libraries supplied for the build (&cv-link-LIBS;)
7710 and decides whether to add them as dependencies,
7711 it does not look <emphasis>inside</emphasis> the built binary.
7715 It is up to the scanner function to decide whether or not to
7716 generate an &SCons; dependency for candidates identified by scanning.
7717 Dependencies are a key part of &SCons; operation,
7718 enabling both rebuild determination and correct ordering of builds.
7719 It is particularly important that generated files which are
7720 dependencies are added into the Node graph,
7721 or use-before-create failures are likely.
7722 However, not everything may need to be tracked as a dependency.
7723 In some cases, implementation-provided header files change
7724 infrequently but are included very widely,
7725 so tracking them in the &SCons; node graph could become quite
7726 expensive for limited benefit -
7727 consider for example the C standard header file
7728 <filename>string.h</filename>.
7729 The scanner function is not passed any special information
7730 to help make this choice, so the decision-making encoded
7731 in the scanner function must be carefully considered.
7738 <term><parameter>name</parameter></term>
7740 <para>The name to use for the Scanner.
7741 This is mainly used to identify the Scanner internally.
7742 The default value is <literal>"NONE"</literal>.</para>
7746 <varlistentry id="scanner-argument">
7747 <term><parameter>argument</parameter></term>
7750 will be passed to the scanner function
7751 <parameter>function</parameter>
7752 and the path function
7753 <parameter>path_function</parameter>
7755 as the optional parameter each of those functions takes.
7760 <varlistentry id="skeys">
7761 <term><parameter>skeys</parameter></term>
7763 <para>Scanner key(s) indicating the file types
7764 this scanner is associated with.
7765 Used internally to select an appropriate scanner.
7766 In the usual case of scanning for file names,
7767 this argument will be a list of suffixes
7768 for the different file types that this
7769 Scanner knows how to scan.
7770 If <parameter>skeys</parameter> is a string,
7771 it will be expanded into a list by the current environment.
7776 <varlistentry id="path_function">
7777 <term><parameter>path_function</parameter></term>
7780 If specified, a function to generate paths to pass to
7781 the scanner function to search while generating dependencies.
7782 The function must take five arguments:
7784 a Node for the directory containing
7785 the &SConscript; file in which
7786 the first target was defined,
7787 a list of target nodes,
7788 a list of source nodes,
7789 and the value of <parameter>argument</parameter>
7790 if it was supplied when the Scanner was created
7791 (since <parameter>argument</parameter> is optional,
7792 the function may be called without this argument,
7793 the <parameter>path_function</parameter>
7794 should be prepared for this).
7795 Must return a tuple of directories
7796 that can be searched for files to be returned
7797 by this Scanner object.
7801 The &f-link-FindPathDirs;
7802 function can be called to return a ready-made
7803 <parameter>path_function</parameter>
7804 for a given &consvar; name,
7805 which is often easier than writing your own function from scratch.
7807 <userinput>path_function=FindPathDirs('CPPPATH')</userinput>
7808 means the scanner function will be called with the paths extracted
7809 from &cv-CPPPATH; in the &consenv; <parameter>env</parameter>,
7810 and passed as the <parameter>path</parameter> parameter
7811 to the scanner function.
7817 <term><parameter>node_class</parameter></term>
7819 <para>The class of Node that should be returned
7820 by this Scanner object.
7821 Any strings or other objects returned
7822 by the scanner function
7823 that are not of this class
7824 will be run through the function
7826 <parameter>node_factory</parameter> argument.
7827 A value of <constant>None</constant> can
7828 be supplied to indicate no conversion;
7829 the default is to return File nodes.
7835 <term><parameter>node_factory</parameter></term>
7837 <para>A &Python; function that will take a string
7839 and turn it into the appropriate class of Node
7840 to be returned by this Scanner object,
7841 as indicated by <parameter>node_class</parameter>.
7847 <term><parameter>scan_check</parameter></term>
7849 <para>A Python function that takes two arguments,
7850 a Node (file) and a &consenv;,
7851 and returns whether the
7852 Node should, in fact,
7853 be scanned for dependencies.
7854 This check can be used to eliminate unnecessary
7855 calls to the scanner function when,
7856 for example, the underlying file
7857 represented by a Node does not yet exist.</para>
7862 <term><parameter>recursive</parameter></term>
7865 Specifies whether this scanner should be re-invoked
7866 on the dependency files returned by the scanner.
7867 If omitted, the Node subsystem will
7868 only invoke the scanner on the file being scanned
7870 Recursion is needed when the files returned by the
7871 scanner may themselves contain further file dependencies,
7872 as in the case of preprocessor <literal>#include</literal> lines.
7873 A value that evaluates true enables recursion;
7874 <emphasis>recursive</emphasis>
7875 may be a callable function,
7876 in which case it will be called with a list of
7878 should return a list of Nodes
7879 that should be scanned recursively;
7880 this can be used to select a specific subset of
7881 Nodes for additional scanning.</para>
7887 Once created, a Scanner can be added to an environment
7888 by setting it in the &cv-link-SCANNERS; list,
7889 which automatically triggers &SCons; to also add it
7890 to the environment as a method.
7891 However, usually a scanner is not truly standalone, but needs to
7892 be plugged in to the existing selection mechanism for
7893 deciding how to scan source files based on filename extensions.
7894 For this, &SCons; has a global
7895 <classname>SourceFileScanner</classname>
7896 object that is used by
7897 the &b-link-Object;, &b-link-SharedObject; and &b-link-StaticObject;
7899 which scanner should be used.
7901 <methodname>SourceFileScanner.add_scanner()</methodname>
7902 method to add your own Scanner object
7906 that builds target programs or
7907 libraries from a list of
7908 source files of different types:</para>
7910 <programlisting language="python">
7911 def xyz_scan(node, env, path):
7912 contents = node.get_text_contents()
7913 # Scan the contents and return the included files.
7915 XYZScanner = Scanner(xyz_scan)
7917 SourceFileScanner.add_scanner('.xyz', XYZScanner)
7919 env.Program('my_prog', ['file1.c', 'file2.f', 'file3.xyz'])
7924 <refsect2 id='tool_modules'>
7925 <title>Tool Modules</title>
7928 Custom tools can be added to a project either by
7929 placing them in the <filename>site_tools</filename> subdirectory
7930 of a configured site directory,
7931 or in a location specified by the
7932 <parameter>toolpath</parameter> keyword argument to &f-link-Environment;.
7933 You have to arrange to call a tool to put it into effect,
7934 either as part of the list given to the <parameter>tools</parameter>
7935 keyword argument at &consenv; initialization,
7936 or by calling &f-link-env-Tool;.
7940 The <parameter>toolpath</parameter> parameter
7941 takes a list of path strings,
7942 and the <parameter>tools</parameter> parameter
7943 takes a list of tools, which are often strings:
7946 <programlisting language="python">
7947 env = Environment(tools=['default', 'foo'], toolpath=['tools'])
7951 This looks for a tool specification module <literal>foo</literal>
7952 in directory <filename>tools</filename> and in the standard locations,
7953 as well as using the ordinary default tools for the platform.
7957 When looking up tool specification modules,
7958 directories specified via <parameter>toolpath</parameter> are
7959 considered before the existing tool path
7960 (<filename>site_tools</filename> subdirectories
7961 of the default or specified site directories),
7962 which are in turn considered before built-in tools.
7964 a tool specification module <filename>gcc.py</filename> to the toolpath
7965 directory would override the built-in &t-link-gcc; tool.
7966 The <parameter>toolpath</parameter> is saved in the environment
7967 and will be used by subsequent calls to the &f-link-env-Tool; method,
7968 as well as by &f-link-env-Clone;.
7971 <programlisting language="python">
7972 base = Environment(toolpath=['custom_path'])
7973 derived = base.Clone(tools=['custom_tool'])
7974 derived.CustomBuilder()
7978 A tool specification module is a form of &Python; module,
7979 looked up internally using the &Python; import mechanism,
7980 so a tool can consist either
7981 of a single &Python; file taking the name of the tool
7982 (e.g. <filename>mytool.py</filename>) or a directory taking
7983 the name of the tool (e.g. <filename>mytool/</filename>)
7984 which contains at least an <filename>__init__.py</filename> file.
7985 A tool specification module has two required entry points:
7990 <term><function>generate</function>(<parameter>env, **kwargs</parameter>)</term>
7992 <para>Modify the &consenv; <parameter>env</parameter>
7993 to set up necessary &consvars;, Builders, Emitters, etc.,
7994 so the facilities represented by the tool can be executed.
7995 Take care not to overwrite &consvars; which may
7996 have been explicitly set by the user;
7997 retain and/or append instead. For example:
7999 <programlisting language="python">
8002 if 'MYTOOL' not in env:
8003 env['MYTOOL'] = env.Detect("mytool")
8004 flags = env.get('MYTOOLFLAGS', SCons.Util.CLVar())
8005 env.AppendUnique(MYTOOLFLAGS='--myarg')
8009 <para>The <function>generate</function> function
8010 may use any keyword arguments
8011 that the user supplies via <parameter>kwargs</parameter>
8012 to vary its initialization.</para>
8016 <term><function>exists</function>(<parameter>env</parameter>)</term>
8018 <para>Return a truthy value if the tool can
8019 be called in the context of <parameter>env</parameter>,
8020 else return a falsy value.
8021 Usually this means looking up one or more
8022 known programs using the <varname>PATH</varname> from the
8023 supplied <parameter>env</parameter>, but the tool can
8024 make the <emphasis>exists</emphasis> decision in any way it chooses.
8032 At the moment, user-added tools do not automatically have their
8033 <function>exists</function> function called.
8034 As a result, it is recommended that the <function>generate</function>
8035 function be defensively coded - that is, do not rely on any
8036 necessary existence checks already having been performed.
8037 This is expected to be a temporary limitation,
8038 and the <function>exists</function> function should still be provided.
8042 <para>An element of the <parameter>tools</parameter> list may also
8043 be a function or other callable object
8044 (including a Tool object returned by a previous call to
8045 &f-link-Tool;) in which case the &f-link-Environment; function
8046 will directly call that object
8047 to update the new &consenv;.
8048 No tool lookup is done in this case.
8051 <programlisting language="python">
8053 env['XYZZY'] = 'xyzzy'
8055 env = Environment(tools=[my_tool])
8058 <para>An element of the <parameter>tools</parameter> list
8059 may also be a two-element list or tuple of the form
8060 <literal>(toolname, kw_dict)</literal>.
8061 SCons searches for the tool specification module
8062 <parameter>toolname</parameter>
8064 and passes <parameter>kw_dict</parameter>,
8065 which must be a dictionary,
8066 as keyword arguments to the tool's
8067 <function>generate</function> function.
8068 The <function>generate</function>
8069 function can use those arguments to modify the tool's behavior
8070 by setting up the environment in different ways
8071 or otherwise changing its initialization.</para>
8073 <programlisting language="python">
8074 # in tools/my_tool.py:
8075 def generate(env, **kwargs):
8076 # Sets MY_TOOL to the value of keyword 'arg1' or '1' if not supplied
8077 env['MY_TOOL'] = kwargs.get('arg1', '1')
8084 tools=['default', ('my_tool', {'arg1': 'abc'})], toolpath=['tools']
8088 <para>The tool specification (<function>my_tool</function> in the example)
8090 &cv-link-PLATFORM; variable from
8091 the &consenv; it is passed to customize the tool for different platforms.
8094 <para>Tools can be "nested" - that is, they
8095 can be located within a subdirectory in the toolpath.
8096 A nested tool name uses a dot to represent a directory separator</para>
8098 <programlisting language="python">
8099 # namespaced builder
8100 env = Environment(ENV=os.environ.copy(), tools=['SubDir1.SubDir2.SomeTool'])
8101 env.SomeTool(targets, sources)
8104 # SCons\Tool\SubDir1\SubDir2\SomeTool.py
8105 # SCons\Tool\SubDir1\SubDir2\SomeTool\__init__.py
8106 # .\site_scons\site_tools\SubDir1\SubDir2\SomeTool.py
8107 # .\site_scons\site_tools\SubDir1\SubDir2\SomeTool\__init__.py
8113 <refsect1 id='systemspecific_behavior'>
8114 <title>SYSTEM-SPECIFIC BEHAVIOR</title>
8116 <para>&scons; and its configuration files are very portable,
8117 due largely to its implementation in &Python;.
8118 There are, however, a few portability
8119 issues waiting to trap the unwary.</para>
8121 <refsect2 id='c_file_suffix'>
8122 <title>.C File Suffix</title>
8124 <para>&scons; handles the upper-case
8125 <filename>.C</filename>
8126 file suffix differently,
8127 depending on the capabilities of
8128 the underlying system.
8129 On a case-sensitive system
8130 such as Linux or UNIX,
8131 &scons; treats a file with a
8132 <filename>.C</filename>
8133 suffix as a C++ source file.
8134 On a case-insensitive system
8136 &scons; treats a file with a
8137 <filename>.C</filename>
8138 suffix as a C source file.</para>
8141 <refsect2 id='f_file_suffix'>
8142 <title>Fortran File Suffixes</title>
8145 There are several ways source file suffixes impact the
8146 behavior of &SCons; when working with Fortran language code
8147 (not all are system-specific, but they are included here
8152 As the Fortran language has evolved through multiple
8153 standards editions, projects might have a need to handle
8154 files from different language generations differently.
8155 To this end, &SCons; dispatches to a different compiler
8156 dialect setup (expressed as a set of &consvars;)
8157 depending on the file suffix.
8158 By default, all of these setups start out the same,
8159 but individual &consvars; can be modified as needed to tune a given dialect.
8160 Each of these dialects has a tool specification module
8161 whose documentation describes the &consvars; associated
8162 with that dialect: <filename>.f</filename>
8163 (as well as <filename>.for</filename> and <filename>.ftn</filename>)
8164 in &t-link-fortran;; (&consvars; start with <literal>FORTRAN</literal>)
8165 <filename>.f77</filename> in &t-link-f77;;
8166 (&consvars; start with <literal>F77</literal>)
8167 <filename>.f90</filename> in &t-link-f90;;
8168 (&consvars; start with <literal>F90</literal>)
8169 <filename>.f95</filename> in &t-link-f95;;
8170 (&consvars; start with <literal>F95</literal>)
8171 <filename>.f03</filename> in &t-link-f03;;
8172 (&consvars; start with <literal>F03</literal>)
8173 <filename>.f08</filename> in &t-link-f08;
8174 (&consvars; start with <literal>F08</literal>).
8178 While &SCons; recognizes multiple internal dialects
8179 based on filename suffixes,
8180 the convention of various available Fortran compilers is
8181 to assign an actual meaning to only two of these suffixes:
8182 <filename>.f</filename>
8183 (as well as <filename>.for</filename> and <filename>.ftn</filename>)
8184 refers to the fixed-format source
8185 code that was the only available option in FORTRAN 77 and earlier,
8186 and <filename>.f90</filename> refers to free-format source code
8187 which became available as of the Fortran 90 standard.
8188 Some compilers recognize suffixes which correspond to Fortran
8189 specifications later than F90 as equivalent to
8190 <filename>.f90</filename> for this purpose,
8191 while some do not - check the documentation for your compiler.
8192 An occasionally suggested policy suggestion is to use only
8193 <filename>.f</filename> and <filename>.f90</filename>
8194 as Fortran filename suffixes.
8195 The fixed/free form determination can usually be controlled
8196 explicitly with compiler flags
8197 (e.g. <option>-ffixed-form</option> for gfortran),
8198 overriding any assumption that may be made based on the source file suffix.
8202 The source file suffix does not imply conformance
8203 with the similarly-named Fortran standard - a suffix of
8204 <filename>.f08</filename> does not mean you are compiling
8205 specifically for Fortran 2008. Normally, compilers
8206 provide command-line options for making this selection
8207 (e.g. <option>-std=f2008</option> for gfortran).
8211 For dialects from F90 on (including the generic FORTRAN dialect),
8212 a suffix of <filename>.mod</filename> is recognized for Fortran modules.
8213 These files are a side effect of compiling a Fortran
8214 source file containing module declarations,
8215 and must be available when other code which declares
8216 that it uses the module is processed.
8217 &SCons; does not currently have integrated support for submodules,
8218 introduced in the Fortran 2008 standard -
8219 the invoked compiler will produce results,
8220 but &SCons; will not recognize
8221 <filename>.smod</filename> files as tracked objects.
8225 On a case-sensitive system such as Linux or UNIX,
8226 a file with a an upper-cased suffix from the set
8227 <filename>.F</filename>,
8228 <filename>.FOR</filename>,
8229 <filename>.FTN</filename>,
8230 <filename>.F90</filename>,
8231 <filename>.F95</filename>,
8232 <filename>.F03</filename> and
8233 <filename>.F08</filename>
8234 is treated as a Fortran source file
8235 which shall first be run through
8236 the standard C preprocessor.
8237 The lower-cased versions of these suffixes do not
8238 trigger this behavior.
8239 On systems which do not distinguish between upper
8240 and lower case in filenames,
8241 this behavior is not available,
8242 but files suffixed with either
8243 <filename>.FPP</filename>
8244 or <filename>.fpp</filename>
8245 are always passed to the preprocessor first.
8246 This matches the convention of <command>gfortran</command>
8247 from the GNU Compiler Collection,
8248 and also followed by certain other Fortran compilers.
8249 For these two suffixes,
8250 the generic <emphasis>FORTRAN</emphasis> dialect will be selected.
8254 &SCons; itself does not invoke the preprocessor,
8255 that is handled by the compiler,
8256 but it adds &consvars; which are applicable to the preprocessor run.
8257 You can see this difference by examining
8258 &cv-link-FORTRANPPCOM; and &cv-link-FORTRANPPCOMSTR;
8259 which are used instead of
8260 &cv-link-FORTRANCOM; and &cv-link-FORTRANCOMSTR; for that dialect.
8264 <refsect2 id='windows_cygwin_tools_and_cygwin_python_v'>
8265 <title>Windows: Cygwin Tools and Cygwin Python vs. Windows Pythons</title>
8267 <para>Cygwin supplies a set of tools and utilities
8268 that let users work on a
8269 Windows system using a POSIX-like environment.
8270 The Cygwin tools, including Cygwin &Python;,
8272 by sharing an ability to interpret POSIX-style path names.
8273 For example, the Cygwin tools
8274 will internally translate a Cygwin path name
8275 like <filename>/cygdrive/c/mydir</filename>
8276 to an equivalent Windows pathname
8277 of <filename>C:/mydir</filename> (equivalent to <filename>C:\mydir</filename>).
8280 <para>Versions of &Python;
8281 that are built for native Windows execution,
8282 such as the python.org and ActiveState versions,
8283 do not understand the Cygwin path name semantics.
8284 This means that using a native Windows version of &Python;
8285 to build compiled programs using Cygwin tools
8286 (such as &gcc;, &bison; and &flex;)
8287 may yield unpredictable results.
8288 "Mixing and matching" in this way
8289 can be made to work,
8290 but it requires careful attention to the use of path names
8291 in your &SConscript; files.</para>
8293 <para>In practice, users can sidestep
8294 the issue by adopting the following guidelines:
8295 When using Cygwin's &gcc; for compiling,
8296 use the Cygwin-supplied &Python; interpreter
8299 (or some other "native" Windows compiler)
8300 use the python.org, Microsoft Store, ActiveState or other
8301 native version of &Python; to run &scons;.
8305 This discussion largely applies to the msys2 environment
8306 as well (with the use of the mingw compiler toolchain),
8307 in particular the recommendation to use the msys2 version of
8308 &Python; if running &scons; from inside an msys2 shell.
8312 <refsect2 id='windows_sconsbat_file'>
8313 <title>Windows: <filename>scons.bat</filename> file</title>
8315 <para>On Windows, if &scons; is executed via a wrapper
8316 <filename>scons.bat</filename> batch file,
8317 there are (at least) two ramifications.
8318 Note this is no longer the default - &scons; installed
8319 via &Python;'s <command>pip</command> installer
8320 will have a <command>scons.exe</command> which does
8321 not have these limitations:
8324 <para>First, Windows command-line users
8325 that want to use variable assignment
8327 may have to put double quotes
8328 around the assignments, otherwise the
8329 Windows command shell will consume those as
8330 arguments to itself, not to &scons;:</para>
8333 <userinput>scons "FOO=BAR" "BAZ=BLEH"</userinput>
8336 <para>Second, the Cygwin shell does not
8337 recognize typing <userinput>scons</userinput>
8338 at the command line prompt as referring to this wrapper.
8339 You can work around this either by executing
8340 <userinput>scons.bat</userinput>
8341 (including the extension)
8342 from the Cygwin command line,
8343 or by creating a wrapper shell
8345 <filename>scons</filename> which
8346 invokes <filename>scons.bat</filename>.
8351 <refsect2 id='mingw'>
8352 <title>MinGW</title>
8354 <para>The MinGW <filename>bin</filename>
8355 directory must be in your <envar>PATH</envar>
8356 environment variable or the
8357 <varname>['ENV']['PATH']</varname> &consvar; for &scons;
8358 to detect and use the MinGW tools. When running under the native Windows
8359 &Python; interpreter, &scons; will prefer the MinGW tools over the Cygwin
8360 tools, if they are both installed, regardless of the order of the bin
8361 directories in the <envar>PATH</envar> variable.
8362 If you have both MSVC and MinGW
8363 installed and you want to use MinGW instead of MSVC,
8364 then you must explicitly tell &scons; to use MinGW by passing
8365 <code>tools=['mingw']</code>
8366 to the &Environment; function, because &scons; will prefer the MSVC tools
8367 over the MinGW tools.</para>
8372 <!-- Removed in favor of scons-cookbook.readthedocs.io,
8373 but leave here for the time being...
8375 <refsect1 id='examples'>
8376 <title>EXAMPLES</title>
8378 <para>To help you get started using &scons;,
8379 this section contains a brief overview of some common tasks.
8380 See the &SCons; User Guide for many more examples.
8384 <refsect2 id='basic_compilation_from_a_single_source_f'>
8385 <title>Basic Compilation From a Single Source File</title>
8387 <programlisting language="python">
8389 env.Program(target='foo', source='foo.c')
8392 <para>Note: Build the file by specifying
8393 the target as an argument
8394 (<userinput>scons foo</userinput> or <userinput>scons foo.exe</userinput>)
8395 or by specifying the current directory as the target
8396 (<userinput>scons .</userinput>).</para>
8400 <refsect2 id='basic_compilation_from_multiple_source_f'>
8401 <title>Basic Compilation From Multiple Source Files</title>
8403 <programlisting language="python">
8405 env.Program(target='foo', source=Split('f1.c f2.c f3.c'))
8410 <refsect2 id='setting_a_compilation_flag'>
8411 <title>Setting a Compilation Flag</title>
8413 <programlisting language="python">
8414 env = Environment(CCFLAGS='-g')
8415 env.Program(target='foo', source='foo.c')
8420 <refsect2 id='search_the_local_directory_for_h_files'>
8421 <title>Search The Local Directory For .h Files</title>
8424 <emphasis>not</emphasis>
8425 need to set <envar>CCFLAGS</envar> to specify
8426 <option>-I</option> options by hand.
8427 &scons; will construct the right <option>-I</option>
8428 options from the contents of <envar>CPPPATH.</envar></para>
8430 <programlisting language="python">
8431 env = Environment(CPPPATH=['.'])
8432 env.Program(target='foo', source='foo.c')
8437 <refsect2 id='search_multiple_directories_for_h_files'>
8438 <title>Search Multiple Directories For .h Files</title>
8440 <programlisting language="python">
8441 env = Environment(CPPPATH=['include1', 'include2'])
8442 env.Program(target='foo', source='foo.c')
8447 <refsect2 id='building_a_static_library'>
8448 <title>Building a Static Library</title>
8450 <programlisting language="python">
8452 env.StaticLibrary(target='foo', source=Split('l1.c l2.c'))
8453 env.StaticLibrary(target='bar', source=['l3.c', 'l4.c'])
8458 <refsect2 id='building_a_shared_library'>
8459 <title>Building a Shared Library</title>
8461 <programlisting language="python">
8463 env.SharedLibrary(target='foo', source=['l5.c', 'l6.c'])
8464 env.SharedLibrary(target='bar', source=Split('l7.c l8.c'))
8469 <refsect2 id='linking_a_local_library_into_a_program'>
8470 <title>Linking a Local Library Into a Program</title>
8472 <programlisting language="python">
8473 env = Environment(LIBS='mylib', LIBPATH=['.'])
8474 env.Library(target='mylib', source=Split('l1.c l2.c'))
8475 env.Program(target='prog', source=['p1.c', 'p2.c'])
8480 <refsect2 id='defining_your_own_builder_object'>
8481 <title>Defining Your Own Builder Object</title>
8483 <para>Notice that when you invoke the Builder,
8484 you can leave off the target file suffix,
8485 and &scons; will add it automatically.</para>
8487 <programlisting language="python">
8489 action='pdftex < $SOURCES > $TARGET',
8493 env = Environment(BUILDERS={'PDFBuilder': bld})
8494 env.PDFBuilder(target='foo.pdf', source='foo.tex')
8496 # The following creates "bar.pdf" from "bar.tex"
8497 env.PDFBuilder(target='bar', source='bar')
8500 <para>Note that the above initialization
8501 replaces the default dictionary of Builders,
8502 so this &consenv; can not be used call Builders like
8503 &b-link-Program;, &b-link-Object;, &b-link-StaticLibrary; etc.
8504 See the next example for an alternative.
8509 <refsect2 id='adding_your_own_builder_object_to_an_env'>
8510 <title>Adding Your Own Builder Object to an Environment</title>
8512 <programlisting language="python">
8514 action='pdftex < $SOURCES > $TARGET'
8519 env.Append(BUILDERS={'PDFBuilder': bld})
8520 env.PDFBuilder(target='foo.pdf', source='foo.tex')
8521 env.Program(target='bar', source='bar.c')
8524 <para>You also can use other Pythonic techniques to add
8525 to the <envar>BUILDERS</envar> &consvar;, such as:</para>
8527 <programlisting language="python">
8529 env['BUILDERS]['PDFBuilder'] = bld
8534 <refsect2 id='defining_your_own_scanner_object'>
8535 <title>Defining Your Own Scanner Object</title>
8537 <para>The following example shows adding an extremely simple scanner
8538 (<function>kfile_scan</function>)
8539 that doesn't use a search path at all
8540 and simply returns the
8541 file names present on any
8542 <literal>include</literal>
8543 lines in the scanned file.
8544 This would implicitly assume that all included
8545 files live in the top-level directory:</para>
8547 <programlisting language="python">
8550 include_re = re.compile(r'^include\s+(\S+)$', re.M)
8552 def kfile_scan(node, env, path, arg):
8553 contents = node.get_text_contents()
8554 includes = include_re.findall(contents)
8555 return env.File(includes)
8559 function=kfile_scan,
8564 scanners = DefaultEnvironment()['SCANNERS']
8565 scanners.append(kscan)
8566 env = Environment(SCANNERS=scanners)
8568 env.Command('foo', 'foo.k', 'kprocess < $SOURCES > $TARGET')
8570 bar_in = File('bar.in')
8571 env.Command('bar', bar_in, 'kprocess $SOURCES > $TARGET')
8572 bar_in.target_scanner = kscan
8575 <para>It is important to note that you
8576 have to return a list of File nodes from the scan function, simple
8577 strings for the file names won't do. As in the examples shown here,
8578 you can use the &f-link-env-File;
8579 function of your current &consenv; in order to create nodes on the fly from
8580 a sequence of file names with relative paths.</para>
8582 <para>Here is a similar but more complete example that adds
8583 a scanner which searches
8584 a path of directories
8586 <envar>MYPATH</envar> &consvar;)
8587 for files that actually exist:</para>
8589 <programlisting language="python">
8593 include_re = re.compile(r'^include\s+(\S+)$', re.M)
8595 def my_scan(node, env, path, arg):
8596 contents = node.get_text_contents()
8597 includes = include_re.findall(contents)
8601 for inc in includes:
8603 file = str(dir) + os.sep + inc
8604 if os.path.exists(file):
8605 results.append(file)
8607 return env.File(results)
8614 path_function=FindPathDirs('MYPATH'),
8617 scanners = DefaultEnvironment()['SCANNERS']
8618 scanners.append(scanner)
8619 env = Environment(SCANNERS=scanners, MYPATH=['incs'])
8621 env.Command('foo', 'foo.x', 'xprocess < $SOURCES > $TARGET')
8625 &f-link-FindPathDirs;
8626 function used in the previous example returns a function
8627 (actually a callable &Python; object)
8628 that will return a list of directories
8630 <envar>MYPATH</envar>
8631 &consvar;. It lets &scons; detect the file
8632 <filename>incs/foo.inc</filename>,
8634 <filename>foo.x</filename>
8636 <literal>include foo.inc</literal>
8638 If you need to customize how the search path is derived,
8639 you would provide your own
8640 <parameter>path_function</parameter>
8641 argument when creating the Scanner object,
8644 <programlisting language="python">
8645 # MYPATH is a list of directories to search for files in
8646 def pf(env, dir, target, source, arg):
8647 top_dir = Dir('#').abspath
8650 for p in env['MYPATH']:
8651 results.append(top_dir + os.sep + p)
8666 <refsect2 id='creating_a_hierarchical_build'>
8667 <title>Creating a Hierarchical Build</title>
8669 <para>Notice that the file names specified in a subdirectory's
8670 &SConscript; file are relative to that subdirectory.</para>
8672 <para><filename>SConstruct</filename>:</para>
8674 <programlisting language="python">
8676 env.Program(target='foo', source='foo.c')
8678 SConscript('sub/SConscript')
8681 <para><filename>sub/SConscript</filename>:</para>
8683 <programlisting language="python">
8685 # Builds sub/foo from sub/foo.c
8686 env.Program(target='foo', source='foo.c')
8688 SConscript('dir/SConscript')
8691 <para><filename>sub/dir/SConscript</filename>:</para>
8693 <programlisting language="python">
8695 # Builds sub/dir/foo from sub/dir/foo.c
8696 env.Program(target='foo', source='foo.c')
8701 <refsect2 id='sharing_variables_between_sconscript_fil'>
8702 <title>Sharing Variables Between SConscript Files</title>
8704 <para>You must explicitly call &f-link-Export; and &f-link-Import;
8706 you want to share between &SConscript; files.</para>
8708 <para><filename>SConstruct</filename>:</para>
8710 <programlisting language="python">
8712 env.Program(target='foo', source='foo.c')
8715 SConscript('subdirectory/SConscript')
8718 <para><filename>subdirectory/SConscript</filename>:</para>
8720 <programlisting language="python">
8722 env.Program(target='foo', source='foo.c')
8727 <refsect2 id='building_multiple_variants_from_the_same'>
8728 <title>Building Multiple Variants From the Same Source</title>
8730 <para>Use the <parameter>variant_dir</parameter> keyword argument to
8731 the &f-link-SConscript; function to establish
8732 one or more separate variant build directory trees
8733 for a given source directory:</para>
8735 <para><filename>SConstruct</filename>:</para>
8737 <programlisting language="python">
8738 cppdefines = ['FOO']
8739 Export("cppdefines")
8740 SConscript('src/SConscript', variant_dir='foo')
8742 cppdefines = ['BAR']
8743 Export("cppdefines")
8744 SConscript('src/SConscript', variant_dir='bar')
8747 <para><filename>src/SConscript</filename>:</para>
8749 <programlisting language="python">
8750 Import("cppdefines")
8751 env = Environment(CPPDEFINES=cppdefines)
8752 env.Program(target='src', source='src.c')
8755 <para>Note the use of the &f-link-Export; method
8756 to set the <varname>cppdefines</varname> variable to a different
8757 value each time we call the &f-link-SConscript; function.</para>
8761 <refsect2 id='hierarchical_build_of_two_libraries_link'>
8762 <title>Hierarchical Build of Two Libraries Linked With a Program</title>
8764 <para><filename>SConstruct</filename>:</para>
8766 <programlisting language="python">
8767 env = Environment(LIBPATH=['#libA', '#libB'])
8769 SConscript('libA/SConscript')
8770 SConscript('libB/SConscript')
8771 SConscript('Main/SConscript')
8774 <para><filename>libA/SConscript</filename>:</para>
8776 <programlisting language="python">
8778 env.Library('a', Split('a1.c a2.c a3.c'))
8781 <para><filename>libB/SConscript</filename>:</para>
8783 <programlisting language="python">
8785 env.Library('b', Split('b1.c b2.c b3.c'))
8788 <para><filename>Main/SConscript</filename>:</para>
8790 <programlisting language="python">
8792 e = env.Clone(LIBS=['a', 'b'])
8793 e.Program('foo', Split('m1.c m2.c m3.c'))
8796 <para>The <literal>#</literal> in the <envar>LIBPATH</envar>
8797 directories specify that they're relative to the
8798 top-level directory, so they don't turn into
8799 <filename>Main/libA</filename> when they're
8800 used in <filename>Main/SConscript</filename></para>
8802 <para>Specifying only 'a' and 'b' for the library names
8803 allows &scons; to attach the appropriate library
8804 prefix and suffix for the current platform in
8805 creating the library filename
8806 (for example, <filename>liba.a</filename> on POSIX systems,
8807 <filename>a.lib</filename> on Windows).</para>
8811 <refsect2 id='customizing_construction_variables_from_'>
8812 <title>Customizing &consvars; from the command line.</title>
8814 <para>The following would allow the C compiler to be specified on the command
8815 line or in the file <filename>custom.py</filename>.</para>
8817 <programlisting language="python">
8818 vars = Variables('custom.py')
8819 vars.Add('CC', 'The C compiler.')
8820 env = Environment(variables=vars)
8821 Help(vars.GenerateHelpText(env))
8824 <para>The user could specify the C compiler on the command line:</para>
8827 <userinput>scons "CC=my_cc"</userinput>
8830 <para>or in the <filename>custom.py</filename> file:</para>
8832 <programlisting language="python">
8836 <para>or get documentation on the options:</para>
8839 $ <userinput>scons -h</userinput>
8848 <refsect2 id='using_microsoft_visual_c_precompiled_hea'>
8849 <title>Using &MSVC; precompiled headers</title>
8851 <para>Since <filename>windows.h</filename> includes everything
8852 and the kitchen sink, it can take quite
8853 some time to compile it over and over again for a bunch of object files, so
8854 Microsoft provides a mechanism to compile a set of headers once and then
8855 include the previously compiled headers in any object file. This
8856 technology is called precompiled headers (<firstterm>PCH</firstterm>).
8857 The general recipe is to create a
8858 file named <filename>StdAfx.cpp</filename>
8859 that includes a single header named <filename>StdAfx.h</filename>,
8860 and then include every header you want to precompile in
8861 <filename>StdAfx.h</filename>,
8862 and finally include <filename>"StdAfx.h</filename>
8863 as the first header in all the source files you are
8864 compiling to object files. For example:</para>
8866 <para><filename>StdAfx.h</filename>:</para>
8868 <programlisting language="C++">
8869 #include <windows.h>
8870 #include <my_big_header.h>
8873 <para><filename>StdAfx.cpp</filename>:</para>
8875 <programlisting language="C++">
8876 #include <StdAfx.h>
8879 <para><filename>Foo.cpp</filename>:</para>
8881 <programlisting language="C++">
8882 #include <StdAfx.h>
8887 <para><filename>Bar.cpp</filename>:</para>
8889 <programlisting language="C++">
8890 #include <StdAfx.h>
8892 /* do some other stuff */
8895 <para><filename>SConstruct</filename>:</para>
8897 <programlisting language="python">
8899 env['PCHSTOP'] = 'StdAfx.h'
8900 env['PCH'] = env.PCH('StdAfx.cpp')[0]
8901 env.Program('MyApp', ['Foo.cpp', 'Bar.cpp'])
8904 <para>For more information see the documentation for the &b-link-PCH; builder,
8905 and the &cv-link-PCH; and &cv-link-PCHSTOP; &consvars;.
8906 To learn about the details of precompiled
8907 headers consult the MSDN documentation for
8908 <option>/Yc</option>, <option>/Yu</option>, and <option>/Yp</option>.</para>
8912 <refsect2 id='using_microsoft_visual_c_external_debugg'>
8913 <title>Using &MSVC; external debugging information</title>
8915 <para>Since including debugging information in programs and shared libraries can
8916 cause their size to increase significantly, Microsoft provides a mechanism
8917 for including the debugging information in an external file called a
8918 <firstterm>PDB</firstterm> file.
8919 &scons; supports PDB files through the &cv-PDB; &consvar;.</para>
8921 <para><filename>SConstruct</filename>:</para>
8923 <programlisting language="python">
8925 env['PDB'] = 'MyApp.pdb'
8926 env.Program('MyApp', ['Foo.cpp', 'Bar.cpp'])
8929 <para>For more information see the documentation for the
8930 &cv-link-PDB; &consvar;.</para>
8935 <refsect1 id='environment'>
8936 <title>ENVIRONMENT</title>
8938 <para>In general, &scons; is not controlled by environment
8939 variables set in the shell used to invoke it, leaving it
8940 up to the &SConscript; file author to import those if desired.
8941 However, the following variables are imported by
8942 &scons; itself if set:
8947 <term><envar>SCONS_LIB_DIR</envar></term>
8949 <para>Specifies the directory that contains the &scons;
8950 &Python; module directory. Normally &scons; can deduce this,
8951 but in some circumstances, such as working with a source
8952 release, it may be necessary to specify
8954 <filename>/home/aroach/scons-src-0.01/src/engine</filename>).</para>
8958 <varlistentry id="v-SCONSFLAGS">
8959 <term><envar>SCONSFLAGS</envar></term>
8961 <para>A string containing options that will be used by &scons;
8962 in addition to those passed on the command line.
8963 Can be used to reduce frequent retyping of common options.
8964 The contents of <envar>SCONSFLAGS</envar> are considered
8965 before any passed command line options,
8966 so the command line can be used to override
8967 <envar>SCONSFLAGS</envar> options if necessary.
8973 <term><envar>SCONS_CACHE_MSVC_CONFIG</envar></term>
8975 <para>(Windows only). If set, save the shell environment variables
8976 generated when setting up the &MSVC; compiler
8977 (and/or Build Tools) to a cache file, to give these settings
8978 persistence across &scons; invocations.
8979 Generating this information is relatively expensive,
8980 so using this option may aid performance where &scons; is run often,
8981 such as Continuous Integration setups.</para>
8983 <para>If set to a True-like value (<literal>"1"</literal>,
8984 <literal>"true"</literal> or
8985 <literal>"True"</literal>) will cache to a file named
8986 <filename>scons_msvc_cache.json</filename> in the user's home directory.
8987 If set to a pathname, will use that pathname for the cache.</para>
8989 <para>Note: this implementation may still be somewhat fragile.
8990 In case of problems, remove the cache file - recreating with
8991 fresh info normally resolves any issues.
8992 &SCons; ignores failures reading or writing the cache file
8993 and will silently revert to non-cached behavior in such cases.
8996 <para><emphasis>New in 3.1 (experimental).
8997 The default cache file name was changed to
8998 its present value in 4.4, and contents were expanded.</emphasis>
9004 <term><envar>QTDIR</envar></term>
9006 <para>If using the &t-link-qt; tool, this is the path to
9007 the Qt installation to build against. &SCons; respects this
9008 setting because it is a long-standing convention in the Qt world,
9009 where multiple Qt installations are possible.</para>
9015 <refsect1 id='see_also'>
9016 <title>SEE ALSO</title>
9018 <simplelist type="vert">
9020 The SCons User Guide at
9021 <ulink url="https://scons.org/doc/production/HTML/scons-user.html"/>
9023 <member>The SCons Design Document (old)</member>
9025 The SCons Cookbook at
9026 <ulink url="https://scons-cookbook.readthedocs.io"/>
9027 for examples of how to solve various problems with &SCons;.
9031 <ulink url="https://github.com/SCons/scons">
9035 The SCons API Reference
9036 <ulink url="https://scons.org/doc/production/HTML/scons-api/index.html"/>
9037 (for internal details)
9043 <refsect1 id='authors'>
9044 <title>AUTHORS</title>
9046 <para>Originally: Steven Knight
9047 <email>knight@baldmt.com</email>
9048 and Anthony Roach <email>aroach@electriceyeball.com</email>.
9051 Since 2010: The SCons Development Team <email>scons-dev@scons.org</email>.