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>
4707 <para>Often when building software,
4708 specialized information needs to be conveyed at build time
4709 to override the defaults in the build scripts.
4710 Command-line arguments (like <literal>--implcit-cache</literal>)
4711 and giving names of build targets are two ways to do that.
4712 Another is to provide variable-assignment arguments
4713 on the command line.
4714 For the particular case where you want to specify new
4715 values for &consvars;,
4716 &SCons; provides a <firstterm>&Variables;</firstterm>
4717 object to simplify collecting those
4718 and updating a &consenv; with the values.
4719 The typical calling style looks like:
4723 <userinput>scons VARIABLE=foo</userinput>
4727 Variables specified in the above way
4728 can be manually processed by accessing the
4729 <link linkend="v-ARGUMENTS">&ARGUMENTS;</link> dictionary
4730 (or <link linkend="v-ARGLIST">&ARGLIST;</link> list),
4731 but using a &Variables; object allows you to describe
4732 anticipated variables,
4733 convert them to a suitable type if necessary,
4734 validate the values are within defined constraints,
4735 and define defaults, help messages and aliases.
4736 This is conceptually similar to the structure of options
4737 (see &f-link-AddOption;).
4738 It also allows obtaining values from a saved variables file,
4739 or from a custom dictionary in an &SConscript; file.
4740 The processed variables can then be applied to the desired &consenv;.
4744 Roughly speaking, arguments are used to convey information to the
4745 &SCons; program about how it should behave;
4746 variables are used to convey information to the build
4747 (although &SCons; does not enforce any such constraint).
4750 <para>To obtain an object for manipulating variables,
4751 call the &Variables; factory function:</para>
4754 <varlistentry id="v-Variables">
4755 <term><function>Variables</function>([<parameter>files, [args]]</parameter>)</term>
4757 <para>If <parameter>files</parameter> is a filename or list of filenames,
4758 they are considered to be &Python; scripts which will
4759 be executed to set variables when the
4760 <link linkend='v-Update'><function>Update</function></link>
4762 this allows the use of &Python; syntax in the assignments.
4763 A file can be the result of an earlier call to the
4764 <link linkend='v-Save'>&Save;</link> method.
4765 If <parameter>files</parameter> is not specified,
4767 <parameter>files</parameter>
4769 <constant>None</constant>,
4770 then no files will be read.
4771 Supplying <constant>None</constant> is required
4772 if there are no files but you want to specify
4773 <parameter>args</parameter> as a positional argument;
4774 this can be omitted if using the keyword argument style.
4775 If any of <parameter>files</parameter> is missing,
4776 it is silently skipped.
4780 Either of the following example file
4781 contents could be used to set an alternative C compiler:</para>
4783 <programlisting language="python">
4785 CC = os.environ.get('CC')
4789 <parameter>args</parameter>
4790 is specified, it must be a dictionary.
4791 The key-value pairs from <parameter>args</parameter>
4792 will be added to those obtained from
4793 <parameter>files</parameter>, if any.
4794 Keys from <parameter>args</parameter>
4795 take precedence over same-named keys from <parameter>files</parameter>.
4796 If omitted, the default is the
4797 <link linkend="v-ARGUMENTS">&ARGUMENTS;</link>
4798 dictionary that holds build variables
4799 specified on the command line.
4800 Using &ARGUMENTS; allows you to indicate that if a setting appears
4801 on both the command line and in the file(s),
4802 the command line setting is preferred.
4803 However, any dictionary can be passed.
4806 <programlisting language="python">
4807 vars = Variables('custom.py')
4808 vars = Variables('overrides.py', ARGUMENTS)
4809 vars = Variables(None, {FOO:'expansion', BAR:7})
4810 vars = Variables(args={FOO:'expansion', BAR:7})
4814 Calling &Variables; with no arguments is equivalent to:
4816 <programlisting language="python">
4817 vars = Variables(files=None, args=ARGUMENTS)
4825 A &Variables; object serves as a container for
4826 descriptions of variables,
4827 which are added by calling methods of the object.
4828 Each variable consists of a name (which will
4829 become a &consvar;), aliases for the name,
4830 a help message, a default value,
4831 and functions to validate and convert values.
4832 Once the object is asked to process variables,
4833 it matches up data from the input
4834 sources it was given with the definitions,
4835 and generates key-value pairs which are added
4836 to the specified &consenv;,
4837 except that if any variable was described
4838 to have a default of <literal>None</literal>,
4839 it is <emphasis>not</emphasis> added to
4840 the construction environment unless it
4841 appears in the input sources.
4842 Otherwise, a variable not in the
4843 input sources is added using its default value.
4847 Note that since the variables are eventually added as &consvars;,
4848 you should choose variable names which do not unintentionally change
4849 pre-defined &consvars; that your project will make use of
4850 (see <xref linkend="construction_variables"/> for a reference),
4851 since variables obtained have values overridden, not merged.
4855 Also note there is currently no way to use the &Variables;
4856 mechanism to define a variable which the user is
4857 <emphasis>required</emphasis> to supply;
4858 if necessary this can be implemented by accessing
4859 <link linkend="v-ARGUMENTS">&ARGUMENTS;</link> directly,
4860 although that only applies to the command line,
4861 not to any stored-values files.
4864 <para>A Variables object has the following methods:</para>
4867 <varlistentry id="v-Add">
4868 <term><replaceable>vars</replaceable>.<function>Add</function>(<parameter>key, [help, default, validator, converter, subst]</parameter>)</term>
4870 <para>Add a customizable &consvar; to the &Variables; object.
4871 <parameter>key</parameter>
4872 is either the name of the variable,
4873 or a sequence of strings, in which case
4874 the first item in the sequence is taken as the variable name,
4875 and any remaining values are considered aliases for the variable.
4876 <parameter>key</parameter> is mandatory,
4877 there is no default.
4878 <parameter>help</parameter>
4879 is the help text for the variable
4880 (defaults to an empty string).
4881 <parameter>default</parameter>
4882 is the default value of the variable
4883 (defaults to <constant>None</constant>).
4887 If the optional <parameter>validator</parameter> argument is supplied,
4888 it is a callback function to validate the value of the variable
4889 when the variables are processed
4890 (that is, when the <link linkend='v-Update'>&Update;</link>
4892 A validator function must accept three arguments:
4893 <parameter>key</parameter>,
4894 <parameter>value</parameter>
4895 and <parameter>env</parameter>,
4896 and should raise an exception (with a helpful error message)
4897 if <parameter>value</parameter> is invalid.
4898 No return value is expected from the validator.
4902 If the optional <parameter>converter</parameter> argument is supplied,
4903 it is a callback function to convert the value into
4904 one suitable for adding to the &consenv;.
4905 A converter function must accept the
4906 <parameter>value</parameter> argument,
4907 and may declare <parameter>env</parameter>
4908 as a second argument if it needs access to the
4909 &consenv; while validating - the function will be called appropriately.
4910 The converter is called before the validator;
4911 it must return a value, which is then passed to the
4912 <parameter>validator</parameter> (if any) for checking.
4913 In general, the converter should not fail,
4914 leaving validation checks to the validator,
4915 although if an operation is impossible to complete
4916 or there is no separate validator
4917 it can raise a <exceptionname>ValueError</exceptionname>.
4921 Substitution will be performed on the variable value
4922 before the converter and validator are called,
4923 unless the optional <parameter>subst</parameter> parameter
4924 is false (default <literal>True</literal>).
4925 Suppressing substitution may be useful if the variable value
4926 looks like a &consvar; reference (e.g. <literal>$VAR</literal>)
4927 and the validator and/or converter should see it unexpanded.
4931 As a special case, if <parameter>key</parameter>
4932 is a sequence and is the <emphasis>only</emphasis>
4933 argument to &Add;, it is unpacked into the five parameters
4934 <parameter>key</parameter>,
4935 <parameter>help</parameter>,
4936 <parameter>default</parameter>,
4937 <parameter>validator</parameter> and
4938 <parameter>converter</parameter>,
4939 with any missing members from the right filled in with
4940 the respective default values.
4942 to consume a tuple emitted by the convenience functions
4943 <link linkend='v-BoolVariable'>&BoolVariable;</link>,
4944 <link linkend='v-EnumVariable'>&EnumVariable;</link>,
4945 <link linkend='v-ListVariable'>&ListVariable;</link>,
4946 <link linkend='v-PackageVariable'>&PackageVariable;</link>
4948 <link linkend='v-PathVariable'>&PathVariable;</link>.
4951 <para>Examples:</para>
4953 <programlisting language="python">
4954 vars.Add('CC', help='The C compiler')
4956 def valid_color(key, val, env):
4957 if not val in ['red', 'blue', 'yellow']:
4958 raise Exception("Invalid color value '%s'" % val)
4960 vars.Add('COLOR', validator=valid_color)
4964 <emphasis>Changed in version 4.8.0:</emphasis>
4965 added the <parameter>subst</parameter> parameter.
4970 <varlistentry id="v-AddVariables">
4971 <term><replaceable>vars</replaceable>.<function>AddVariables</function>(<parameter>args</parameter>)</term>
4973 <para>A convenience method that adds
4974 one or more customizable &consvars;
4975 to a &Variables; object in one call;
4976 equivalent to calling
4977 <link linkend='v-Add'><function>Add</function></link>
4979 Each <parameter>args</parameter> member
4980 must be a tuple that contains the arguments
4981 for an individual call to the &Add; method
4982 using the "special case" form;
4983 the other calling styles (individual positional
4984 arguments and/or keyword arguments) are not supported.
4987 <programlisting language="python">
4990 ("CC", "The C compiler"),
4991 ("VALIDATE", "An option for testing validation", "notset", validator, None),
4998 <varlistentry id="v-Update">
4999 <term><replaceable>vars</replaceable>.<function>Update</function>(<parameter>env, [args]</parameter>)</term>
5001 <para>Process the input sources recorded
5002 when the &Variables; object was initialized
5004 <parameter>env</parameter>
5005 with the customized &consvars;.
5006 The names of any variables in the input sources that are not
5007 configured in the &Variables; object
5008 are recorded and may be retrieved using the
5009 <link linkend='v-UnknownVariables'>&UnknownVariables;</link>
5014 <parameter>args</parameter>
5015 argument is provided, it is a dictionary of variables
5016 to use in place of the one saved when
5017 <link linkend='v-Variables'>&Variables;</link>
5021 <para>Normally, &Update; is not called directly,
5022 but rather invoked indirectly by passing the &Variables; object to
5023 the &f-link-Environment; function:</para>
5025 <programlisting language="python">
5026 env = Environment(..., variables=vars)
5032 <varlistentry id="v-UnknownVariables">
5033 <term><replaceable>vars</replaceable>.<function>UnknownVariables</function>()</term>
5035 <para>Returns a dictionary containing any
5036 variables that were specified in the
5037 <parameter>files</parameter> and/or
5038 <parameter>args</parameter> parameters
5039 when <link linkend='v-Variables'>&Variables;</link>
5040 was called, but the object was not actually configured for.
5041 This information is not available until the
5042 <link linkend='v-Update'><function>Update</function></link>
5046 <programlisting language="python">
5047 env = Environment(variables=vars)
5048 for key, value in vars.UnknownVariables():
5049 print("unknown variable: %s=%s" % (key, value))
5055 <varlistentry id="v-Save">
5056 <term><replaceable>vars</replaceable>.<function>Save</function>(<parameter>filename, env</parameter>)</term>
5058 <para>Saves the currently set variables into a script file named
5059 by <parameter>filename</parameter>.
5060 This provides a way to cache particular variable settings for reuse.
5061 Only variables that are set to non-default values are saved.
5062 You can load these saved variables on a subsequent run
5063 by passing <parameter>filename</parameter> to the
5064 <link linkend='v-Variables'>&Variables;</link> function,
5068 <programlisting language="python">
5070 vars = Variables(['variables.cache', 'custom.py'])
5073 vars.Save('variables.cache', env)
5079 <varlistentry id="v-GenerateHelpText">
5080 <term><replaceable>vars</replaceable>.<function>GenerateHelpText</function>(<parameter>env, [sort]</parameter>)</term>
5083 Return a formatted string with the help text collected
5084 from all the variables configured in this &Variables; object.
5085 This string is suitable for passing in to the &f-link-Help; function.
5086 The generated string include an indication of the
5087 actual value in the environment given by <parameter>env</parameter>.
5092 <parameter>sort</parameter> parameter is set to
5093 a callable value, it is used as a comparison function to
5094 determine how to sort the added variables.
5095 This function must accept two arguments, compare them,
5096 and return a negative integer if the first is
5097 less-than the second, zero if equal, or a positive integer
5099 If <parameter>sort</parameter> is not callable,
5100 but is set to <constant>True</constant>,
5101 an alphabetical sort is performed.
5102 The default is <constant>False</constant> (unsorted).
5105 <programlisting language="python">
5106 Help(vars.GenerateHelpText(env))
5109 return (a > b) - (a < b)
5111 Help(vars.GenerateHelpText(env, sort=cmp))
5117 <varlistentry id="v-FormatVariableHelpText">
5118 <term><replaceable>vars</replaceable>.<function>FormatVariableHelpText</function>(<parameter>env, opt, help, default, actual</parameter>)</term>
5120 <para>Returns a formatted string
5121 containing the printable help text
5122 for the single option <parameter>opt</parameter>.
5123 It is normally not called directly,
5124 but is called by the &GenerateHelpText;
5125 method to create the returned help text.
5126 It may be overridden with your own
5127 function that takes the arguments specified above
5128 and returns a string of help text formatted to your liking.
5129 Note that &GenerateHelpText;
5130 will not put any blank lines or extra
5131 characters in between the entries,
5132 so you must add those characters to the returned
5133 string if you want the entries separated.</para>
5135 <programlisting language="python">
5136 def my_format(env, opt, help, default, actual):
5137 fmt = "\n%s: default=%s actual=%s (%s)\n"
5138 return fmt % (opt, default, actual, help)
5140 vars.FormatVariableHelpText = my_format
5148 &SCons; provides five pre-defined variable types,
5149 accessible through factory functions that generate
5150 a tuple appropriate for directly passing to the
5151 <link linkend='v-Add'><function>Add</function></link>
5152 <link linkend='v-AddVariables'><function>AddVariables</function></link>
5157 <varlistentry id="v-BoolVariable">
5158 <term><function>BoolVariable</function>(<parameter>key, help, default</parameter>)</term>
5161 Set up a Boolean variable named <parameter>key</parameter>.
5162 The variable will have a default value of
5163 <parameter>default</parameter>,
5164 and <parameter>help</parameter>
5165 will form the descriptive part of the help text.
5166 The variable will interpret the command-line values
5167 <userinput>y</userinput>,
5168 <userinput>yes</userinput>,
5169 <userinput>t</userinput>,
5170 <userinput>true</userinput>,
5171 <userinput>1</userinput>,
5172 <userinput>on</userinput>
5174 <userinput>all</userinput>
5176 and the command-line values
5177 <userinput>n</userinput>,
5178 <userinput>no</userinput>,
5179 <userinput>f</userinput>,
5180 <userinput>false</userinput>,
5181 <userinput>0</userinput>,
5182 <userinput>off</userinput>
5184 <userinput>none</userinput>
5189 <varlistentry id="v-EnumVariable">
5190 <term><function>EnumVariable</function>(<parameter>key, help, default, allowed_values, [map, ignorecase]</parameter>)</term>
5193 Set up a variable named <parameter>key</parameter>
5194 whose value may only be from
5195 a specified list ("enumeration") of values.
5196 The variable will have a default value of
5197 <parameter>default</parameter>
5198 and <parameter>help</parameter>
5199 will form the descriptive part of the help text.
5200 Any value that is not in
5201 <parameter>allowed_values</parameter>
5202 will raise an error,
5203 except that the optional
5204 <parameter>map</parameter>
5205 argument is a dictionary
5206 that can be used to map additional names into
5207 a particular name in the
5208 <parameter>allowed_values</parameter> list.
5209 If the value of optional
5210 <parameter>ignore_case</parameter>
5212 <literal>0</literal>
5214 then the values are case-sensitive.
5216 <parameter>ignore_case</parameter>
5218 <literal>1</literal>,
5219 then values will be matched
5222 <parameter>ignore_case</parameter>
5224 <literal>2</literal>,
5225 then values will be matched
5227 and all input values will be
5228 converted to lower case.</para>
5232 <varlistentry id="v-ListVariable">
5233 <term><function>ListVariable</function>(<parameter>key, help, default, names, [map, validator]</parameter>)</term>
5236 Set up a variable named <parameter>key</parameter>
5237 whose value may be one or more
5238 from a specified list of values.
5239 The variable will have a default value of
5240 <parameter>default</parameter>,
5241 and <parameter>help</parameter>
5242 will form the descriptive part of the help text.
5243 Any value that is not in
5244 <parameter>names</parameter> or the special values
5245 <userinput>all</userinput> or
5246 <userinput>none</userinput>
5247 will raise an error.
5248 Use a comma separator to specify multiple values.
5249 <parameter>default</parameter> may be specified
5250 either as a string of comma-separated values,
5251 or as a &Python; list of values.
5255 <parameter>map</parameter>
5256 argument is a dictionary
5257 that can be used to convert
5258 input values into specific legal values
5260 <parameter>names</parameter>
5262 (Note that the additional values accepted through
5263 the use of a <parameter>map</parameter> are not
5264 reflected in the generated help message). </para>
5266 The optional <parameter>validator</parameter> argument
5267 can be used to specify a custom validator callback function,
5268 as described for <link linkend='v-Add'><function>Add</function></link>.
5269 The default is to use an internal validator routine.
5271 <para><emphasis>New in 4.8.0: <parameter>validator</parameter>.
5276 <varlistentry id="v-PackageVariable">
5277 <term><function>PackageVariable</function>(<parameter>key, help, default</parameter>)</term>
5280 Set up a variable named <parameter>key</parameter>
5281 to help control a build component,
5282 such as a software package.
5283 The variable can be specified to disable, enable,
5284 or enable with a custom path.
5285 The resulting &consvar; will have a value of
5286 <literal>True</literal>, <literal>False</literal>, or a path string.
5287 Interpretation of this value is up to the consumer,
5288 but a path string must refer to an existing filesystem entry
5289 or the <function>PackageVariable</function> validator
5290 will raise an exception.
5294 Any of the (case-insensitive) strings
5295 <userinput>1</userinput>,
5296 <userinput>yes</userinput>,
5297 <userinput>true</userinput>,
5298 <userinput>on</userinput>,
5299 <userinput>enable</userinput>
5301 <userinput>search</userinput>
5303 to indicate the package is "enabled",
5304 and the (case-insensitive) strings
5305 <userinput>0</userinput>,
5306 <userinput>no</userinput>,
5307 <userinput>false</userinput>,
5308 <userinput>off</userinput>
5310 <userinput>disable</userinput>
5311 to indicate the package is "disabled".
5315 The <parameter>default</parameter> parameter
5316 can be either a path string or one of the enabling or disabling strings.
5317 <parameter>default</parameter> is produced if the variable is not specified,
5318 or if it is specified with one of the enabling strings,
5319 except that if <parameter>default</parameter> is one
5320 of the enabling strings, the boolean literal <literal>True</literal>
5321 is produced instead of the string.
5322 The <parameter>help</parameter> parameter
5323 specifies the descriptive part of the help text.
5328 <varlistentry id="v-PathVariable">
5329 <term><function>PathVariable</function>(<parameter>key, help, default, [validator]</parameter>)</term>
5332 Set up a variable named <parameter>key</parameter> to hold a path string.
5333 The variable will have a default value of
5334 <parameter>default</parameter>,
5335 and the <parameter>help</parameter> parameter
5336 will be used as the descriptive part of the help text.
5341 <parameter>validator</parameter> parameter
5342 describes a callback function which will be called to
5343 verify that the specified path is acceptable.
5345 following ready-made validators:</para>
5347 <variablelist> <!-- nested list -->
5349 <term><literal>PathVariable</literal>.<function>PathExists</function></term>
5351 <para>Verify that the specified path exists
5352 (this the default behavior if no
5353 <parameter>validator</parameter> is supplied).</para>
5358 <term><literal>PathVariable</literal>.<function>PathIsFile</function></term>
5360 <para>Verify that the specified path exists and is a regular file.</para>
5365 <term><literal>PathVariable</literal>.<function>PathIsDir</function></term>
5367 <para>Verify that the specified path exists and is a directory.</para>
5372 <term><literal>PathVariable</literal>.<function>PathIsDirCreate</function></term>
5374 <para>Verify that the specified path exists and is a directory;
5375 if it does not exist, create the directory.</para>
5380 <term><literal>PathVariable</literal>.<function>PathAccept</function></term>
5382 <para>Accept the specific path name argument without validation,
5383 suitable for when you want your users
5384 to be able to specify a directory path that will be
5385 created as part of the build process, for example.</para>
5388 </variablelist> <!-- end nested list -->
5391 You may supply your own
5392 <emphasis>validator</emphasis>
5394 which must accept three arguments:
5395 <parameter>key</parameter>,
5396 the name of the variable to be set;
5397 <parameter>val</parameter>,
5398 the specified value being checked;
5400 <parameter>env</parameter>,
5402 and should raise an exception
5403 if the specified value is not acceptable.</para>
5407 <para>These functions make it
5408 convenient to create a number
5409 of variables with consistent behavior
5410 in a single call to the
5411 <link linkend='v-AddVariables'><function>AddVariables</function></link>
5415 <programlisting language="python">
5419 help="compilation with -Wall and similar",
5424 help="debug output and symbols",
5426 allowed_values=("yes", "no", "full"),
5428 ignorecase=0, # case-sensitive
5432 help="libraries to build as shared libraries",
5438 help="use X11 installed here (yes = search some places)",
5443 help="where the root of Qt is installed",
5447 help="where the foo library is installed",
5449 validator=PathVariable.PathIsDir,
5456 <refsect2 id='node_objects'>
5457 <title>Node Objects</title>
5460 &SCons; represents objects that are the sources or targets of
5461 build operations as <firstterm>Nodes</firstterm>,
5462 which are internal data structures.
5463 There are a number of user-visible types of nodes:
5464 File Nodes, Directory Nodes, Value Nodes and Alias Nodes.
5465 Some of the node types have public attributes and methods,
5466 described below. Each of the node types has a global function
5467 and a matching environment method to create instances:
5468 &f-link-File;, &f-link-Dir;, &f-link-Value; and &f-link-Alias;.
5471 <refsect3 id='file_and_directory_nodes'>
5472 <title>Filesystem Nodes</title>
5475 The &f-link-File; and &f-link-Dir;
5476 functions/methods return
5477 File Nodes and Directory Nodes, respectively.
5478 Such <firstterm>Filesystem Nodes</firstterm>
5479 represent build components that correspond to an entry
5480 in the computer's filesystem,
5481 whether or not such an entry exists at the time the Node is created.
5482 You do not usually need to explicitly create filesystem Nodes,
5483 since when you supply a string as a target or source of a Builder,
5484 &SCons; will create the Nodes as needed to populate the
5486 Builders return the target Node(s) in the form of a list,
5487 which you can then make use of.
5488 However, since filesystem Nodes have some useful
5489 public attributes and methods
5490 that you can use in &SConscript; files,
5491 it is sometimes appropriate to create them manually,
5492 outside the regular context of a Builder call.
5495 The following attributes provide information about a Node:
5500 <term><replaceable>node</replaceable>.<varname>path</varname></term>
5502 <para>The build path
5503 of the given file or directory.
5504 This path is relative to the project top directory.
5505 The build path is the same as the source path if
5506 <emphasis>variant_dir</emphasis>
5507 is not being used.</para>
5512 <term><replaceable>node</replaceable>.<varname>abspath</varname></term>
5514 <para>The absolute build path of the given file or directory.</para>
5519 <term><replaceable>node</replaceable>.<varname>relpath</varname></term>
5521 <para>The build path of the given file or directory relative to
5522 the project top directory.</para>
5527 <term><replaceable>node</replaceable>.<function>srcnode</function>()</term>
5530 <function>srcnode</function>
5532 returns another File or Directory Node
5533 representing the source path of the given
5534 File or Directory Node.
5540 <para>Examples:</para>
5542 <programlisting language="python">
5543 # Get the current build dir's path, relative to top.
5546 # Current dir's absolute path
5549 # Current dir's path relative to the project top directory
5552 # Next line is always '.', because it is the top dir's path relative to itself.
5555 # Source path of the given source file.
5556 File('foo.c').srcnode().path
5558 # Builders return lists of File objects:
5559 foo = env.Program('foo.c')
5560 print("foo will be built in", foo[0].path)
5564 Filesystem Node objects have methods to create new
5565 Filesystem Nodes relative to the original Node.
5566 There are also times when you may need to refer to an entry
5567 in a filesystem without knowing in advance whether it's a
5568 file or a directory.
5569 For those situations,
5570 there is an <function>Entry</function> method of filesystem node objects,
5571 which returns a Node that can represent either a file or a directory.
5575 If the original Node is a Directory Node,
5576 these methods will place the new Node within the directory
5577 the original Node represents:
5582 <term><replaceable>node</replaceable>.<function>Dir</function>(<parameter>name</parameter>)</term>
5584 <para>Returns a directory Node
5585 <parameter>name</parameter>
5586 which is a subdirectory of
5587 the directory represented by
5588 <replaceable>node</replaceable>.</para>
5593 <term><replaceable>node</replaceable>.<function>File</function>(<parameter>name</parameter>)</term>
5595 <para>Returns a file Node
5596 <parameter>name</parameter>
5597 in the directory represented by
5598 <replaceable>node</replaceable>.</para>
5603 <term><replaceable>node</replaceable>.<function>Entry</function>(<parameter>name</parameter>)</term>
5605 <para>Returns an unresolved Node
5606 <parameter>name</parameter>
5607 in the directory represented by
5608 <replaceable>node</replaceable>.</para>
5614 If the original Node is a File Node,
5615 these methods will place the new Node in the same
5616 directory as the one the original Node represents:
5621 <term><replaceable>node</replaceable>.<function>Dir</function>(<parameter>name</parameter>)</term>
5623 <para>Returns a Node
5624 <parameter>name</parameter>
5625 for a directory in the parent directory of
5626 the file represented by
5627 <replaceable>node</replaceable>.</para>
5632 <term><replaceable>node</replaceable>.<function>File</function>(<parameter>name</parameter>)</term>
5634 <para>Returns a Node
5635 <parameter>name</parameter>
5636 for a file in the parent directory of
5637 the file represented by
5638 <replaceable>node</replaceable>.</para>
5643 <term><replaceable>node</replaceable>.<function>Entry</function>(<parameter>name</parameter>)</term>
5645 <para>Returns an unresolved Node
5646 <parameter>name</parameter>
5647 in the parent directory of
5648 the file represented by
5649 <replaceable>node</replaceable>.</para>
5654 <para>For example:</para>
5656 <programlisting language="python">
5657 # Get a Node for a file within a directory
5658 incl = Dir('include')
5659 f = incl.File('header.h')
5661 # Get a Node for a subdirectory within a directory
5662 dist = Dir('project-3.2.1')
5663 src = dist.Dir('src')
5665 # Get a Node for a file in the same directory
5666 cfile = File('sample.c')
5667 hfile = cfile.File('sample.h')
5671 html = docs.Dir('html')
5672 index = html.File('index.html')
5673 css = index.File('app.css')
5677 <refsect3 id='value_and_alias_nodes'>
5678 <title>Value and Alias Nodes</title>
5681 &SCons; provides two other Node types to represent
5682 object that will not have an equivalent filesystem entry.
5683 Such Nodes always need to be created explicitly.
5687 The &f-link-Alias; method returns an Alias Node.
5688 Aliases are virtual objects - they will not themselves result
5689 in physical objects being constructed, but are entered into
5690 the dependency graph related to their sources.
5691 An alias is checked for up to date by checking if
5692 its sources are up-to-date.
5693 An alias is built by making sure its sources have been built,
5694 and if any building took place,
5695 applying any Actions that are defined as part of the alias.
5699 An &f-link-Alias; call creates an entry in the alias namespace,
5700 which is used for disambiguation.
5701 If an alias source has a string valued name,
5702 it will be resolved to a filesystem entry Node,
5703 unless it is found in the alias namespace,
5704 in which case it is resolved to the matching alias Node.
5705 As a result, the order of &f-Alias; calls is significant.
5706 An alias can refer to another alias, but only if the
5707 other alias has previously been created.
5711 The &f-link-Value; method returns a Value Node.
5712 Value nodes are often used for generated data that
5713 will not have any corresponding filesystem entry,
5714 but will be used to determine whether a build target is out-of-date,
5715 or to include as part of a build Action.
5716 Common examples are timestamp strings,
5717 revision control version strings
5718 and other run-time generated strings.
5722 A Value Node can also be the target of a builder.
5729 <refsect1 id='extending_scons'>
5730 <title>EXTENDING SCONS</title>
5733 &SCons; is designed to be extensible through provided facilities,
5734 so changing the code of &SCons; itself is only rarely needed
5735 to customize its behavior.
5736 A number of the main operations use callable objects
5737 which can be supplemented by writing your own.
5738 Builders, Scanners and Tools each use a kind of plugin system,
5739 allowing you to easily drop in new ones.
5740 Information about creating
5741 <link linkend='builder_objects'>Builder Objects</link> and
5742 <link linkend='scanner_objects'>Scanner Objects</link>
5743 appear in the following sections.
5744 The instructions &SCons; actually uses to
5745 construct things are called Actions,
5746 and it is easy to create Action Objects and hand them
5747 to the objects that need to know about those actions
5748 (besides Builders, see &f-link-AddPostAction;,
5749 &f-link-AddPreAction; and &f-link-Alias; for some examples
5750 of other places that take Actions).
5751 <link linkend='action_objects'>Action Objects</link>
5752 are also described below.
5753 Adding new Tool modules is described in
5754 <link linkend='tool_modules'>Tool Modules</link>
5757 <refsect2 id='builder_objects'>
5758 <title>Builder Objects</title>
5761 can be extended to build different types of targets
5762 by adding new Builder objects
5764 <emphasis>In general</emphasis>,
5765 you should only need to add a new Builder object
5766 when you want to build a new type of file or other external target.
5767 For output file types &scons; already knows about,
5768 you can usually modify the behavior of premade Builders
5769 such as &b-link-Program;, &b-link-Object; or &b-link-Library;
5770 by changing the &consvars; they use
5771 (&cv-link-CC;, &cv-link-LINK;, etc.).
5772 In this manner you can, for example, change the compiler to use,
5773 which is simpler and less error-prone than writing a new builder.
5774 The documentation for each Builder lists which
5778 <para>Builder objects are created
5782 Once created, a builder is added to an environment
5783 by entering it in the &cv-link-BUILDERS; dictionary
5784 in that environment (some of the examples
5785 in this section illustrate this).
5786 Doing so automatically triggers &SCons; to add a method
5787 with the name of the builder to the environment.
5793 function accepts the following keyword arguments:</para>
5797 <term><parameter>action</parameter></term>
5799 <para>The command used to build the target from the source.
5800 <parameter>action</parameter>
5801 may be a string representing a template command line to execute,
5802 a list of strings representing the command
5803 to execute with its arguments
5804 (suitable for enclosing white space in an argument),
5806 mapping source file name suffixes to
5807 any combination of command line strings
5808 (if the builder should accept multiple source file extensions),
5809 a &Python; function,
5811 (see <link linkend='action_objects'>Action Objects</link>)
5812 or a list of any of the above.</para>
5814 <para>An action function must accept three arguments:
5815 <parameter>source</parameter>,
5816 <parameter>target</parameter> and
5817 <parameter>env</parameter>.
5818 <parameter>source</parameter> is a list of source nodes;
5819 <parameter>target</parameter> is a list of target nodes;
5820 <parameter>env</parameter> is the &consenv; to use for context.
5824 The <parameter>action</parameter>
5825 and <parameter>generator</parameter>
5826 arguments must not both be used for the same Builder.</para>
5831 <term><parameter>prefix</parameter></term>
5833 <para>The prefix to prepend to the target file name.
5834 <parameter>prefix</parameter> may be
5835 a string, a function (or other callable) that takes
5836 two arguments (a &consenv; and a list of sources)
5837 and returns a prefix string,
5838 or a dictionary specifying a mapping from a specific source suffix
5839 (of the first source specified)
5840 to a corresponding target prefix string. For the dictionary form, both the source
5841 suffix (key) and target prefix (value) specifications may use environment variable
5842 substitution, and the target prefix
5843 may also be a callable object. The default target prefix
5844 may be indicated by a dictionary entry with a key of <constant>None</constant>.</para>
5846 <programlisting language="python">
5847 b = Builder("build_it < $SOURCE > $TARGET", prefix="file-")
5849 def gen_prefix(env, sources):
5850 return "file-" + env['PLATFORM'] + '-'
5852 b = Builder("build_it < $SOURCE > $TARGET", prefix=gen_prefix)
5855 "build_it < $SOURCE > $TARGET",
5856 suffix={None: "file-", "$SRC_SFX_A": gen_prefix},
5863 <term><parameter>suffix</parameter></term>
5865 <para>The suffix to append to the target file name.
5866 Specified in the same manner as for <parameter>prefix</parameter> above.
5867 If the suffix is a string, then
5869 prepends a <literal>'.'</literal> to the suffix if it's not already there.
5870 The string returned by the callable object or obtained from the
5871 dictionary is untouched, and you need to manually prepend a <literal>'.'</literal>
5872 if one is required.</para>
5874 <programlisting language="python">
5875 b = Builder("build_it < $SOURCE > $TARGET", suffix="-file")
5877 def gen_suffix(env, sources):
5878 return "." + env['PLATFORM'] + "-file"
5880 b = Builder("build_it < $SOURCE > $TARGET", suffix=gen_suffix)
5882 "build_it < $SOURCE > $TARGET",
5883 suffix={None: ".sfx1", "$SRC_SFX_A": gen_suffix},
5890 <term><parameter>ensure_suffix</parameter></term>
5892 <para>If set to a true value,
5893 ensures that targets will end in
5894 <parameter>suffix</parameter>.
5895 Thus, the suffix will also be added to any target strings
5896 that have a suffix that is not already <parameter>suffix</parameter>.
5897 The default behavior (also indicated by a false value)
5898 is to leave unchanged
5899 any target string that looks like it already has a suffix.</para>
5901 <programlisting language="python">
5902 b1 = Builder("build_it < $SOURCE > $TARGET", suffix=".out")
5904 "build_it < $SOURCE > $TARGET", suffix=".out", ensure_suffix=True
5907 env['BUILDERS']['B1'] = b1
5908 env['BUILDERS']['B2'] = b2
5910 # Builds "foo.txt" because ensure_suffix is not set.
5911 env.B1('foo.txt', 'foo.in')
5913 # Builds "bar.txt.out" because ensure_suffix is set.
5914 env.B2('bar.txt', 'bar.in')
5921 <term><parameter>src_suffix</parameter></term>
5923 <para>The expected source file name suffix.
5924 <parameter>src_suffix</parameter>
5925 may be a string or a list of strings.</para>
5929 <varlistentry id="target_scanner">
5930 <term><parameter>target_scanner</parameter></term>
5932 <para>A Scanner object that
5933 will be invoked to find
5934 implicit dependencies for this target file.
5935 Use only to specify Scanner objects that find
5936 implicit dependencies
5937 based on the target file
5939 <emphasis>not</emphasis>
5940 for implicit dependencies based on source files
5941 (use <xref linkend="source_scanner"/> for those).
5942 See <xref linkend="scanner_objects"/>
5943 for information about creating your own Scanner objects.</para>
5947 <varlistentry id="source_scanner">
5948 <term><parameter>source_scanner</parameter></term>
5950 <para>A Scanner object that
5952 find implicit dependencies in
5954 used to build this target file.
5955 Use to specify a scanner to
5957 <literal>#include</literal>
5958 lines in source files.
5960 <classname>DirScanner</classname>
5961 Scanner object may be used to
5962 indicate that this Builder
5963 should scan directory trees
5964 for on-disk changes to files
5967 does not know about from other Builder or function calls.
5968 See <xref linkend="scanner_objects"/>
5969 for information about creating your own Scanner objects.</para>
5974 <term><parameter>target_factory</parameter></term>
5976 <para>A factory function that the Builder will use
5977 to turn any targets specified as strings into SCons Nodes.
5979 SCons assumes that all targets are files
5980 (that is, the default factory is &File;).
5981 Other useful <parameter>target_factory</parameter>
5982 values include &Dir;
5983 for when a Builder creates a directory target,
5985 for when a Builder can create either a file
5986 or directory target.</para>
5988 <para>Example:</para>
5990 <programlisting language="python">
5991 def my_mkdir(target, source, env):
5992 # target[0] will be a Dir node for 'new_directory'
5994 MakeDirectoryBuilder = Builder(action=my_mkdir, target_factory=Dir)
5996 env.Append(BUILDERS={'MakeDirectory': MakeDirectoryBuilder})
5997 env.MakeDirectory('new_directory', [])
6000 <para>Note that the call to the <function>MakeDirectory</function> Builder
6001 needs to specify an empty source list
6002 to make the filename string represent the builder's target.
6003 &SCons; assumes a single positional argument to a builder
6004 is the source, and would try to deduce the target name from it,
6005 which, in the absence of an automatically-added prefix or suffix,
6006 would lead to a matching target and source name
6007 and a circular dependency.</para>
6012 <term><parameter>source_factory</parameter></term>
6014 <para>A factory function that the Builder will use
6015 to turn any sources specified as strings into SCons Nodes.
6017 SCons assumes that all source are files
6018 (that is, the default factory is &File;).
6019 Other useful <parameter>source_factory</parameter>
6020 values include &Dir;
6021 for when a Builder uses a directory as a source,
6023 for when a Builder can use files
6024 or directories (or both) as sources.</para>
6026 <para>Example:</para>
6028 <programlisting language="python">
6029 def collect(target, source, env):
6030 # target[0] will default to a File node for 'archive' (no target_factory)
6031 # source[0] will be a Dir node for 'directory_name'
6033 CollectBuilder = Builder(action=collect, source_factory=Dir)
6035 env.Append(BUILDERS={'Collect': CollectBuilder})
6036 env.Collect('archive', 'directory_name')
6041 <varlistentry id="emitter_function">
6042 <term><parameter>emitter</parameter></term>
6044 <para>A function or list of functions to manipulate the target and source
6045 lists before dependencies are established
6046 and the target(s) are actually built.
6047 <parameter>emitter</parameter>
6048 can also be a string containing a &consvar; to expand
6049 to an emitter function or list of functions,
6050 or a dictionary mapping source file suffixes
6051 to emitter functions.
6052 (Only the suffix of the first source file
6053 is used to select the actual emitter function
6054 from an emitter dictionary.)</para>
6056 <para>A function passed as <parameter>emitter</parameter>
6057 must accept three arguments:
6058 <parameter>source</parameter>,
6059 <parameter>target</parameter> and
6060 <parameter>env</parameter>.
6061 <parameter>source</parameter> is a list of source nodes,
6062 <parameter>target</parameter> is a list of target nodes,
6063 <parameter>env</parameter> is the &consenv; to use for context.
6066 <para>An emitter must return a tuple containing two lists,
6067 the list of targets to be built by this builder,
6068 and the list of sources for this builder.</para>
6070 <para>Example:</para>
6072 <programlisting language="python">
6073 def e(target, source, env):
6074 return target + ['foo.foo'], source + ['foo.src']
6076 # Simple association of an emitter function with a Builder.
6077 b = Builder("my_build < $TARGET > $SOURCE", emitter=e)
6079 def e2(target, source, env):
6080 return target + ['bar.foo'], source + ['bar.src']
6082 # Simple association of a list of emitter functions with a Builder.
6083 b = Builder("my_build < $TARGET > $SOURCE", emitter=[e, e2])
6085 # Calling an emitter function through a construction variable.
6086 env = Environment(MY_EMITTER=e)
6087 b = Builder("my_build < $TARGET > $SOURCE", emitter='$MY_EMITTER')
6089 # Calling a list of emitter functions through a construction variable.
6090 env = Environment(EMITTER_LIST=[e, e2])
6091 b = Builder("my_build < $TARGET > $SOURCE", emitter='$EMITTER_LIST')
6093 # Associating multiple emitters with different file
6094 # suffixes using a dictionary.
6095 def e_suf1(target, source, env):
6096 return target + ['another_target_file'], source
6098 def e_suf2(target, source, env):
6099 return target, source + ['another_source_file']
6102 action="my_build < $TARGET > $SOURCE",
6103 emitter={'.suf1': e_suf1, '.suf2': e_suf2}
6110 <term><parameter>multi</parameter></term>
6112 <para>Specifies whether this builder is allowed to be called multiple times for
6113 the same target file(s). The default is <constant>False</constant>,
6114 which means the builder
6115 can not be called multiple times for the same target file(s). Calling a
6116 builder multiple times for the same target simply adds additional source
6117 files to the target; it is not allowed to change the environment associated
6118 with the target, specify additional environment overrides,
6119 or associate a different
6120 builder with the target.</para>
6125 <term><parameter>env</parameter></term>
6127 <para>A &consenv; that can be used
6128 to fetch source code using this Builder.
6129 (Note that this environment is
6130 <emphasis>not</emphasis>
6131 used for normal builds of normal target files,
6132 which use the environment that was
6133 used to call the Builder for the target file.)</para>
6137 <varlistentry id="generator_function">
6138 <term><parameter>generator</parameter></term>
6140 <para>A function that returns a list of actions that will be executed to build
6141 the target(s) from the source(s).
6142 The returned action(s) may be
6143 an Action object, or anything that
6144 can be converted into an Action object
6145 (see the next section).</para>
6147 <para>A function passed as <parameter>generator</parameter>
6148 must accept four arguments:
6149 <parameter>source</parameter>,
6150 <parameter>target</parameter>,
6151 <parameter>env</parameter> and
6152 <parameter>for_signature</parameter>.
6153 <parameter>source</parameter> is a list of source nodes,
6154 <parameter>target</parameter> is a list of target nodes,
6155 <parameter>env</parameter> is the &consenv; to use for context,
6156 and <parameter>for_signature</parameter> is
6157 a Boolean value that tells the function
6158 if it is being called for the purpose of generating a &buildsig;
6159 (as opposed to actually executing the command).
6160 Since the &buildsig; is used for rebuild determination,
6161 the function should omit those elements
6162 that do not affect whether a rebuild should be triggered
6163 if <parameter>for_signature</parameter> is true.
6166 <para>Example:</para>
6168 <programlisting language="python">
6169 def g(source, target, env, for_signature):
6170 return [["gcc", "-c", "-o"] + target + source]
6172 b = Builder(generator=g)
6177 <emphasis>generator</emphasis>
6179 <emphasis>action</emphasis>
6180 arguments must not both be used for the same Builder.</para>
6185 <term><parameter>src_builder</parameter></term>
6187 <para>Specifies a builder to use when a source file name suffix does not match
6188 any of the suffixes of the builder. Using this argument produces a
6189 multi-stage builder.</para>
6194 <term><parameter>single_source</parameter></term>
6196 <para>Specifies that this builder expects exactly one source file per call. Giving
6197 more than one source file without target files results in implicitly calling
6198 the builder multiple times (once for each source given). Giving multiple
6199 source files together with target files results in a
6200 <exceptionname>UserError</exceptionname> exception.</para>
6205 <term><parameter>source_ext_match</parameter></term>
6207 <para>When the specified
6208 <parameter>action</parameter>
6209 argument is a dictionary,
6210 the default behavior when a builder is passed
6211 multiple source files is to make sure that the
6212 extensions of all the source files match.
6213 If it is legal for this builder to be
6214 called with a list of source files with different extensions,
6215 this check can be suppressed by setting
6216 <parameter>source_ext_match</parameter>
6218 <constant>False</constant>
6219 or some other non-true value.
6220 In this case, &scons;
6221 will use the suffix of the first specified
6222 source file to select the appropriate action from the
6223 <parameter>action</parameter>
6226 <para>In the following example,
6228 <parameter>source_ext_match</parameter>
6231 from exiting with an error
6232 due to the mismatched suffixes of
6233 <filename>foo.in</filename>
6235 <filename>foo.extra</filename>.</para>
6237 <programlisting language="python">
6238 b = Builder(action={'.in': 'build $SOURCES > $TARGET'}, source_ext_match=False)
6239 env = Environment(BUILDERS={'MyBuild': b})
6240 env.MyBuild('foo.out', ['foo.in', 'foo.extra'])
6247 <term><parameter>env</parameter></term>
6249 <para>A &consenv; that can be used
6250 to fetch source code using this Builder.
6251 (Note that this environment is
6252 <emphasis>not</emphasis>
6253 used for normal builds of normal target files,
6254 which use the environment that was
6255 used to call the Builder for the target file.)</para>
6257 <programlisting language="python">
6258 b = Builder(action="build < $SOURCE > $TARGET")
6259 env = Environment(BUILDERS={'MyBuild' : b})
6260 env.MyBuild('foo.out', 'foo.in', my_arg='xyzzy')
6267 <term><parameter>chdir</parameter></term>
6269 <para>A directory from which scons
6274 <parameter>chdir</parameter>
6276 a string or a directory Node,
6277 scons will change to the specified directory.
6279 <parameter>chdir</parameter>
6280 is not a string or Node
6282 then scons will change to the
6283 target file's directory.</para>
6285 <para>Note that scons will
6286 <emphasis>not</emphasis>
6287 automatically modify
6290 <envar>$TARGET</envar>
6292 <envar>$SOURCE</envar>
6293 when using the <parameter>chdir</parameter>
6294 keyword argument--that is,
6295 the expanded file names
6296 will still be relative to the project top directory,
6297 and consequently incorrect
6298 relative to the chdir directory.
6299 Builders created using <parameter>chdir</parameter> keyword argument,
6300 will need to use &consvar;
6302 <literal>${TARGET.file}</literal>
6304 <literal>${SOURCE.file}</literal>
6305 to use just the filename portion of the
6306 targets and source.</para>
6308 <programlisting language="python">
6309 b = Builder(action="build < ${SOURCE.file} > ${TARGET.file}", chdir=True)
6310 env = Environment(BUILDERS={'MyBuild' : b})
6311 env.MyBuild('sub/dir/foo.out', 'sub/dir/foo.in')
6316 &Python; only keeps one current directory
6317 location even if there are multiple threads.
6318 This means that use of the
6319 <parameter>chdir</parameter>
6322 <emphasis>not</emphasis>
6326 because individual worker threads spawned
6327 by SCons interfere with each other
6328 when they start changing directory.</para>
6334 <para>Any additional keyword arguments supplied
6335 when a Builder object is created
6336 (that is, when the &f-link-Builder; function is called)
6337 will be set in the executing construction
6338 environment when the Builder object is called.
6339 The canonical example here would be
6340 to set a &consvar; to
6341 the repository of a source code system.</para>
6343 <para>Any such keyword arguments supplied
6344 when a Builder object is called
6345 will only be associated with the target
6346 created by that particular &f-Builder; call
6347 (and any other files built as a
6348 result of the call).
6349 These extra keyword arguments are passed to the
6350 following functions:
6351 <link linkend='generator_function'>command generator functions</link>,
6352 <link linkend='miscellaneous_action_functions'>function Actions</link>,
6354 <link linkend='emitter_function'>emitter functions</link>.
6359 <refsect2 id='action_objects'>
6360 <title>Action Objects</title>
6364 factory function will turn its
6365 <parameter>action</parameter>
6366 keyword argument into an appropriate
6367 internal Action object, as will
6368 the &f-link-Command; function.
6369 You can also explicitly create Action objects
6370 for passing to &f-Builder;, or other functions
6371 that take actions as arguments,
6372 by calling the &f-link-Action; factory function.
6373 This may more efficient when multiple
6374 Builder objects need to do the same thing
6375 rather than letting each of those Builder objects
6376 create a separate Action object.
6377 It also allows more flexible configuration
6378 of an Action object. For example, to control
6379 the message printed when the action is taken
6380 you need to create the action object using &f-Action;.
6384 &Action; factory function
6385 returns an appropriate object for the action
6386 represented by the type of the
6387 <parameter>action</parameter> argument
6388 (the first positional parameter):</para>
6392 <para>If <parameter>action</parameter> is already an Action object,
6393 the object is simply returned.</para>
6397 <para>If <parameter>action</parameter> is a string,
6398 a command-line Action is returned.
6399 If such a string begins with <literal>@</literal>,
6400 the command line is not printed.
6401 If the string begins with hyphen
6402 (<literal>-</literal>),
6403 the exit status from the specified command
6404 is ignored, allowing execution to continue
6405 even if the command reports failure:</para>
6407 <programlisting language="python">
6408 Action('$CC -c -o $TARGET $SOURCES')
6410 # Doesn't print the line being executed.
6411 Action('@build $TARGET $SOURCES')
6413 # Ignores return value
6414 Action('-build $TARGET $SOURCES')
6419 <para>If <parameter>action</parameter> is a list,
6420 then a list of Action objects is returned.
6421 An Action object is created as necessary
6422 for each element in the list.
6423 If an element within
6424 the list is itself a list,
6425 the embedded list is taken as the
6426 command and arguments to be executed via
6428 This allows white space to be enclosed
6429 in an argument rather than taken as a separator by defining
6430 a command in a list within a list:</para>
6432 <programlisting language="python">
6433 Action([['cc', '-c', '-DWHITE SPACE', '-o', '$TARGET', '$SOURCES']])
6438 <para>If <parameter>action</parameter> is a callable object,
6439 a Function Action is returned.
6440 The callable must accept three keyword arguments:
6441 <parameter>target</parameter>,
6442 <parameter>source</parameter> and
6443 <parameter>env</parameter>.
6444 <parameter>target</parameter>
6445 is a Node object representing the target file,
6446 <parameter>source</parameter>
6447 is a Node object representing the source file and
6448 <parameter>env</parameter>
6449 is the &consenv; used for building the target file.
6454 <parameter>target</parameter>
6456 <parameter>source</parameter>
6457 arguments may be lists of Node objects if there is
6458 more than one target file or source file.
6459 The actual target and source file name(s) may
6460 be retrieved from their Node objects
6461 via the built-in &Python; <function>str</function> function:</para>
6463 <programlisting language="python">
6464 target_file_name = str(target)
6465 source_file_names = [str(x) for x in source]
6468 <para>The function should return
6469 <literal>0</literal>
6471 <constant>None</constant>
6472 to indicate a successful build of the target file(s).
6473 The function may raise an exception
6474 or return a non-zero exit status
6475 to indicate an unsuccessful build.</para>
6477 <programlisting language="python">
6478 def build_it(target=None, source=None, env=None):
6479 # build the target from the source
6482 a = Action(build_it)
6488 <parameter>action</parameter>
6489 is not one of the above types,
6490 no action object is generated and &f-Action;
6491 returns <constant>None</constant>.</para>
6495 <para>The environment method form &f-link-env-Action;
6496 will expand &consvars; in any argument strings,
6498 <parameter>action</parameter>,
6499 at the time it is called,
6500 using the construction variables in the &consenv; through which
6501 it was called. The global function form &f-link-Action;
6502 delays variable expansion until
6503 the Action object is actually used.
6506 <para>The optional second argument to &f-Action;
6507 is used to control the output
6508 which is printed when the Action is actually performed.
6509 If this parameter is omitted,
6510 or if the value is an empty string,
6511 a default output depending on the type of the action is used.
6512 For example, a command-line action will print the executed command.
6513 The following argument types are accepted:
6518 <para>If the second argument is a string,
6519 or if the <parameter>cmdstr</parameter> keyword argument is supplied,
6520 the string defines what is printed.
6521 Substitution is performed on the string before it is printed.
6522 The string typically contains substitutable variables, notably
6523 <literal>$TARGET(S)</literal> and <literal>$SOURCE(S)</literal>,
6524 or consists of just a single variable
6525 which is optionally defined somewhere else.
6526 &SCons; itself heavily uses the latter variant.</para>
6530 <para>If the second argument is a function,
6531 or if the <parameter>strfunction</parameter> keyword argument is supplied,
6532 the function will be called to obtain the string
6533 to be printed when the action is performed.
6535 must accept three keyword arguments:
6536 <parameter>target</parameter>,
6537 <parameter>source</parameter> and
6538 <parameter>env</parameter>,
6539 with the same interpretation as for a callable
6540 <parameter>action</parameter> argument above.
6541 The function is responsible for handling any required substitutions.
6546 <para>If the second argument is <constant>None</constant>,
6547 or if <literal>cmdstr=None</literal> is supplied,
6548 output is suppressed entirely.</para>
6553 The <parameter>cmdstr</parameter> and
6554 <parameter>strfunction</parameter>
6555 keyword arguments may not both be supplied in a single call to &f-Action;
6559 Printing of action strings is affected by the setting of
6560 &cv-link-PRINT_CMD_LINE_FUNC;.
6563 <para>Examples:</para>
6565 <programlisting language="python">
6566 def build_it(target, source, env):
6567 # build the target from the source
6570 def string_it(target, source, env):
6571 return "building '%s' from '%s'" % (target[0], source[0])
6573 # Use a positional argument.
6574 f = Action(build_it, string_it)
6575 s = Action(build_it, "building '$TARGET' from '$SOURCE'")
6577 # Alternatively, use a keyword argument.
6578 f = Action(build_it, strfunction=string_it)
6579 s = Action(build_it, cmdstr="building '$TARGET' from '$SOURCE'")
6581 # You can provide a configurable variable.
6582 l = Action(build_it, '$STRINGIT')
6585 <para>Any additional positional arguments, if present,
6586 may either be &consvars; or lists of &consvars;
6587 whose values will be included in the signature of the Action
6589 when deciding whether a target should be rebuilt because the action changed.
6590 Such variables may also be specified using the
6591 <parameter>varlist</parameter>
6593 both positional and keyword forms may be present, and will be combined.
6594 This is necessary whenever you want a target to be rebuilt
6595 when a specific &consvar; changes.
6596 This is not often needed for a string action,
6597 as the expanded variables will normally be part of the command line,
6598 but may be needed if a &Python; function action uses
6599 the value of a &consvar; when generating the command line.</para>
6601 <programlisting language="python">
6602 def build_it(target, source, env):
6603 # build the target from the 'XXX' construction variable
6604 with open(target[0], 'w') as f:
6608 # Use positional arguments.
6609 a = Action(build_it, '$STRINGIT', ['XXX'])
6611 # Alternatively, use a keyword argument.
6612 a = Action(build_it, varlist=['XXX'])
6618 can be passed the following
6619 optional keyword arguments
6620 to modify the Action object's behavior:</para>
6624 <term><parameter>chdir</parameter></term>
6627 If <parameter>chdir</parameter> is true
6628 (the default is <constant>False</constant>),
6629 &SCons; will change directories before
6630 executing the action.
6631 If the value of <parameter>chdir</parameter>
6632 is a string or a directory Node,
6633 &SCons; will change to the specified directory.
6634 Otherwise, if <parameter>chdir</parameter> evaluates true,
6635 &SCons; will change to the
6636 target file's directory.</para>
6638 <para>Note that &SCons; will
6639 <emphasis>not</emphasis>
6640 automatically modify
6643 &cv-TARGET; and &cv-SOURCE;
6644 when using the <parameter>chdir</parameter>
6645 parameter - that is,
6646 the expanded file names
6647 will still be relative to
6648 the project top directory,
6649 and consequently incorrect
6650 relative to the chdir directory.
6651 Builders created using <parameter>chdir</parameter> keyword argument,
6652 will need to use &consvar;
6654 <literal>${TARGET.file}</literal>
6656 <literal>${SOURCE.file}</literal>
6657 to use just the filename portion of the
6658 targets and source. Example:</para>
6660 <programlisting language="python">
6661 a = Action("build < ${SOURCE.file} > ${TARGET.file}", chdir=True)
6666 <term><parameter>exitstatfunc</parameter></term>
6669 If provided, must be a callable which accepts a single parameter,
6670 the exit status (or return value)
6671 from the specified action,
6672 and which returns an arbitrary
6674 This can be used, for example,
6675 to specify that an Action object's
6676 return value should be ignored
6677 under special conditions
6678 and SCons should, therefore,
6679 consider that the action always succeeds. Example:</para>
6681 <programlisting language="python">
6682 def always_succeed(s):
6683 # Always return 0, which indicates success.
6686 a = Action("build < ${SOURCE.file} > ${TARGET.file}", exitstatfunc=always_succeed)
6691 <term><parameter>batch_key</parameter></term>
6694 If provided, indicates that the Action can create multiple target files
6695 by processing multiple independent source files simultaneously.
6696 (The canonical example is "batch compilation"
6697 of multiple object files
6698 by passing multiple source files
6699 to a single invocation of a compiler
6702 <parameter>batch_key</parameter>
6703 argument evaluates True and is not a callable object,
6704 the configured Action object will cause
6706 to collect all targets built with the Action object
6707 and configured with the same &consenv;
6708 into single invocations of the Action object's
6709 command line or function.
6710 Command lines will typically want to use the
6711 &cv-CHANGED_SOURCES; &consvar;
6712 (and possibly &cv-CHANGED_TARGETS; as well)
6713 to only pass to the command line those sources that
6714 have actually changed since their targets were built.
6717 <programlisting language="python">
6718 a = Action('build $CHANGED_SOURCES', batch_key=True)
6722 <parameter>batch_key</parameter>
6723 argument may also be
6725 that returns a key that
6726 will be used to identify different
6727 "batches" of target files to be collected
6730 <parameter>batch_key</parameter>
6731 function must accept four parameters:
6732 <parameter>action</parameter>,
6733 <parameter>env</parameter>,
6734 <parameter>target</parameter> and
6735 <parameter>source</parameter>.
6736 The first parameter, <parameter>action</parameter>,
6737 is the active action object.
6738 The second parameter, <parameter>env</parameter>,
6739 is the &consenv; configured for the target.
6740 The <parameter>target</parameter> and <parameter>source</parameter>
6741 parameters are the lists of targets and sources
6742 for the configured action.
6745 <para>The returned key should typically
6746 be a tuple of values derived from the arguments,
6747 using any appropriate logic to decide
6748 how multiple invocations should be batched.
6750 <parameter>batch_key</parameter>
6751 function may decide to return
6752 the value of a specific &consvar;
6753 from <parameter>env</parameter>
6756 to batch-build targets
6757 with matching values of that &consvar;,
6758 or perhaps return the
6759 &Python; <function>id</function>()
6760 of the entire &consenv;,
6764 all targets configured with the same &consenv;.
6766 <constant>None</constant>
6768 the particular target should
6769 <emphasis>not</emphasis>
6770 be part of any batched build,
6771 but instead will be built
6772 by a separate invocation of action's
6773 command or function.
6776 <programlisting language="python">
6777 def batch_key(action, env, target, source):
6778 tdir = target[0].dir
6779 if tdir.name == 'special':
6780 # Don't batch-build any target
6781 # in the special/ subdirectory.
6783 return (id(action), id(env), tdir)
6784 a = Action('build $CHANGED_SOURCES', batch_key=batch_key)
6790 <refsect3 id='miscellaneous_action_functions'>
6791 <title>Miscellaneous Action Functions</title>
6794 supplies Action functions
6795 that arrange for various common
6796 file and directory manipulations
6798 These are similar in concept to "tasks" in the
6800 although the implementation is slightly different.
6801 These functions do not actually
6802 perform the specified action
6803 at the time the function is called,
6804 but rather are factory functions which
6805 return an Action object
6806 that can be executed at the
6807 appropriate time.</para>
6810 There are two natural ways
6813 are intended to be used.</para>
6817 to perform the action
6818 at the time the &SConscript;
6822 global function:</para>
6824 <programlisting language="python">
6825 Execute(Touch('file'))
6829 you can use these functions
6830 to supply Actions in a list
6831 for use by the &f-link-env-Command; method.
6832 This can allow you to
6833 perform more complicated
6834 sequences of file manipulation
6836 on platform-specific
6840 <programlisting language="python">
6841 env = Environment(TMPBUILD='/tmp/builddir')
6847 Copy('$TMPBUILD', '${SOURCE.dir}'),
6848 "cd $TMPBUILD && make",
6849 Delete('$TMPBUILD'),
6856 <term><function>Chmod</function>(<parameter>dest, mode</parameter>)</term>
6858 <para>Returns an Action object that
6859 changes the permissions on the specified
6860 <parameter>dest</parameter>
6861 file or directory to the specified
6862 <parameter>mode</parameter>
6863 which can be octal or string, similar to the POSIX
6864 <command>chmod</command> command.
6867 <programlisting language="python">
6868 Execute(Chmod('file', 0o755))
6873 [Copy('$TARGET', '$SOURCE'), Chmod('$TARGET', 0o755)],
6876 Execute(Chmod('file', "ugo+w"))
6881 [Copy('$TARGET', '$SOURCE'), Chmod('$TARGET', "ugo+w")],
6886 The behavior of <function>Chmod</function> is limited on Windows
6887 and on WebAssembly platforms,
6888 see the notes in the &Python; documentation for
6889 <ulink url="https://docs.python.org/3/library/os.html#os.chmod">
6890 os.chmod</ulink>, which is the underlying function.
6897 <term><function>Copy</function>(<parameter>dest, src</parameter>)</term>
6899 <para>Returns an Action object
6901 <parameter>src</parameter>
6902 source file or directory to the
6903 <parameter>dest</parameter>
6904 destination file or directory.
6905 If <parameter>src</parameter> is a list,
6906 <parameter>dest</parameter> must be a directory
6907 if it already exists.
6910 <programlisting language="python">
6911 Execute(Copy('foo.output', 'foo.input'))
6913 env.Command('bar.out', 'bar.in', Copy('$TARGET', '$SOURCE'))
6920 <term><function>Delete</function>(<parameter>entry, [must_exist]</parameter>)</term>
6922 <para>Returns an Action that
6923 deletes the specified
6924 <parameter>entry</parameter>,
6925 which may be a file or a directory tree.
6926 If a directory is specified,
6927 the entire directory tree
6930 <parameter>must_exist</parameter>
6931 flag is set to a true value,
6932 then a &Python; error will be raised
6933 if the specified entry does not exist;
6934 the default is false,
6935 that is, the Action will silently do nothing
6936 if the entry does not exist.
6939 <programlisting language="python">
6940 Execute(Delete('/tmp/buildroot'))
6946 Delete('${TARGET.dir}'),
6951 Execute(Delete('file_that_must_exist', must_exist=True))
6958 <term><function>Mkdir</function>(<parameter>name</parameter>)</term>
6960 <para>Returns an Action
6961 that creates the directory
6962 <parameter>name</parameter>
6963 and all needed intermediate directories.
6964 <parameter>name</parameter> may also be a list
6965 of directories to create.
6968 <programlisting language="python">
6969 Execute(Mkdir('/tmp/outputdir'))
6975 Mkdir('/tmp/builddir'),
6976 Copy('/tmp/builddir/foo.in', '$SOURCE'),
6977 "cd /tmp/builddir && make",
6978 Copy('$TARGET', '/tmp/builddir/foo.out'),
6987 <term><function>Move</function>(<parameter>dest, src</parameter>)</term>
6989 <para>Returns an Action
6990 that moves the specified
6991 <parameter>src</parameter>
6992 file or directory to
6994 <parameter>dest</parameter>
6998 <programlisting language="python">
6999 Execute(Move('file.destination', 'file.source'))
7004 action=[MyBuildAction, Move('$TARGET', 'file_created_by_MyBuildAction')],
7012 <term><function>Touch</function>(<parameter>file</parameter>)</term>
7014 <para>Returns an Action
7015 that updates the modification time
7017 <parameter>file</parameter>.
7020 <programlisting language="python">
7021 Execute(Touch('file_to_be_touched'))
7023 env.Command('marker', 'input_file', action=[MyBuildAction, Touch('$TARGET')])
7031 <refsect3 id='variable_substitution'>
7032 <title>Variable Substitution</title>
7035 Before executing a command, &scons;
7036 performs parameter expansion (<firstterm>substitution</firstterm>)
7037 on the string that makes up the action part of the builder.
7038 The format of a substitutable parameter is
7039 <literal>${<replaceable>expression</replaceable>}</literal>.
7040 If <replaceable>expression</replaceable> refers to a variable,
7041 the braces in <literal>${<replaceable>expression</replaceable>}</literal>
7042 can be omitted <emphasis>unless</emphasis> the variable name is
7043 immediately followed by a character that could either be interpreted
7044 as part of the name, or is &Python; syntax such as
7045 <emphasis role="bold">[</emphasis> (for indexing/slicing)
7046 or <emphasis role="bold">.</emphasis> (for attribute access -
7047 see <link linkend="special_attributes">Special Attributes</link> below).
7051 If <replaceable>expression</replaceable> refers to a &consvar;,
7052 it (including the <literal>$</literal> or <literal>${ }</literal>)
7053 is replaced with the value of that variable in the
7054 &consenv; at the time of execution.
7055 If <replaceable>expression</replaceable> looks like
7056 a variable name but is not defined in the &consenv;
7057 it is replaced with an empty string.
7058 If <replaceable>expression</replaceable> refers to one of the
7059 <link linkend="special_variables">Special Variables</link>
7060 (see below) the corresponding value of the variable is substituted.
7061 <replaceable>expression</replaceable> may also be
7062 a &Python; expression to be evaluated.
7063 See <link linkend='python_code_substitution'>Python Code Substitution</link>
7064 below for a description.
7067 <para>&SCons; uses the following rules when converting &consvars; into
7068 command line strings:</para>
7072 <para>If the value is a string it is interpreted as space delimited
7073 command line arguments.</para>
7077 <para>If the value is a list it is interpreted as a list of command
7078 line arguments. Each element of the list is converted to a string.</para>
7082 <para>Anything that is not a list or string is converted to a string and
7083 interpreted as a single command line argument.</para>
7087 <para>Newline characters (<literal>\n</literal>) delimit lines.
7088 The newline parsing is done after
7089 all other parsing, so it is not possible for arguments (e.g. file names) to
7090 contain embedded newline characters.</para>
7094 <para>For a literal <emphasis role="bold">$</emphasis>
7095 use <emphasis role="bold">$$</emphasis>.
7096 For example, <literal>$$FOO</literal> will be left in the
7097 final string as <literal>$FOO</literal>.</para>
7102 When a build action is executed, a hash of the command line is
7103 saved, together with other information about the target(s) built
7104 by the action, for future use in rebuild determination.
7105 This is called the <firstterm>&buildsig;</firstterm>
7106 (or <firstterm>&build_action; signature</firstterm>).
7108 <emphasis role="bold">$(</emphasis>
7109 <replaceable>subexpression</replaceable>
7110 <emphasis role="bold">$)</emphasis>
7111 may be used to indicate parts of a command line
7112 that may change without
7113 causing a rebuild--that is,
7114 which are not to be included when calculating the &buildsig;.
7116 <emphasis role="bold">$(</emphasis>
7117 up to and including the matching
7118 <emphasis role="bold">$)</emphasis>
7119 will be removed from the command line
7120 before it is added to the &buildsig;
7122 <emphasis role="bold">$(</emphasis>
7124 <emphasis role="bold">$)</emphasis>
7125 will be removed before the command is executed.
7126 For example, the command line string:</para>
7128 <programlisting language="python">
7129 "echo Last build occurred $( $TODAY $). > $TARGET"
7132 <para>would execute the command:</para>
7135 echo Last build occurred $TODAY. > $TARGET
7138 <para>but the &buildsig; added to any target files would be computed from:</para>
7141 echo Last build occurred . > $TARGET
7144 <para>While &consvars; are normally directly substituted,
7145 if a &consvar; has a value which
7146 is a callable &Python; object
7147 (a function, or a class with a <literal>__call__</literal> method),
7148 that object is called during substitution.
7149 The callable must accept four arguments:
7150 <parameter>target</parameter>,
7151 <parameter>source</parameter>,
7152 <parameter>env</parameter> and
7153 <parameter>for_signature</parameter>.
7154 <parameter>source</parameter> is a list of source nodes,
7155 <parameter>target</parameter> is a list of target nodes,
7156 <parameter>env</parameter> is the &consenv; to use for context,
7157 and <parameter>for_signature</parameter> is
7158 a boolean value that tells the callable
7159 if it is being called for the purpose of generating a &buildsig;.
7160 Since the &buildsig; is used for rebuild determination,
7161 variable elements that do not affect whether
7162 a rebuild should be triggered
7163 should be omitted from the returned string
7164 if <parameter>for_signature</parameter> is true.
7165 See <emphasis role="bold">$(</emphasis>
7166 and <emphasis role="bold">$)</emphasis> above
7171 &SCons; will insert whatever
7172 the callable returns
7173 into the expanded string:
7176 <programlisting language="python">
7177 def foo(target, source, env, for_signature):
7180 # Will expand $BAR to "bar baz"
7181 env = Environment(FOO=foo, BAR="$FOO baz")
7184 <para>As a reminder, substitution happens when
7185 <literal>$BAR</literal> is actually used in a
7186 builder action. The value of <literal>env['BAR']</literal>
7187 will be exactly as it was set: <literal>"$FOO baz"</literal>.
7188 This can make debugging tricky,
7189 as the substituted result is not available at the time
7190 the &SConscript; files are being interpreted and
7191 thus not available to the <systemitem>print</systemitem> function.
7192 However, you can perform the substitution on demand
7193 by calling the &f-link-env-subst; method for this purpose.
7196 <para>You can use this feature to pass arguments to a
7197 callable variable by creating a callable class
7198 that stores passed arguments in the instance,
7200 (in the <methodname>__call__</methodname> method)
7201 when the instance is called.
7202 Note that in this case,
7203 the entire variable expansion must
7204 be enclosed by curly braces
7205 so that the arguments will
7206 be associated with the
7207 instantiation of the class:</para>
7209 <programlisting language="python">
7211 def __init__(self, arg):
7214 def __call__(self, target, source, env, for_signature):
7215 return self.arg + " bar"
7217 # Will expand $BAR to "my argument bar baz"
7218 env=Environment(FOO=foo, BAR="${FOO('my argument')} baz")
7223 <refsect3 id='special_variables'>
7224 <title>Substitution: Special Variables</title>
7227 Besides regular &consvars;, scons provides the following
7228 <firstterm>Special Variables</firstterm> for use in expanding commands:</para>
7232 <term>&cv-CHANGED_SOURCES;</term>
7234 <para>The file names of all sources of the build command
7235 that have changed since the target was last built.</para>
7240 <term>&cv-CHANGED_TARGETS;</term>
7242 <para>The file names of all targets that would be built
7243 from sources that have changed since the target was last built.</para>
7248 <term>&cv-SOURCE;</term>
7250 <para>The file name of the source of the build command,
7251 or the file name of the first source
7252 if multiple sources are being built.</para>
7257 <term>&cv-SOURCES;</term>
7259 <para>The file names of the sources of the build command.</para>
7264 <term>&cv-TARGET;</term>
7266 <para>The file name of the target being built,
7267 or the file name of the first target
7268 if multiple targets are being built.</para>
7273 <term>&cv-TARGETS;</term>
7275 <para>The file names of all targets being built.</para>
7280 <term>&cv-UNCHANGED_SOURCES;</term>
7282 <para>The file names of all sources of the build command
7284 <emphasis>not</emphasis>
7285 changed since the target was last built.</para>
7290 <term>&cv-UNCHANGED_TARGETS;</term>
7292 <para>The file names of all targets that would be built
7293 from sources that have
7294 <emphasis>not</emphasis>
7295 changed since the target was last built.</para>
7301 These names are reserved
7302 and may not be assigned to or used as &consvars;.
7303 &SCons; computes them in a context-dependent manner
7304 and they and are not retrieved from a &consenv;.
7307 <para>For example, the following builder call:
7310 <programlisting language="python">
7311 env = Environment(CC='cc')
7314 source=['foo.c', 'bar.c'],
7315 action='@echo $CC -c -o $TARGET $SOURCES'
7319 <para>would produce the following output:</para>
7322 cc -c -o foo foo.c bar.c
7326 In the previous example, a string
7327 <code>${SOURCES[1]}</code>
7328 would expand to: <computeroutput>bar.c</computeroutput>.
7333 <refsect3 id='special_attributes'>
7334 <title>Substitution: Special Attributes
7336 <para>A variable name may
7338 modifiers appended within the enclosing curly braces
7339 to access properties of the interpolated string.
7340 These are known as <firstterm>special attributes</firstterm>.
7344 <member><parameter>base</parameter> -
7345 The base path of the file name,
7346 including the directory path
7347 but excluding any suffix.
7349 <member><parameter>dir</parameter> - The name of the directory in which the file exists.</member>
7350 <member><parameter>file</parameter> - The file name, minus any directory portion.</member>
7351 <member><parameter>filebase</parameter> - Like <parameter>file</parameter> but minus its suffix.</member>
7352 <member><parameter>suffix</parameter> - Just the file suffix.</member>
7353 <member><parameter>abspath</parameter> - The absolute path name of the file.</member>
7354 <member><parameter>relpath</parameter> - The path name of the file relative to the project top directory.</member>
7355 <member><parameter>posix</parameter> -
7356 The path with directories separated by forward slashes
7357 (<emphasis role="bold">/</emphasis>).
7358 Sometimes necessary on Windows systems
7359 when a path references a file on other (POSIX) systems.
7361 <member><parameter>windows</parameter> -
7362 The path with directories separated by backslashes
7363 (<emphasis role="bold"><literal>\\</literal></emphasis>).
7364 Sometimes necessary on POSIX-style systems
7365 when a path references a file on other (Windows) systems.
7366 <parameter>win32</parameter> is a (deprecated) synonym for
7367 <parameter>windows</parameter>.
7369 <member><parameter>srcpath</parameter> -
7370 The directory and file name to the source file linked to this file through
7372 If this file isn't linked,
7373 it just returns the directory and filename unchanged.
7375 <member><parameter>srcdir</parameter> -
7376 The directory containing the source file linked to this file through
7378 If this file isn't linked,
7379 it just returns the directory part of the filename.
7381 <member><parameter>rsrcpath</parameter> -
7382 The directory and file name to the source file linked to this file through
7384 If the file does not exist locally but exists in a Repository,
7385 the path in the Repository is returned.
7386 If this file isn't linked, it just returns the
7387 directory and filename unchanged.
7389 <member><parameter>rsrcdir</parameter> -
7390 The Repository directory containing the source file linked to this file through
7392 If this file isn't linked,
7393 it just returns the directory part of the filename.
7397 <para>For example, the specified target will
7398 expand as follows for the corresponding modifiers:</para>
7400 <literallayout class="monospaced">
7401 $TARGET => sub/dir/file.x
7402 ${TARGET.base} => sub/dir/file
7403 ${TARGET.dir} => sub/dir
7404 ${TARGET.file} => file.x
7405 ${TARGET.filebase} => file
7406 ${TARGET.suffix} => .x
7407 ${TARGET.abspath} => /top/dir/sub/dir/file.x
7408 ${TARGET.relpath} => sub/dir/file.x
7410 $TARGET => ../dir2/file.x
7411 ${TARGET.abspath} => /top/dir2/file.x
7412 ${TARGET.relpath} => ../dir2/file.x
7414 SConscript('src/SConscript', variant_dir='sub/dir')
7415 $SOURCE => sub/dir/file.x
7416 ${SOURCE.srcpath} => src/file.x
7417 ${SOURCE.srcdir} => src
7419 Repository('/usr/repository')
7420 $SOURCE => sub/dir/file.x
7421 ${SOURCE.rsrcpath} => /usr/repository/src/file.x
7422 ${SOURCE.rsrcdir} => /usr/repository/src
7426 Some modifiers can be combined, like
7427 <literal>${TARGET.srcpath.base)</literal>,
7428 <literal>${TARGET.file.suffix}</literal>, etc.
7433 <refsect3 id='python_code_substitution'>
7434 <title>Python Code Substitution</title>
7437 If a substitutable expression using the notation
7438 <literal>${<replaceable>expression</replaceable>}</literal>
7439 does not appear to match one of the other substitution patterns,
7440 it is evaluated as a &Python; expression.
7441 This uses &Python;'s <function>eval</function> function,
7442 with the <parameter>globals</parameter> parameter set to
7443 the current environment's set of &consvars;,
7444 and the result substituted in.
7445 So in the following case:</para>
7447 <programlisting language="python">
7449 'foo.out', 'foo.in', "echo ${COND==1 and 'FOO' or 'BAR'} > $TARGET"
7453 <para>the command executed will be either</para>
7456 echo FOO > foo.out
7462 echo BAR > foo.out
7465 <para>according to the current value of <literal>env['COND']</literal>
7466 when the command is executed.
7467 The evaluation takes place when the target is being
7468 built, not when the &SConscript; is being read. So if
7469 <literal>env['COND']</literal> is changed
7470 later in the &SConscript;, the final value will be used.</para>
7472 <para>Here's a more complete example. Note that all of
7473 <envar>COND</envar>,
7476 <envar>BAR</envar> are &consvars;,
7477 and their values are substituted into the final command.
7478 <envar>FOO</envar> is a list, so its elements are interpolated
7479 separated by spaces.</para>
7481 <programlisting language="python">
7484 env['FOO'] = ['foo1', 'foo2']
7485 env['BAR'] = 'barbar'
7487 'foo.out', 'foo.in', "echo ${COND==1 and FOO or BAR} > $TARGET"
7491 <para>will execute:</para>
7493 echo foo1 foo2 > foo.out
7497 In point of fact, &Python; expression evaluation is
7498 how the special attributes are substituted:
7499 they are simply attributes of the &Python; objects
7500 that represent &cv-TARGET;, &cv-SOURCES;, etc.,
7501 which &SCons; passes to <function>eval</function> which
7506 Use of the &Python; <function>eval</function> function
7507 is considered to have security implications, since,
7508 depending on input sources,
7509 arbitrary unchecked strings of code can be executed by the &Python; interpreter.
7510 Although &SCons; makes use of it in a somewhat restricted context,
7511 you should be aware of this issue when using the
7512 <literal>${python-expression-for-subst}</literal> form.
7517 <refsect2 id='scanner_objects'>
7518 <title>Scanner Objects</title>
7521 Scanner objects are used
7522 to scan specific file types for implicit dependencies,
7523 for example embedded preprocessor/compiler directives
7524 that cause other files to be included during processing.
7525 &SCons; has a number of pre-built Scanner objects,
7526 so it is usually only necessary to set up Scanners for new file types.
7527 You do this by calling the &f-link-Scanner; factory function.
7528 &f-Scanner; accepts the following arguments.
7529 Only <parameter>function</parameter> is required;
7530 the rest are optional:
7535 <term><parameter>function</parameter></term>
7538 A function which can process ("scan")
7539 a given Node (usually a file)
7540 and return a list of Nodes
7541 representing any implicit
7542 dependencies (usually files) which will be tracked
7544 The function must accept three required arguments,
7545 <parameter>node</parameter>,
7546 <parameter>env</parameter> and
7547 <parameter>path</parameter>,
7548 and an optional fourth,
7549 <parameter>arg</parameter>.
7550 <parameter>node</parameter> is
7551 the internal &SCons; node representing the file to scan,
7552 <parameter>env</parameter> is the &consenv; to use during
7553 the scan, and <parameter>path</parameter> is a tuple
7554 of directories that can be searched for files,
7555 as generated by the optional scanner
7556 <xref linkend="path_function"/>.
7557 If the <xref linkend="scanner-argument"/>
7558 parameter was supplied when the Scanner object was created,
7559 it is passed as the <parameter>arg</parameter> parameter
7560 to the scanner function when it is called.
7561 Since <parameter>argument</parameter> is optional,
7562 the scanner function <emphasis>may</emphasis> be
7563 called without an <parameter>arg</parameter> parameter.
7567 The scanner function can make use of
7568 <function>str</function>(<parameter>node</parameter>)
7569 to fetch the name of the file,
7570 <parameter>node</parameter>.<methodname>dir</methodname>
7571 to fetch the directory the file is in,
7572 <parameter>node</parameter>.<methodname>get_contents</methodname>()
7573 to fetch the contents of the file as bytes or
7574 <parameter>node</parameter>.<methodname>get_text_contents</methodname>()
7575 to fetch the contents of the file as text.
7579 The scanner function should account for any directories
7580 listed in the <parameter>path</parameter> parameter
7581 when determining the existence of possible dependencies.
7582 External tools such as the C/C++ preprocessor are given
7583 lists of directories to search for source file inclusion directives
7584 (e.g. <literal>#include "myheader.h"</literal>).
7585 That list is generated from the relevant path variable
7586 (e.g. &cv-link-CPPPATH; for C/C++). The Scanner can be
7587 directed to pass the same list on to the scanner function
7588 via the <parameter>path</parameter> parameter so it can
7589 search in the same places.
7590 The Scanner is enabled to pass this list via the
7591 <xref linkend="path_function"/> argument at Scanner creation time.
7595 Instead of a scanner function, you can supply a dictionary as the
7596 <parameter>function</parameter> parameter.
7597 The dictionary must map keys (such as file suffixes)
7598 to other Scanner objects.
7599 A Scanner created this way serves as a dispatcher:
7600 the Scanner's <xref linkend="skeys"/> parameter is
7601 automatically populated with the dictionary's keys,
7602 indicating that the Scanner handles Nodes which would be
7603 selected by those keys; the mapping is then used to pass
7604 the file on to a different Scanner that would not have been
7605 selected to handle that Node based on its
7606 own <parameter>skeys</parameter>.
7610 Note that the file to scan is
7611 <emphasis>not</emphasis>
7612 guaranteed to exist at the time the scanner is called -
7613 it could be a generated file which has not been generated yet -
7614 so the scanner function must be tolerant of that.
7618 While many scanner functions operate on source code files by
7619 looking for known patterns in the code, they can really
7620 do anything they need to.
7621 For example, the &b-link-Program; Builder is assigned a
7622 <xref linkend="target_scanner"/> which examines the
7623 list of libraries supplied for the build (&cv-link-LIBS;)
7624 and decides whether to add them as dependencies,
7625 it does not look <emphasis>inside</emphasis> the built binary.
7629 It is up to the scanner function to decide whether or not to
7630 generate an &SCons; dependency for candidates identified by scanning.
7631 Dependencies are a key part of &SCons; operation,
7632 enabling both rebuild determination and correct ordering of builds.
7633 It is particularly important that generated files which are
7634 dependencies are added into the Node graph,
7635 or use-before-create failures are likely.
7636 However, not everything may need to be tracked as a dependency.
7637 In some cases, implementation-provided header files change
7638 infrequently but are included very widely,
7639 so tracking them in the &SCons; node graph could become quite
7640 expensive for limited benefit -
7641 consider for example the C standard header file
7642 <filename>string.h</filename>.
7643 The scanner function is not passed any special information
7644 to help make this choice, so the decision-making encoded
7645 in the scanner function must be carefully considered.
7652 <term><parameter>name</parameter></term>
7654 <para>The name to use for the Scanner.
7655 This is mainly used to identify the Scanner internally.
7656 The default value is <literal>"NONE"</literal>.</para>
7660 <varlistentry id="scanner-argument">
7661 <term><parameter>argument</parameter></term>
7664 will be passed to the scanner function
7665 <parameter>function</parameter>
7666 and the path function
7667 <parameter>path_function</parameter>
7669 as the optional parameter each of those functions takes.
7674 <varlistentry id="skeys">
7675 <term><parameter>skeys</parameter></term>
7677 <para>Scanner key(s) indicating the file types
7678 this scanner is associated with.
7679 Used internally to select an appropriate scanner.
7680 In the usual case of scanning for file names,
7681 this argument will be a list of suffixes
7682 for the different file types that this
7683 Scanner knows how to scan.
7684 If <parameter>skeys</parameter> is a string,
7685 it will be expanded into a list by the current environment.
7690 <varlistentry id="path_function">
7691 <term><parameter>path_function</parameter></term>
7694 If specified, a function to generate paths to pass to
7695 the scanner function to search while generating dependencies.
7696 The function must take five arguments:
7698 a Node for the directory containing
7699 the &SConscript; file in which
7700 the first target was defined,
7701 a list of target nodes,
7702 a list of source nodes,
7703 and the value of <parameter>argument</parameter>
7704 if it was supplied when the Scanner was created
7705 (since <parameter>argument</parameter> is optional,
7706 the function may be called without this argument,
7707 the <parameter>path_function</parameter>
7708 should be prepared for this).
7709 Must return a tuple of directories
7710 that can be searched for files to be returned
7711 by this Scanner object.
7715 The &f-link-FindPathDirs;
7716 function can be called to return a ready-made
7717 <parameter>path_function</parameter>
7718 for a given &consvar; name,
7719 which is often easier than writing your own function from scratch.
7721 <userinput>path_function=FindPathDirs('CPPPATH')</userinput>
7722 means the scanner function will be called with the paths extracted
7723 from &cv-CPPPATH; in the &consenv; <parameter>env</parameter>,
7724 and passed as the <parameter>path</parameter> parameter
7725 to the scanner function.
7731 <term><parameter>node_class</parameter></term>
7733 <para>The class of Node that should be returned
7734 by this Scanner object.
7735 Any strings or other objects returned
7736 by the scanner function
7737 that are not of this class
7738 will be run through the function
7740 <parameter>node_factory</parameter> argument.
7741 A value of <constant>None</constant> can
7742 be supplied to indicate no conversion;
7743 the default is to return File nodes.
7749 <term><parameter>node_factory</parameter></term>
7751 <para>A &Python; function that will take a string
7753 and turn it into the appropriate class of Node
7754 to be returned by this Scanner object,
7755 as indicated by <parameter>node_class</parameter>.
7761 <term><parameter>scan_check</parameter></term>
7763 <para>A Python function that takes two arguments,
7764 a Node (file) and a &consenv;,
7765 and returns whether the
7766 Node should, in fact,
7767 be scanned for dependencies.
7768 This check can be used to eliminate unnecessary
7769 calls to the scanner function when,
7770 for example, the underlying file
7771 represented by a Node does not yet exist.</para>
7776 <term><parameter>recursive</parameter></term>
7779 Specifies whether this scanner should be re-invoked
7780 on the dependency files returned by the scanner.
7781 If omitted, the Node subsystem will
7782 only invoke the scanner on the file being scanned
7784 Recursion is needed when the files returned by the
7785 scanner may themselves contain further file dependencies,
7786 as in the case of preprocessor <literal>#include</literal> lines.
7787 A value that evaluates true enables recursion;
7788 <emphasis>recursive</emphasis>
7789 may be a callable function,
7790 in which case it will be called with a list of
7792 should return a list of Nodes
7793 that should be scanned recursively;
7794 this can be used to select a specific subset of
7795 Nodes for additional scanning.</para>
7801 Once created, a Scanner can be added to an environment
7802 by setting it in the &cv-link-SCANNERS; list,
7803 which automatically triggers &SCons; to also add it
7804 to the environment as a method.
7805 However, usually a scanner is not truly standalone, but needs to
7806 be plugged in to the existing selection mechanism for
7807 deciding how to scan source files based on filename extensions.
7808 For this, &SCons; has a global
7809 <classname>SourceFileScanner</classname>
7810 object that is used by
7811 the &b-link-Object;, &b-link-SharedObject; and &b-link-StaticObject;
7813 which scanner should be used.
7815 <methodname>SourceFileScanner.add_scanner()</methodname>
7816 method to add your own Scanner object
7820 that builds target programs or
7821 libraries from a list of
7822 source files of different types:</para>
7824 <programlisting language="python">
7825 def xyz_scan(node, env, path):
7826 contents = node.get_text_contents()
7827 # Scan the contents and return the included files.
7829 XYZScanner = Scanner(xyz_scan)
7831 SourceFileScanner.add_scanner('.xyz', XYZScanner)
7833 env.Program('my_prog', ['file1.c', 'file2.f', 'file3.xyz'])
7838 <refsect2 id='tool_modules'>
7839 <title>Tool Modules</title>
7842 Custom tools can be added to a project either by
7843 placing them in the <filename>site_tools</filename> subdirectory
7844 of a configured site directory,
7845 or in a location specified by the
7846 <parameter>toolpath</parameter> keyword argument to &f-link-Environment;.
7847 You have to arrange to call a tool to put it into effect,
7848 either as part of the list given to the <parameter>tools</parameter>
7849 keyword argument at &consenv; initialization,
7850 or by calling &f-link-env-Tool;.
7854 The <parameter>toolpath</parameter> parameter
7855 takes a list of path strings,
7856 and the <parameter>tools</parameter> parameter
7857 takes a list of tools, which are often strings:
7860 <programlisting language="python">
7861 env = Environment(tools=['default', 'foo'], toolpath=['tools'])
7865 This looks for a tool specification module <literal>foo</literal>
7866 in directory <filename>tools</filename> and in the standard locations,
7867 as well as using the ordinary default tools for the platform.
7871 When looking up tool specification modules,
7872 directories specified via <parameter>toolpath</parameter> are
7873 considered before the existing tool path
7874 (<filename>site_tools</filename> subdirectories
7875 of the default or specified site directories),
7876 which are in turn considered before built-in tools.
7878 a tool specification module <filename>gcc.py</filename> to the toolpath
7879 directory would override the built-in &t-link-gcc; tool.
7880 The <parameter>toolpath</parameter> is saved in the environment
7881 and will be used by subsequent calls to the &f-link-env-Tool; method,
7882 as well as by &f-link-env-Clone;.
7885 <programlisting language="python">
7886 base = Environment(toolpath=['custom_path'])
7887 derived = base.Clone(tools=['custom_tool'])
7888 derived.CustomBuilder()
7892 A tool specification module is a form of &Python; module,
7893 looked up internally using the &Python; import mechanism,
7894 so a tool can consist either
7895 of a single &Python; file taking the name of the tool
7896 (e.g. <filename>mytool.py</filename>) or a directory taking
7897 the name of the tool (e.g. <filename>mytool/</filename>)
7898 which contains at least an <filename>__init__.py</filename> file.
7899 A tool specification module has two required entry points:
7904 <term><function>generate</function>(<parameter>env, **kwargs</parameter>)</term>
7906 <para>Modify the &consenv; <parameter>env</parameter>
7907 to set up necessary &consvars;, Builders, Emitters, etc.,
7908 so the facilities represented by the tool can be executed.
7909 Take care not to overwrite &consvars; which may
7910 have been explicitly set by the user;
7911 retain and/or append instead. For example:
7913 <programlisting language="python">
7916 if 'MYTOOL' not in env:
7917 env['MYTOOL'] = env.Detect("mytool")
7918 flags = env.get('MYTOOLFLAGS', SCons.Util.CLVar())
7919 env.AppendUnique(MYTOOLFLAGS='--myarg')
7923 <para>The <function>generate</function> function
7924 may use any keyword arguments
7925 that the user supplies via <parameter>kwargs</parameter>
7926 to vary its initialization.</para>
7930 <term><function>exists</function>(<parameter>env</parameter>)</term>
7932 <para>Return a truthy value if the tool can
7933 be called in the context of <parameter>env</parameter>,
7934 else return a falsy value.
7935 Usually this means looking up one or more
7936 known programs using the <varname>PATH</varname> from the
7937 supplied <parameter>env</parameter>, but the tool can
7938 make the <emphasis>exists</emphasis> decision in any way it chooses.
7946 At the moment, user-added tools do not automatically have their
7947 <function>exists</function> function called.
7948 As a result, it is recommended that the <function>generate</function>
7949 function be defensively coded - that is, do not rely on any
7950 necessary existence checks already having been performed.
7951 This is expected to be a temporary limitation,
7952 and the <function>exists</function> function should still be provided.
7956 <para>An element of the <parameter>tools</parameter> list may also
7957 be a function or other callable object
7958 (including a Tool object returned by a previous call to
7959 &f-link-Tool;) in which case the &f-link-Environment; function
7960 will directly call that object
7961 to update the new &consenv;.
7962 No tool lookup is done in this case.
7965 <programlisting language="python">
7967 env['XYZZY'] = 'xyzzy'
7969 env = Environment(tools=[my_tool])
7972 <para>An element of the <parameter>tools</parameter> list
7973 may also be a two-element list or tuple of the form
7974 <literal>(toolname, kw_dict)</literal>.
7975 SCons searches for the tool specification module
7976 <parameter>toolname</parameter>
7978 and passes <parameter>kw_dict</parameter>,
7979 which must be a dictionary,
7980 as keyword arguments to the tool's
7981 <function>generate</function> function.
7982 The <function>generate</function>
7983 function can use those arguments to modify the tool's behavior
7984 by setting up the environment in different ways
7985 or otherwise changing its initialization.</para>
7987 <programlisting language="python">
7988 # in tools/my_tool.py:
7989 def generate(env, **kwargs):
7990 # Sets MY_TOOL to the value of keyword 'arg1' or '1' if not supplied
7991 env['MY_TOOL'] = kwargs.get('arg1', '1')
7998 tools=['default', ('my_tool', {'arg1': 'abc'})], toolpath=['tools']
8002 <para>The tool specification (<function>my_tool</function> in the example)
8004 &cv-link-PLATFORM; variable from
8005 the &consenv; it is passed to customize the tool for different platforms.
8008 <para>Tools can be "nested" - that is, they
8009 can be located within a subdirectory in the toolpath.
8010 A nested tool name uses a dot to represent a directory separator</para>
8012 <programlisting language="python">
8013 # namespaced builder
8014 env = Environment(ENV=os.environ.copy(), tools=['SubDir1.SubDir2.SomeTool'])
8015 env.SomeTool(targets, sources)
8018 # SCons\Tool\SubDir1\SubDir2\SomeTool.py
8019 # SCons\Tool\SubDir1\SubDir2\SomeTool\__init__.py
8020 # .\site_scons\site_tools\SubDir1\SubDir2\SomeTool.py
8021 # .\site_scons\site_tools\SubDir1\SubDir2\SomeTool\__init__.py
8027 <refsect1 id='systemspecific_behavior'>
8028 <title>SYSTEM-SPECIFIC BEHAVIOR</title>
8030 <para>&scons; and its configuration files are very portable,
8031 due largely to its implementation in &Python;.
8032 There are, however, a few portability
8033 issues waiting to trap the unwary.</para>
8035 <refsect2 id='c_file_suffix'>
8036 <title>.C File Suffix</title>
8038 <para>&scons; handles the upper-case
8039 <filename>.C</filename>
8040 file suffix differently,
8041 depending on the capabilities of
8042 the underlying system.
8043 On a case-sensitive system
8044 such as Linux or UNIX,
8045 &scons; treats a file with a
8046 <filename>.C</filename>
8047 suffix as a C++ source file.
8048 On a case-insensitive system
8050 &scons; treats a file with a
8051 <filename>.C</filename>
8052 suffix as a C source file.</para>
8055 <refsect2 id='f_file_suffix'>
8056 <title>Fortran File Suffixes</title>
8059 There are several ways source file suffixes impact the
8060 behavior of &SCons; when working with Fortran language code
8061 (not all are system-specific, but they are included here
8066 As the Fortran language has evolved through multiple
8067 standards editions, projects might have a need to handle
8068 files from different language generations differently.
8069 To this end, &SCons; dispatches to a different compiler
8070 dialect setup (expressed as a set of &consvars;)
8071 depending on the file suffix.
8072 By default, all of these setups start out the same,
8073 but individual &consvars; can be modified as needed to tune a given dialect.
8074 Each of these dialects has a tool specification module
8075 whose documentation describes the &consvars; associated
8076 with that dialect: <filename>.f</filename>
8077 (as well as <filename>.for</filename> and <filename>.ftn</filename>)
8078 in &t-link-fortran;; (&consvars; start with <literal>FORTRAN</literal>)
8079 <filename>.f77</filename> in &t-link-f77;;
8080 (&consvars; start with <literal>F77</literal>)
8081 <filename>.f90</filename> in &t-link-f90;;
8082 (&consvars; start with <literal>F90</literal>)
8083 <filename>.f95</filename> in &t-link-f95;;
8084 (&consvars; start with <literal>F95</literal>)
8085 <filename>.f03</filename> in &t-link-f03;;
8086 (&consvars; start with <literal>F03</literal>)
8087 <filename>.f08</filename> in &t-link-f08;
8088 (&consvars; start with <literal>F08</literal>).
8092 While &SCons; recognizes multiple internal dialects
8093 based on filename suffixes,
8094 the convention of various available Fortran compilers is
8095 to assign an actual meaning to only two of these suffixes:
8096 <filename>.f</filename>
8097 (as well as <filename>.for</filename> and <filename>.ftn</filename>)
8098 refers to the fixed-format source
8099 code that was the only available option in FORTRAN 77 and earlier,
8100 and <filename>.f90</filename> refers to free-format source code
8101 which became available as of the Fortran 90 standard.
8102 Some compilers recognize suffixes which correspond to Fortran
8103 specifications later than F90 as equivalent to
8104 <filename>.f90</filename> for this purpose,
8105 while some do not - check the documentation for your compiler.
8106 An occasionally suggested policy suggestion is to use only
8107 <filename>.f</filename> and <filename>.f90</filename>
8108 as Fortran filename suffixes.
8109 The fixed/free form determination can usually be controlled
8110 explicitly with compiler flags
8111 (e.g. <option>-ffixed-form</option> for gfortran),
8112 overriding any assumption that may be made based on the source file suffix.
8116 The source file suffix does not imply conformance
8117 with the similarly-named Fortran standard - a suffix of
8118 <filename>.f08</filename> does not mean you are compiling
8119 specifically for Fortran 2008. Normally, compilers
8120 provide command-line options for making this selection
8121 (e.g. <option>-std=f2008</option> for gfortran).
8125 For dialects from F90 on (including the generic FORTRAN dialect),
8126 a suffix of <filename>.mod</filename> is recognized for Fortran modules.
8127 These files are a side effect of compiling a Fortran
8128 source file containing module declarations,
8129 and must be available when other code which declares
8130 that it uses the module is processed.
8131 &SCons; does not currently have integrated support for submodules,
8132 introduced in the Fortran 2008 standard -
8133 the invoked compiler will produce results,
8134 but &SCons; will not recognize
8135 <filename>.smod</filename> files as tracked objects.
8139 On a case-sensitive system such as Linux or UNIX,
8140 a file with a an upper-cased suffix from the set
8141 <filename>.F</filename>,
8142 <filename>.FOR</filename>,
8143 <filename>.FTN</filename>,
8144 <filename>.F90</filename>,
8145 <filename>.F95</filename>,
8146 <filename>.F03</filename> and
8147 <filename>.F08</filename>
8148 is treated as a Fortran source file
8149 which shall first be run through
8150 the standard C preprocessor.
8151 The lower-cased versions of these suffixes do not
8152 trigger this behavior.
8153 On systems which do not distinguish between upper
8154 and lower case in filenames,
8155 this behavior is not available,
8156 but files suffixed with either
8157 <filename>.FPP</filename>
8158 or <filename>.fpp</filename>
8159 are always passed to the preprocessor first.
8160 This matches the convention of <command>gfortran</command>
8161 from the GNU Compiler Collection,
8162 and also followed by certain other Fortran compilers.
8163 For these two suffixes,
8164 the generic <emphasis>FORTRAN</emphasis> dialect will be selected.
8168 &SCons; itself does not invoke the preprocessor,
8169 that is handled by the compiler,
8170 but it adds &consvars; which are applicable to the preprocessor run.
8171 You can see this difference by examining
8172 &cv-link-FORTRANPPCOM; and &cv-link-FORTRANPPCOMSTR;
8173 which are used instead of
8174 &cv-link-FORTRANCOM; and &cv-link-FORTRANCOMSTR; for that dialect.
8178 <refsect2 id='windows_cygwin_tools_and_cygwin_python_v'>
8179 <title>Windows: Cygwin Tools and Cygwin Python vs. Windows Pythons</title>
8181 <para>Cygwin supplies a set of tools and utilities
8182 that let users work on a
8183 Windows system using a POSIX-like environment.
8184 The Cygwin tools, including Cygwin &Python;,
8186 by sharing an ability to interpret POSIX-style path names.
8187 For example, the Cygwin tools
8188 will internally translate a Cygwin path name
8189 like <filename>/cygdrive/c/mydir</filename>
8190 to an equivalent Windows pathname
8191 of <filename>C:/mydir</filename> (equivalent to <filename>C:\mydir</filename>).
8194 <para>Versions of &Python;
8195 that are built for native Windows execution,
8196 such as the python.org and ActiveState versions,
8197 do not understand the Cygwin path name semantics.
8198 This means that using a native Windows version of &Python;
8199 to build compiled programs using Cygwin tools
8200 (such as &gcc;, &bison; and &flex;)
8201 may yield unpredictable results.
8202 "Mixing and matching" in this way
8203 can be made to work,
8204 but it requires careful attention to the use of path names
8205 in your &SConscript; files.</para>
8207 <para>In practice, users can sidestep
8208 the issue by adopting the following guidelines:
8209 When using Cygwin's &gcc; for compiling,
8210 use the Cygwin-supplied &Python; interpreter
8213 (or some other "native" Windows compiler)
8214 use the python.org, Microsoft Store, ActiveState or other
8215 native version of &Python; to run &scons;.
8219 This discussion largely applies to the msys2 environment
8220 as well (with the use of the mingw compiler toolchain),
8221 in particular the recommendation to use the msys2 version of
8222 &Python; if running &scons; from inside an msys2 shell.
8226 <refsect2 id='windows_sconsbat_file'>
8227 <title>Windows: <filename>scons.bat</filename> file</title>
8229 <para>On Windows, if &scons; is executed via a wrapper
8230 <filename>scons.bat</filename> batch file,
8231 there are (at least) two ramifications.
8232 Note this is no longer the default - &scons; installed
8233 via &Python;'s <command>pip</command> installer
8234 will have a <command>scons.exe</command> which does
8235 not have these limitations:
8238 <para>First, Windows command-line users
8239 that want to use variable assignment
8241 may have to put double quotes
8242 around the assignments, otherwise the
8243 Windows command shell will consume those as
8244 arguments to itself, not to &scons;:</para>
8247 <userinput>scons "FOO=BAR" "BAZ=BLEH"</userinput>
8250 <para>Second, the Cygwin shell does not
8251 recognize typing <userinput>scons</userinput>
8252 at the command line prompt as referring to this wrapper.
8253 You can work around this either by executing
8254 <userinput>scons.bat</userinput>
8255 (including the extension)
8256 from the Cygwin command line,
8257 or by creating a wrapper shell
8259 <filename>scons</filename> which
8260 invokes <filename>scons.bat</filename>.
8265 <refsect2 id='mingw'>
8266 <title>MinGW</title>
8268 <para>The MinGW <filename>bin</filename>
8269 directory must be in your <envar>PATH</envar>
8270 environment variable or the
8271 <varname>['ENV']['PATH']</varname> &consvar; for &scons;
8272 to detect and use the MinGW tools. When running under the native Windows
8273 &Python; interpreter, &scons; will prefer the MinGW tools over the Cygwin
8274 tools, if they are both installed, regardless of the order of the bin
8275 directories in the <envar>PATH</envar> variable.
8276 If you have both MSVC and MinGW
8277 installed and you want to use MinGW instead of MSVC,
8278 then you must explicitly tell &scons; to use MinGW by passing
8279 <code>tools=['mingw']</code>
8280 to the &Environment; function, because &scons; will prefer the MSVC tools
8281 over the MinGW tools.</para>
8286 <!-- Removed in favor of scons-cookbook.readthedocs.io,
8287 but leave here for the time being...
8289 <refsect1 id='examples'>
8290 <title>EXAMPLES</title>
8292 <para>To help you get started using &scons;,
8293 this section contains a brief overview of some common tasks.
8294 See the &SCons; User Guide for many more examples.
8298 <refsect2 id='basic_compilation_from_a_single_source_f'>
8299 <title>Basic Compilation From a Single Source File</title>
8301 <programlisting language="python">
8303 env.Program(target='foo', source='foo.c')
8306 <para>Note: Build the file by specifying
8307 the target as an argument
8308 (<userinput>scons foo</userinput> or <userinput>scons foo.exe</userinput>)
8309 or by specifying the current directory as the target
8310 (<userinput>scons .</userinput>).</para>
8314 <refsect2 id='basic_compilation_from_multiple_source_f'>
8315 <title>Basic Compilation From Multiple Source Files</title>
8317 <programlisting language="python">
8319 env.Program(target='foo', source=Split('f1.c f2.c f3.c'))
8324 <refsect2 id='setting_a_compilation_flag'>
8325 <title>Setting a Compilation Flag</title>
8327 <programlisting language="python">
8328 env = Environment(CCFLAGS='-g')
8329 env.Program(target='foo', source='foo.c')
8334 <refsect2 id='search_the_local_directory_for_h_files'>
8335 <title>Search The Local Directory For .h Files</title>
8338 <emphasis>not</emphasis>
8339 need to set <envar>CCFLAGS</envar> to specify
8340 <option>-I</option> options by hand.
8341 &scons; will construct the right <option>-I</option>
8342 options from the contents of <envar>CPPPATH.</envar></para>
8344 <programlisting language="python">
8345 env = Environment(CPPPATH=['.'])
8346 env.Program(target='foo', source='foo.c')
8351 <refsect2 id='search_multiple_directories_for_h_files'>
8352 <title>Search Multiple Directories For .h Files</title>
8354 <programlisting language="python">
8355 env = Environment(CPPPATH=['include1', 'include2'])
8356 env.Program(target='foo', source='foo.c')
8361 <refsect2 id='building_a_static_library'>
8362 <title>Building a Static Library</title>
8364 <programlisting language="python">
8366 env.StaticLibrary(target='foo', source=Split('l1.c l2.c'))
8367 env.StaticLibrary(target='bar', source=['l3.c', 'l4.c'])
8372 <refsect2 id='building_a_shared_library'>
8373 <title>Building a Shared Library</title>
8375 <programlisting language="python">
8377 env.SharedLibrary(target='foo', source=['l5.c', 'l6.c'])
8378 env.SharedLibrary(target='bar', source=Split('l7.c l8.c'))
8383 <refsect2 id='linking_a_local_library_into_a_program'>
8384 <title>Linking a Local Library Into a Program</title>
8386 <programlisting language="python">
8387 env = Environment(LIBS='mylib', LIBPATH=['.'])
8388 env.Library(target='mylib', source=Split('l1.c l2.c'))
8389 env.Program(target='prog', source=['p1.c', 'p2.c'])
8394 <refsect2 id='defining_your_own_builder_object'>
8395 <title>Defining Your Own Builder Object</title>
8397 <para>Notice that when you invoke the Builder,
8398 you can leave off the target file suffix,
8399 and &scons; will add it automatically.</para>
8401 <programlisting language="python">
8403 action='pdftex < $SOURCES > $TARGET',
8407 env = Environment(BUILDERS={'PDFBuilder': bld})
8408 env.PDFBuilder(target='foo.pdf', source='foo.tex')
8410 # The following creates "bar.pdf" from "bar.tex"
8411 env.PDFBuilder(target='bar', source='bar')
8414 <para>Note that the above initialization
8415 replaces the default dictionary of Builders,
8416 so this &consenv; can not be used call Builders like
8417 &b-link-Program;, &b-link-Object;, &b-link-StaticLibrary; etc.
8418 See the next example for an alternative.
8423 <refsect2 id='adding_your_own_builder_object_to_an_env'>
8424 <title>Adding Your Own Builder Object to an Environment</title>
8426 <programlisting language="python">
8428 action='pdftex < $SOURCES > $TARGET'
8433 env.Append(BUILDERS={'PDFBuilder': bld})
8434 env.PDFBuilder(target='foo.pdf', source='foo.tex')
8435 env.Program(target='bar', source='bar.c')
8438 <para>You also can use other Pythonic techniques to add
8439 to the <envar>BUILDERS</envar> &consvar;, such as:</para>
8441 <programlisting language="python">
8443 env['BUILDERS]['PDFBuilder'] = bld
8448 <refsect2 id='defining_your_own_scanner_object'>
8449 <title>Defining Your Own Scanner Object</title>
8451 <para>The following example shows adding an extremely simple scanner
8452 (<function>kfile_scan</function>)
8453 that doesn't use a search path at all
8454 and simply returns the
8455 file names present on any
8456 <literal>include</literal>
8457 lines in the scanned file.
8458 This would implicitly assume that all included
8459 files live in the top-level directory:</para>
8461 <programlisting language="python">
8464 include_re = re.compile(r'^include\s+(\S+)$', re.M)
8466 def kfile_scan(node, env, path, arg):
8467 contents = node.get_text_contents()
8468 includes = include_re.findall(contents)
8469 return env.File(includes)
8473 function=kfile_scan,
8478 scanners = DefaultEnvironment()['SCANNERS']
8479 scanners.append(kscan)
8480 env = Environment(SCANNERS=scanners)
8482 env.Command('foo', 'foo.k', 'kprocess < $SOURCES > $TARGET')
8484 bar_in = File('bar.in')
8485 env.Command('bar', bar_in, 'kprocess $SOURCES > $TARGET')
8486 bar_in.target_scanner = kscan
8489 <para>It is important to note that you
8490 have to return a list of File nodes from the scan function, simple
8491 strings for the file names won't do. As in the examples shown here,
8492 you can use the &f-link-env-File;
8493 function of your current &consenv; in order to create nodes on the fly from
8494 a sequence of file names with relative paths.</para>
8496 <para>Here is a similar but more complete example that adds
8497 a scanner which searches
8498 a path of directories
8500 <envar>MYPATH</envar> &consvar;)
8501 for files that actually exist:</para>
8503 <programlisting language="python">
8507 include_re = re.compile(r'^include\s+(\S+)$', re.M)
8509 def my_scan(node, env, path, arg):
8510 contents = node.get_text_contents()
8511 includes = include_re.findall(contents)
8515 for inc in includes:
8517 file = str(dir) + os.sep + inc
8518 if os.path.exists(file):
8519 results.append(file)
8521 return env.File(results)
8528 path_function=FindPathDirs('MYPATH'),
8531 scanners = DefaultEnvironment()['SCANNERS']
8532 scanners.append(scanner)
8533 env = Environment(SCANNERS=scanners, MYPATH=['incs'])
8535 env.Command('foo', 'foo.x', 'xprocess < $SOURCES > $TARGET')
8539 &f-link-FindPathDirs;
8540 function used in the previous example returns a function
8541 (actually a callable &Python; object)
8542 that will return a list of directories
8544 <envar>MYPATH</envar>
8545 &consvar;. It lets &scons; detect the file
8546 <filename>incs/foo.inc</filename>,
8548 <filename>foo.x</filename>
8550 <literal>include foo.inc</literal>
8552 If you need to customize how the search path is derived,
8553 you would provide your own
8554 <parameter>path_function</parameter>
8555 argument when creating the Scanner object,
8558 <programlisting language="python">
8559 # MYPATH is a list of directories to search for files in
8560 def pf(env, dir, target, source, arg):
8561 top_dir = Dir('#').abspath
8564 for p in env['MYPATH']:
8565 results.append(top_dir + os.sep + p)
8580 <refsect2 id='creating_a_hierarchical_build'>
8581 <title>Creating a Hierarchical Build</title>
8583 <para>Notice that the file names specified in a subdirectory's
8584 &SConscript; file are relative to that subdirectory.</para>
8586 <para><filename>SConstruct</filename>:</para>
8588 <programlisting language="python">
8590 env.Program(target='foo', source='foo.c')
8592 SConscript('sub/SConscript')
8595 <para><filename>sub/SConscript</filename>:</para>
8597 <programlisting language="python">
8599 # Builds sub/foo from sub/foo.c
8600 env.Program(target='foo', source='foo.c')
8602 SConscript('dir/SConscript')
8605 <para><filename>sub/dir/SConscript</filename>:</para>
8607 <programlisting language="python">
8609 # Builds sub/dir/foo from sub/dir/foo.c
8610 env.Program(target='foo', source='foo.c')
8615 <refsect2 id='sharing_variables_between_sconscript_fil'>
8616 <title>Sharing Variables Between SConscript Files</title>
8618 <para>You must explicitly call &f-link-Export; and &f-link-Import;
8620 you want to share between &SConscript; files.</para>
8622 <para><filename>SConstruct</filename>:</para>
8624 <programlisting language="python">
8626 env.Program(target='foo', source='foo.c')
8629 SConscript('subdirectory/SConscript')
8632 <para><filename>subdirectory/SConscript</filename>:</para>
8634 <programlisting language="python">
8636 env.Program(target='foo', source='foo.c')
8641 <refsect2 id='building_multiple_variants_from_the_same'>
8642 <title>Building Multiple Variants From the Same Source</title>
8644 <para>Use the <parameter>variant_dir</parameter> keyword argument to
8645 the &f-link-SConscript; function to establish
8646 one or more separate variant build directory trees
8647 for a given source directory:</para>
8649 <para><filename>SConstruct</filename>:</para>
8651 <programlisting language="python">
8652 cppdefines = ['FOO']
8653 Export("cppdefines")
8654 SConscript('src/SConscript', variant_dir='foo')
8656 cppdefines = ['BAR']
8657 Export("cppdefines")
8658 SConscript('src/SConscript', variant_dir='bar')
8661 <para><filename>src/SConscript</filename>:</para>
8663 <programlisting language="python">
8664 Import("cppdefines")
8665 env = Environment(CPPDEFINES=cppdefines)
8666 env.Program(target='src', source='src.c')
8669 <para>Note the use of the &f-link-Export; method
8670 to set the <varname>cppdefines</varname> variable to a different
8671 value each time we call the &f-link-SConscript; function.</para>
8675 <refsect2 id='hierarchical_build_of_two_libraries_link'>
8676 <title>Hierarchical Build of Two Libraries Linked With a Program</title>
8678 <para><filename>SConstruct</filename>:</para>
8680 <programlisting language="python">
8681 env = Environment(LIBPATH=['#libA', '#libB'])
8683 SConscript('libA/SConscript')
8684 SConscript('libB/SConscript')
8685 SConscript('Main/SConscript')
8688 <para><filename>libA/SConscript</filename>:</para>
8690 <programlisting language="python">
8692 env.Library('a', Split('a1.c a2.c a3.c'))
8695 <para><filename>libB/SConscript</filename>:</para>
8697 <programlisting language="python">
8699 env.Library('b', Split('b1.c b2.c b3.c'))
8702 <para><filename>Main/SConscript</filename>:</para>
8704 <programlisting language="python">
8706 e = env.Clone(LIBS=['a', 'b'])
8707 e.Program('foo', Split('m1.c m2.c m3.c'))
8710 <para>The <literal>#</literal> in the <envar>LIBPATH</envar>
8711 directories specify that they're relative to the
8712 top-level directory, so they don't turn into
8713 <filename>Main/libA</filename> when they're
8714 used in <filename>Main/SConscript</filename></para>
8716 <para>Specifying only 'a' and 'b' for the library names
8717 allows &scons; to attach the appropriate library
8718 prefix and suffix for the current platform in
8719 creating the library filename
8720 (for example, <filename>liba.a</filename> on POSIX systems,
8721 <filename>a.lib</filename> on Windows).</para>
8725 <refsect2 id='customizing_construction_variables_from_'>
8726 <title>Customizing &consvars; from the command line.</title>
8728 <para>The following would allow the C compiler to be specified on the command
8729 line or in the file <filename>custom.py</filename>.</para>
8731 <programlisting language="python">
8732 vars = Variables('custom.py')
8733 vars.Add('CC', 'The C compiler.')
8734 env = Environment(variables=vars)
8735 Help(vars.GenerateHelpText(env))
8738 <para>The user could specify the C compiler on the command line:</para>
8741 <userinput>scons "CC=my_cc"</userinput>
8744 <para>or in the <filename>custom.py</filename> file:</para>
8746 <programlisting language="python">
8750 <para>or get documentation on the options:</para>
8753 $ <userinput>scons -h</userinput>
8762 <refsect2 id='using_microsoft_visual_c_precompiled_hea'>
8763 <title>Using &MSVC; precompiled headers</title>
8765 <para>Since <filename>windows.h</filename> includes everything
8766 and the kitchen sink, it can take quite
8767 some time to compile it over and over again for a bunch of object files, so
8768 Microsoft provides a mechanism to compile a set of headers once and then
8769 include the previously compiled headers in any object file. This
8770 technology is called precompiled headers (<firstterm>PCH</firstterm>).
8771 The general recipe is to create a
8772 file named <filename>StdAfx.cpp</filename>
8773 that includes a single header named <filename>StdAfx.h</filename>,
8774 and then include every header you want to precompile in
8775 <filename>StdAfx.h</filename>,
8776 and finally include <filename>"StdAfx.h</filename>
8777 as the first header in all the source files you are
8778 compiling to object files. For example:</para>
8780 <para><filename>StdAfx.h</filename>:</para>
8782 <programlisting language="C++">
8783 #include <windows.h>
8784 #include <my_big_header.h>
8787 <para><filename>StdAfx.cpp</filename>:</para>
8789 <programlisting language="C++">
8790 #include <StdAfx.h>
8793 <para><filename>Foo.cpp</filename>:</para>
8795 <programlisting language="C++">
8796 #include <StdAfx.h>
8801 <para><filename>Bar.cpp</filename>:</para>
8803 <programlisting language="C++">
8804 #include <StdAfx.h>
8806 /* do some other stuff */
8809 <para><filename>SConstruct</filename>:</para>
8811 <programlisting language="python">
8813 env['PCHSTOP'] = 'StdAfx.h'
8814 env['PCH'] = env.PCH('StdAfx.cpp')[0]
8815 env.Program('MyApp', ['Foo.cpp', 'Bar.cpp'])
8818 <para>For more information see the documentation for the &b-link-PCH; builder,
8819 and the &cv-link-PCH; and &cv-link-PCHSTOP; &consvars;.
8820 To learn about the details of precompiled
8821 headers consult the MSDN documentation for
8822 <option>/Yc</option>, <option>/Yu</option>, and <option>/Yp</option>.</para>
8826 <refsect2 id='using_microsoft_visual_c_external_debugg'>
8827 <title>Using &MSVC; external debugging information</title>
8829 <para>Since including debugging information in programs and shared libraries can
8830 cause their size to increase significantly, Microsoft provides a mechanism
8831 for including the debugging information in an external file called a
8832 <firstterm>PDB</firstterm> file.
8833 &scons; supports PDB files through the &cv-PDB; &consvar;.</para>
8835 <para><filename>SConstruct</filename>:</para>
8837 <programlisting language="python">
8839 env['PDB'] = 'MyApp.pdb'
8840 env.Program('MyApp', ['Foo.cpp', 'Bar.cpp'])
8843 <para>For more information see the documentation for the
8844 &cv-link-PDB; &consvar;.</para>
8849 <refsect1 id='environment'>
8850 <title>ENVIRONMENT</title>
8852 <para>In general, &scons; is not controlled by environment
8853 variables set in the shell used to invoke it, leaving it
8854 up to the &SConscript; file author to import those if desired.
8855 However, the following variables are imported by
8856 &scons; itself if set:
8861 <term><envar>SCONS_LIB_DIR</envar></term>
8863 <para>Specifies the directory that contains the &scons;
8864 &Python; module directory. Normally &scons; can deduce this,
8865 but in some circumstances, such as working with a source
8866 release, it may be necessary to specify
8868 <filename>/home/aroach/scons-src-0.01/src/engine</filename>).</para>
8872 <varlistentry id="v-SCONSFLAGS">
8873 <term><envar>SCONSFLAGS</envar></term>
8875 <para>A string containing options that will be used by &scons;
8876 in addition to those passed on the command line.
8877 Can be used to reduce frequent retyping of common options.
8878 The contents of <envar>SCONSFLAGS</envar> are considered
8879 before any passed command line options,
8880 so the command line can be used to override
8881 <envar>SCONSFLAGS</envar> options if necessary.
8887 <term><envar>SCONS_CACHE_MSVC_CONFIG</envar></term>
8889 <para>(Windows only). If set, save the shell environment variables
8890 generated when setting up the &MSVC; compiler
8891 (and/or Build Tools) to a cache file, to give these settings
8892 persistence across &scons; invocations.
8893 Generating this information is relatively expensive,
8894 so using this option may aid performance where &scons; is run often,
8895 such as Continuous Integration setups.</para>
8897 <para>If set to a True-like value (<literal>"1"</literal>,
8898 <literal>"true"</literal> or
8899 <literal>"True"</literal>) will cache to a file named
8900 <filename>scons_msvc_cache.json</filename> in the user's home directory.
8901 If set to a pathname, will use that pathname for the cache.</para>
8903 <para>Note: this implementation may still be somewhat fragile.
8904 In case of problems, remove the cache file - recreating with
8905 fresh info normally resolves any issues.
8906 &SCons; ignores failures reading or writing the cache file
8907 and will silently revert to non-cached behavior in such cases.
8910 <para><emphasis>New in 3.1 (experimental).
8911 The default cache file name was changed to
8912 its present value in 4.4, and contents were expanded.</emphasis>
8918 <term><envar>QTDIR</envar></term>
8920 <para>If using the &t-link-qt; tool, this is the path to
8921 the Qt installation to build against. &SCons; respects this
8922 setting because it is a long-standing convention in the Qt world,
8923 where multiple Qt installations are possible.</para>
8929 <refsect1 id='see_also'>
8930 <title>SEE ALSO</title>
8932 <simplelist type="vert">
8934 The SCons User Guide at
8935 <ulink url="https://scons.org/doc/production/HTML/scons-user.html"/>
8937 <member>The SCons Design Document (old)</member>
8939 The SCons Cookbook at
8940 <ulink url="https://scons-cookbook.readthedocs.io"/>
8941 for examples of how to solve various problems with &SCons;.
8945 <ulink url="https://github.com/SCons/scons">
8949 The SCons API Reference
8950 <ulink url="https://scons.org/doc/production/HTML/scons-api/index.html"/>
8951 (for internal details)
8957 <refsect1 id='authors'>
8958 <title>AUTHORS</title>
8960 <para>Originally: Steven Knight
8961 <email>knight@baldmt.com</email>
8962 and Anthony Roach <email>aroach@electriceyeball.com</email>.
8965 Since 2010: The SCons Development Team <email>scons-dev@scons.org</email>.