<?xml version="1.0"?>
<!--
SPDX-FileCopyrightText: Copyright The SCons Foundation (https://scons.org)
SPDX-License-Identifier: MIT
SPDX-FileType: DOCUMENTATION

This file is processed by the bin/SConsDoc.py module.
-->

<!DOCTYPE sconsdoc [
<!ENTITY % scons SYSTEM '../doc/scons.mod'>
%scons;
<!ENTITY % builders-mod SYSTEM '../doc/generated/builders.mod'>
%builders-mod;
<!ENTITY % functions-mod SYSTEM '../doc/generated/functions.mod'>
%functions-mod;
<!ENTITY % tools-mod SYSTEM '../doc/generated/tools.mod'>
%tools-mod;
<!ENTITY % variables-mod SYSTEM '../doc/generated/variables.mod'>
%variables-mod;
]>

<sconsdoc xmlns="http://www.scons.org/dbxsd/v1.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.scons.org/dbxsd/v1.0 http://www.scons.org/dbxsd/v1.0/scons.xsd">


<!-- Construction variables -->

<cvar name="BUILDERS">
<summary>
<para>
A dictionary mapping the names of the builders
available through the &consenv; to underlying Builder objects.
Custom builders need to be added to this to make them available.
</para>

<para>
A platform-dependent default list of builders such as
&b-link-Program;, &b-link-Library; etc. is used to
populate this &consvar; when the &consenv; is initialized
via the presence/absence of the tools those builders depend on.
&cv-BUILDERS; can be examined to learn which builders will
actually be available at run-time.
</para>

<para>
Note that if you initialize this &consvar; through
assignment when the &consenv; is created,
that value for &cv-BUILDERS; will override any defaults:
</para>

<example_commands>
bld = Builder(action='foobuild &lt; $SOURCE > $TARGET')
env = Environment(BUILDERS={'NewBuilder': bld})
</example_commands>

<para>
To instead use a new Builder object in addition to the default Builders,
add your new Builder object like this:
</para>

<example_commands>
env = Environment()
env.Append(BUILDERS={'NewBuilder': bld})
</example_commands>

<para>
or this:
</para>

<example_commands>
env = Environment()
env['BUILDERS']['NewBuilder'] = bld
</example_commands>
</summary>
</cvar>

<cvar name="ENV">
<summary>
<para>
The <firstterm>execution environment</firstterm> -
a dictionary of environment variables
used when &SCons; invokes external commands
to build targets defined in this &consenv;.
When &cv-ENV; is passed to a command,
all list values are assumed to be path lists and
are joined using the search path separator.
Any other non-string values are coerced to a string.
</para>

<para>
Note that by default
&SCons;
does
<emphasis>not</emphasis>
propagate the environment in effect when you execute
&scons; (the "shell environment")
to the execution environment.
This is so that builds will be guaranteed
repeatable regardless of the environment
variables set at the time
&scons;
is invoked.
If you want to propagate a
shell environment variable
to the commands executed
to build target files,
you must do so explicitly.
A common example is
the system &PATH;
environment variable,
so that
&scons;
will find utilities the same way
as the invoking shell (or other process):
</para>

<example_commands>
import os
env = Environment(ENV={'PATH': os.environ['PATH']})
</example_commands>

<para>
Although it is usually not recommended,
you can propagate the entire shell environment
in one go:
</para>

<example_commands>
import os
env = Environment(ENV=os.environ.copy())
</example_commands>

</summary>
</cvar>

<cvar name="SCANNERS">
<summary>
<para>
A list of the available implicit dependency scanners.
New file scanners may be added by
appending to this list,
although the more flexible approach
is to associate scanners
with a specific Builder.
See the manpage sections "Builder Objects"
and "Scanner Objects"
for more information.
</para>
</summary>
</cvar>

<cvar name="CHANGED_SOURCES">
<summary>
<para>
A reserved variable name
that may not be set or used in a &consenv;.
(See the manpage section "Variable Substitution"
for more information).
</para>
</summary>
</cvar>

<cvar name="CHANGED_TARGETS">
<summary>
<para>
A reserved variable name
that may not be set or used in a &consenv;.
(See the manpage section "Variable Substitution"
for more information).
</para>
</summary>
</cvar>

<cvar name="SOURCE">
<summary>
<para>
A reserved variable name
that may not be set or used in a &consenv;.
(See the manpage section "Variable Substitution"
for more information).
</para>
</summary>
</cvar>

<cvar name="SOURCES">
<summary>
<para>
A reserved variable name
that may not be set or used in a &consenv;.
(See the manpage section "Variable Substitution"
for more information).
</para>
</summary>
</cvar>

<cvar name="TARGET">
<summary>
<para>
A reserved variable name
that may not be set or used in a &consenv;.
(See the manpage section "Variable Substitution"
for more information).
</para>
</summary>
</cvar>

<cvar name="TARGETS">
<summary>
<para>
A reserved variable name
that may not be set or used in a &consenv;.
(See the manpage section "Variable Substitution"
for more information).
</para>
</summary>
</cvar>

<cvar name="UNCHANGED_SOURCES">
<summary>
<para>
A reserved variable name
that may not be set or used in a &consenv;.
(See the manpage section "Variable Substitution"
for more information).
</para>
</summary>
</cvar>

<cvar name="UNCHANGED_TARGETS">
<summary>
<para>
A reserved variable name
that may not be set or used in a &consenv;.
(See the manpage section "Variable Substitution"
for more information).
</para>
</summary>
</cvar>

<cvar name="TOOLS">
<summary>
<para>
A list of the names of the Tool specification modules
that were actually initialized in the current &consenv;.
This may be useful as a diagnostic aid
to see if a tool did (or did not) run.
The value is informative and is not guaranteed to be complete.
</para>
</summary>
</cvar>

<cvar name="CACHEDIR_CLASS">
    <summary>
        <para>
The class type that SCons should use when instantiating a
new &f-link-CacheDir; in this &consenv;. Must be
a subclass of the <classname>SCons.CacheDir.CacheDir</classname> class.
        </para>
    </summary>
</cvar>

<!-- Functions /  Construction environment methods -->

<scons_function name="Action">
<arguments>
(action, [output, [var, ...]] [key=value, ...])
</arguments>
<summary>
<para>
A factory function to create an Action object for
the specified
<parameter>action</parameter>.
See the manpage section "Action Objects"
for a complete explanation of the arguments and behavior.
</para>

<para>
Note that the &f-env-Action;
form of the invocation will expand
&consvars; in any argument strings,
including the
<parameter>action</parameter>
argument, at the time it is called
using the &consvars; in the
&consenv; through which
&f-env-Action; was called.
The &f-Action; global function
form delays all variable expansion
until the Action object is actually used.
</para>
</summary>
</scons_function>

<scons_function name="AddMethod">
<arguments signature="global">
(object, function, [name])
</arguments>
<arguments signature="env">
(function, [name])
</arguments>
<summary>
<para>
Adds <parameter>function</parameter> to an object as a method.
<parameter>function</parameter> will be called with an instance
object as the first argument as for other methods.
If <parameter>name</parameter> is given, it is used as
the name of the new method, else the name of
<parameter>function</parameter> is used.
</para>
<para>
When the global function &f-AddMethod; is called,
the object to add the method to must be passed as the first argument;
typically this will be &Environment;,
in order to create a method which applies to all &consenvs;
subsequently constructed.
When called using the &f-env-AddMethod; form,
the method is added to the specified &consenv; only.
Added methods propagate through &f-env-Clone; calls.
</para>

<para>
More examples:
</para>

<example_commands>
# Function to add must accept an instance argument.
# The Python convention is to call this 'self'.
def my_method(self, arg):
    print("my_method() got", arg)

# Use the global function to add a method to the Environment class:
AddMethod(Environment, my_method)
env = Environment()
env.my_method('arg')

# Use the optional name argument to set the name of the method:
env.AddMethod(my_method, 'other_method_name')
env.other_method_name('another arg')
</example_commands>
</summary>
</scons_function>

<scons_function name="AddPostAction">
<arguments>
(target, action)
</arguments>
<summary>
<para>
Arrange for the specified
<parameter>action</parameter>
to be performed
after the specified
<parameter>target</parameter>
has been built.
<parameter>action</parameter> may be
an Action object, or anything that
can be converted into an Action object.
See the manpage section "Action Objects"
for a complete explanation.
</para>

<para>
When multiple targets are supplied,
the action may be called multiple times,
once after each action that generates
one or more targets in the list.
</para>

<example_commands>
foo = Program('foo.c')
# remove execute permission from binary:
AddPostAction(foo, Chmod('$TARGET', "a-x"))
</example_commands>

<para>
If a <parameter>target</parameter> is an &f-Alias;,
<parameter>action</parameter> is associated with the
action of the alias, if specified.
</para>

</summary>
</scons_function>

<scons_function name="AddPreAction">
<arguments>
(target, action)
</arguments>
<summary>
<para>
Arrange for the specified
<parameter>action</parameter>
to be performed
before the specified
<parameter>target</parameter>
is built.
<parameter>action</parameter> may be
an Action object, or anything that
can be converted into an Action object.
See the manpage section "Action Objects"
for a complete explanation.
</para>

<para>
When multiple targets are specified,
the action(s) may be called multiple times,
once before each action that generates
one or more targets in the list.
</para>

<para>
Note that if any of the targets are built in multiple steps,
the action will be invoked just
before the action step that specifically
generates the specified target(s).
It may not always be obvious
if the process is multi-step - for example,
if you use the &Program; builder to
construct an executable program from a
<filename>.c</filename> source file,
&scons; builds an intermediate object file first;
the pre-action is invoked after this step
and just before the link command to
generate the executable program binary.
Example:
</para>

<example_commands>
foo = Program('foo.c')
AddPreAction(foo, 'echo "Running pre-action"')
</example_commands>

<screen>
$ scons -Q
gcc -o foo.o -c foo.c
echo "Running pre-action"
Running pre-action
gcc -o foo foo.o
</screen>

<para>
If a <parameter>target</parameter> is an &f-Alias;,
<parameter>action</parameter> is associated with the
action of the alias, if specified.
</para>

</summary>
</scons_function>

<scons_function name="Alias">
<arguments>
(alias, [source, [action]])
</arguments>
<summary>
<para>
Create an <firstterm>Alias</firstterm> node that
can be used as a reference to zero or more other targets,
specified by the optional <parameter>source</parameter> parameter.
Aliases provide a way to give a shorter or more descriptive
name to specific targets,
and to group multiple targets under a single name.
The alias name, or an Alias Node object,
may be used as a dependency of any other target,
including another alias.
</para>

<para>
<parameter>alias</parameter> and <parameter>source</parameter>
may each be a string or Node object,
or a list of strings or Node objects;
if Nodes are used for
<parameter>alias</parameter>
they must be Alias nodes.
If <parameter>source</parameter> is omitted,
the alias is created but has no reference;
if selected for building this will result in a
<quote>Nothing to be done.</quote> message.
An empty alias can be used to define the alias
in a visible place in the project;
it can later be appended to in a subsidiary SConscript file
with the actual target(s) to refer to.
The optional
<parameter>action</parameter>
parameter specifies an action or list of actions
that will be executed
whenever the any of the alias targets are out-of-date.
</para>

<para>
&f-Alias; can be called for an existing alias,
which appends the <parameter>alias</parameter>
and/or <parameter>action</parameter> arguments
to the existing lists for that alias.
</para>

<para>
Returns a list of Alias Node objects representing the alias(es),
which exist outside of any physical file system.
The alias name space is separate from the name space for
tangible targets; to avoid confusion do not reuse
target names as alias names.
</para>

<para>
Examples:
</para>

<example_commands>
Alias('install')
Alias('install', '/usr/bin')
Alias(['install', 'install-lib'], '/usr/local/lib')

env.Alias('install', ['/usr/local/bin', '/usr/local/lib'])
env.Alias('install', ['/usr/local/man'])

env.Alias('update', ['file1', 'file2'], "update_database $SOURCES")
</example_commands>
</summary>
</scons_function>

<scons_function name="AlwaysBuild">
<arguments>
(target, ...)
</arguments>
<summary>
<para>
Marks each given
<parameter>target</parameter>
so that it is always assumed to be out-of-date,
and will always be rebuilt if needed.
Note, however, that
&f-AlwaysBuild;
does not add its target(s) to the default target list,
so the targets will only be built
if they are specified on the command line,
or are a dependent of a target specified on the command line--but
they will
<emphasis>always</emphasis>
be built if so specified.
Multiple targets can be passed in to a single call to
&f-AlwaysBuild;.
</para>
</summary>
</scons_function>

<scons_function name="Append">
<arguments signature="env">
(key=val, [...])
</arguments>
<summary>
<para>
Appends value(s) intelligently to &consvars; in
<varname>env</varname>.
The &consvars; and values to add to them are passed as
<parameter>key=val</parameter> pairs (&Python; keyword arguments).
&f-env-Append; is designed to allow adding values
without having to think about the data type of an existing &consvar;.
Regular &Python; syntax can also be used to manipulate the &consvar;,
but for that you may need to know the types involved,
for example pure &Python; lets you directly "add" two lists of strings,
but adding a string to a list or a list to a string requires
different syntax - things &f-Append; takes care of.
Some pre-defined &consvars; do have type expectations
based on how &SCons; will use them:
for example &cv-link-CPPDEFINES; is often a string or a list of strings,
but can also be a list of tuples or a dictionary;
while &cv-link-LIBEMITTER;
is expected to be a callable or list of callables,
and &cv-link-BUILDERS; is expected to be a dictionary.
Consult the documentation for the various &consvars; for more details.
</para>

<para>
The following descriptions apply to both the &f-Append;
and &f-Prepend; methods, as well as their
<emphasis role="bold">Unique</emphasis> variants,
with the differences being the insertion point of the added values
and whether duplication is allowed.
</para>

<para>
<parameter>val</parameter> can be almost any type.
If <varname>env</varname> does not have a &consvar;
named <parameter>key</parameter>,
then <parameter>key</parameter> is simply
stored with a value of <parameter>val</parameter>.
Otherwise, <parameter>val</parameter> is
combined with the existing value,
possibly converting into an appropriate type
which can hold the expanded contents.
There are a few special cases to be aware of.
Normally, when two strings are combined,
the result is a new string containing their concatenation
(and you are responsible for supplying any needed separation);
however, the contents of &cv-link-CPPDEFINES;
will be post-processed by adding a prefix and/or suffix
to each entry when the command line is produced,
so &SCons; keeps them separate -
appending a string will result in a separate string entry,
not a combined string.
For &cv-CPPDEFINES;. as well as
&cv-link-LIBS;, and the various <literal>*PATH</literal> variables,
&SCons; will amend the variable by supplying the compiler-specific
syntax (e.g. prepending a <literal>-D</literal> or <literal>/D</literal>
prefix for &cv-CPPDEFINES;), so you should omit this syntax when
adding values to these variables.
Examples (gcc syntax shown in the expansion of &CPPDEFINES;):
</para>

<example_commands>
env = Environment(CXXFLAGS="-std=c11", CPPDEFINES="RELEASE")
print(f"CXXFLAGS = {env['CXXFLAGS']}, CPPDEFINES = {env['CPPDEFINES']}")
# notice including a leading space in CXXFLAGS addition
env.Append(CXXFLAGS=" -O", CPPDEFINES="EXTRA")
print(f"CXXFLAGS = {env['CXXFLAGS']}, CPPDEFINES = {env['CPPDEFINES']}")
print("CPPDEFINES will expand to", env.subst('$_CPPDEFFLAGS'))
</example_commands>

<screen>
$ scons -Q
CXXFLAGS = -std=c11, CPPDEFINES = RELEASE
CXXFLAGS = -std=c11 -O, CPPDEFINES = deque(['RELEASE', 'EXTRA'])
CPPDEFINES will expand to -DRELEASE -DEXTRA
scons: `.' is up to date.
</screen>

<para>
Because &cv-link-CPPDEFINES; is intended for command-line
specification of C/C++ preprocessor macros,
additional syntax is accepted when adding to it.
The preprocessor accepts arguments to predefine a macro name by itself
(<computeroutput>-DFOO</computeroutput> for most compilers,
<computeroutput>/DFOO</computeroutput> for Microsoft C++),
which gives it an implicit value of <constant>1</constant>,
or can be given with a replacement value
(<computeroutput>-DBAR=TEXT</computeroutput>).
&SCons; follows these rules when adding to &cv-CPPDEFINES;:
</para>
<itemizedlist>
<listitem>
<para>A string is split on spaces,
giving an easy way to enter multiple macros in one addition.
Use an <literal>=</literal> to specify a valued macro.</para>
</listitem>
<listitem>
<para>A tuple is treated as a valued macro.
Use the value <constant>None</constant> if the macro should not have a value.
It is an error to supply more than two elements in such a tuple.</para>
</listitem>
<listitem>
<para>A list is processed in order,
adding each item without further interpretation.
In this case, space-separated strings are not split.</para>
</listitem>
<listitem>
<para>A dictionary is processed in order,
adding each key-value pair as a valued macro.
Use the value <constant>None</constant> if the macro should not have a value.
</para>
</listitem>
</itemizedlist>

<para>
Examples:
</para>

<example_commands>
env = Environment(CPPDEFINES="FOO")
print("CPPDEFINES =", env['CPPDEFINES'])
env.Append(CPPDEFINES="BAR=1")
print("CPPDEFINES =", env['CPPDEFINES'])
env.Append(CPPDEFINES=[("OTHER", 2)])
print("CPPDEFINES =", env['CPPDEFINES'])
env.Append(CPPDEFINES={"EXTRA": "arg"})
print("CPPDEFINES =", env['CPPDEFINES'])
print("CPPDEFINES will expand to", env.subst('$_CPPDEFFLAGS'))
</example_commands>

<screen>
$ scons -Q
CPPDEFINES = FOO
CPPDEFINES = deque(['FOO', 'BAR=1'])
CPPDEFINES = deque(['FOO', 'BAR=1', ('OTHER', 2)])
CPPDEFINES = deque(['FOO', 'BAR=1', ('OTHER', 2), ('EXTRA', 'arg')])
CPPDEFINES will expand to -DFOO -DBAR=1 -DOTHER=2 -DEXTRA=arg
scons: `.' is up to date.
</screen>

<para>
Examples of adding multiple macros:
</para>

<example_commands>
env = Environment()
env.Append(CPPDEFINES=[("ONE", 1), "TWO", ("THREE", )])
print("CPPDEFINES =", env['CPPDEFINES'])
env.Append(CPPDEFINES={"FOUR": 4, "FIVE": None})
print("CPPDEFINES =", env['CPPDEFINES'])
print("CPPDEFINES will expand to", env.subst('$_CPPDEFFLAGS'))
</example_commands>

<screen>
$ scons -Q
CPPDEFINES = [('ONE', 1), 'TWO', ('THREE',)]
CPPDEFINES = deque([('ONE', 1), 'TWO', ('THREE',), ('FOUR', 4), ('FIVE', None)])
CPPDEFINES will expand to -DONE=1 -DTWO -DTHREE -DFOUR=4 -DFIVE
scons: `.' is up to date.
</screen>

<para>
<emphasis>Changed in version  4.5</emphasis>:
clarified the use of tuples vs. other types,
handling is now consistent across the four functions.
</para>

<example_commands>
env = Environment()
env.Append(CPPDEFINES=("MACRO1", "MACRO2"))
print("CPPDEFINES =", env['CPPDEFINES'])
env.Append(CPPDEFINES=[("MACRO3", "MACRO4")])
print("CPPDEFINES =", env['CPPDEFINES'])
print("CPPDEFINES will expand to", env.subst('$_CPPDEFFLAGS'))
</example_commands>

<screen>
$ scons -Q
CPPDEFINES = ('MACRO1', 'MACRO2')
CPPDEFINES = deque(['MACRO1', 'MACRO2', ('MACRO3', 'MACRO4')])
CPPDEFINES will expand to -DMACRO1 -DMACRO2 -DMACRO3=MACRO4
scons: `.' is up to date.
</screen>

<para>
See &cv-link-CPPDEFINES; for more details.
</para>

<para>
Appending a string <parameter>val</parameter>
to a dictionary-typed &consvar; enters
<parameter>val</parameter> as the key in the dictionary,
and <literal>None</literal> as its value.
Using a tuple type to supply a key-value pair
only works for the special case of &cv-CPPDEFINES;
described above.
</para>

<para>
Although most combinations of types work without
needing to know the details, some combinations
do not make sense and &Python; raises an exception.
</para>

<para>
When using &f-env-Append; to modify &consvars;
which are path specifications (conventionally,
the names of such end in <literal>PATH</literal>),
it is recommended to add the values as a list of strings,
even if you are only adding a single string.
The same goes for adding library names to &cv-LIBS;.
</para>

<example_commands>
env.Append(CPPPATH=["#/include"])
</example_commands>

<para>
See also &f-link-env-AppendUnique;,
&f-link-env-Prepend; and &f-link-env-PrependUnique;.
</para>

</summary>
</scons_function>

<scons_function name="AppendENVPath">
<arguments signature="env">
(name, newpath, [envname, sep, delete_existing=False])
</arguments>
<summary>
<para>
Append directory paths from
<parameter>newpath</parameter> to
a search-path entry <parameter>name</parameter>
in &consvar; <parameter>envname</parameter>
in the current enviromment (<parameter>env</parameter>).
If <parameter>envname</parameter> is not given,
the default is <literal>"ENV"</literal>
(see &cv-link-ENV;).
<parameter>envname</parameter> is expected
to refer to a dictionary-like object;
if it does not exist in <parameter>env</parameter>
it will be created as an initially empty dict.
<parameter>newpath</parameter>
may be specified as a string,
a directory node, or a list of strings.
If a string, it may contain multiple paths separated
by the system path separator
(<systemitem>os.pathsep</systemitem>),
or, if specified, by the value of <parameter>sep</parameter>.
Top-relative path strings (starting with <literal>#</literal>) are recognized.
The type of the existing value
of <parameter>name</parameter> is preserved.
</para>

<para>
Paths will only appear once.
Duplicate paths in <parameter>newpath</parameter> are removed,
preserving the last occurrence to maintain path order.
If <parameter>delete_existing</parameter> is true (the default),
existing duplicates are removed before appending,
otherwise, new duplicates are skipped.
During comparisons, paths are normalized, to avoid
issues with case differences (on case-insensitive filesystems)
and with relative paths that may refer back to the same directory.
The stored values are not modified by this process.
</para>

<para>
Example:
</para>

<example_commands>
print('before:', env['ENV']['INCLUDE'])
include_path = '/foo/bar:/foo'
env.AppendENVPath('INCLUDE', include_path)
print('after:', env['ENV']['INCLUDE'])
</example_commands>

<para>Yields:</para>
<screen>
before: /foo:/biz
after: /biz:/foo/bar:/foo
</screen>

<para>
See also &f-link-env-PrependENVPath;.
</para>

</summary>
</scons_function>

<scons_function name="AppendUnique">
<arguments signature="env">
(key=val, [...], [delete_existing=False])
</arguments>
<summary>
<para>
Append values to &consvars; in the current &consenv;,
maintaining uniqueness.
Works like &f-link-env-Append;,
except that values that would become duplicates
are not added.
If <parameter>delete_existing</parameter>
is set to a true value, then for any duplicate,
the existing instance of <parameter>val</parameter> is first removed,
then <parameter>val</parameter> is appended,
having the effect of moving it to the end.
</para>

<para>
Example:
</para>

<example_commands>
env.AppendUnique(CCFLAGS='-g', FOO=['foo.yyy'])
</example_commands>

<para>
See also &f-link-env-Append;,
&f-link-env-Prepend;
and &f-link-env-PrependUnique;.
</para>
</summary>
</scons_function>

<scons_function name="Builder">
<arguments>
(action, [arguments])
</arguments>
<summary>
<para>
Creates a Builder object for
the specified
<parameter>action</parameter>.
See the manpage section "Builder Objects"
for a complete explanation of the arguments and behavior.
</para>

<para>
Note that the
<function>env.Builder</function>()
form of the invocation will expand
&consvars; in any arguments strings,
including the
<parameter>action</parameter>
argument,
at the time it is called
using the &consvars; in the
<varname>env</varname>
&consenv; through which
&f-env-Builder; was called.
The
&f-Builder;
form delays all variable expansion
until after the Builder object is actually called.
</para>
</summary>
</scons_function>

<scons_function name="CacheDir">
<arguments>
(cache_dir, custom_class=None)
</arguments>
<summary>
<para>
Direct
&scons;
to maintain a derived-file cache in
<parameter>cache_dir</parameter>.
The derived files in the cache will be shared
among all the builds specifying the same
<parameter>cache_dir</parameter>.
Specifying a
<parameter>cache_dir</parameter>
of
<constant>None</constant>
disables derived file caching.
</para>

<para>
Calling the environment method
&f-link-env-CacheDir;
limits the effect to targets built
through the specified &consenv;.
Calling the global function
&f-link-CacheDir;
sets a global default
that will be used by all targets built
through &consenvs;
that do not set up environment-specific
caching by calling &f-env-CacheDir;.
</para>

<para>
Caching behavior can be configured by passing a specialized cache
class as the optional <parameter>custom_class</parameter> parameter.
This class must be a subclass of
<classname>SCons.CacheDir.CacheDir</classname>.
&SCons; will internally invoke the custom class for performing
caching operations.
If the parameter is omitted or set to
<constant>None</constant>, &SCons; will use the default
<classname>SCons.CacheDir.CacheDir</classname> class.
</para>

<para>
When derived-file caching
is being used and
&scons;
finds a derived file that needs to be rebuilt,
it will first look in the cache to see if a
file with matching &buildsig; exists
(indicating the input file(s) and build action(s)
were identical to those for the current target),
and if so, will retrieve the file from the cache.
&scons;
will report
<computeroutput>Retrieved `file' from cache</computeroutput>
instead of the normal build message.
If the derived file is not present in the cache,
&scons;
will build it and
then place a copy of the built file in the cache,
identified by its &buildsig;, for future use.
</para>

<para>
The
<computeroutput>Retrieved `file' from cache</computeroutput>
messages are useful for human consumption,
but less useful when comparing log files between
&scons; runs which will show differences that are
noisy and not actually significant.
To disable,
use the <option>--cache-show</option> option.
With this option, &scons; changes printing
to always show the action that would
have been used to build the file without caching.
</para>

<para>
Derived-file caching
may be disabled for any invocation
of &scons; by giving the
<option>--cache-disable</option>
command line option;
cache updating may be disabled, leaving cache
fetching enabled, by giving the
<option>--cache-readonly</option> option.
</para>

<para>
If the
<option>--cache-force</option>
option is used,
&scons;
will place a copy of
<emphasis>all</emphasis>
derived files into the cache,
even if they already existed
and were not built by this invocation.
This is useful to populate a cache
the first time a
<parameter>cache_dir</parameter>
is used for a build,
or to bring a cache up to date after
a build with cache updating disabled
(<option>--cache-disable</option>
or <option>--cache-readonly</option>)
has been done.
</para>

<para>
The
&f-link-NoCache;
method can be used to disable caching of specific files.  This can be
useful if inputs and/or outputs of some tool are impossible to
predict or prohibitively large.
</para>

<para>
Note that (at this time) &SCons; provides no facilities
for managing the derived-file cache. It is up to the developer
to arrange for cache pruning, expiry, access control, etc. if needed.
</para>

</summary>
</scons_function>

<scons_function name="Clean">
<arguments>
(targets, files)
</arguments>
<summary>
<para>
Set additional <parameter>files</parameter>
for removal when any of
<parameter>targets</parameter> are selected
for cleaning
(<link linkend="opt-clean"><option>-c</option></link>
command line option).
<parameter>targets</parameter> and
<parameter>files</parameter>
can each be a single filename or node,
or a list of filenames or nodes.
These can refer to files or directories.
Calling this method repeatedly
has an additive effect.
</para>

<para>
The related
&f-link-NoClean;
method has higher priority:
any target specified to
&f-NoClean;
will not be cleaned even if also given as
a <parameter>files</parameter>
parameter to &f-Clean;.
</para>

<para>
Examples:
</para>

<example_commands>
Clean('foo', ['bar', 'baz'])
Clean('dist', env.Program('hello', 'hello.c'))
Clean(['foo', 'bar'], 'something_else_to_clean')
</example_commands>

<para>
&SCons; does not directly track directories as targets -
they are created if needed and not normally removed
in clean mode.
In this example,
installing the project creates a subdirectory for the documentation.
The &f-Clean; call ensures that the subdirectory is removed
if the project is uninstalled.
</para>
<example_commands>
Clean(docdir, os.path.join(docdir, projectname))
</example_commands>
</summary>
</scons_function>

<scons_function name="Clone">
<arguments signature="env">
([key=val, ...])
</arguments>
<summary>
<para>
Returns an independent copy of a &consenv;.
If there are any unrecognized keyword arguments specified,
they are added as &consvars; in the copy,
overwriting any existing values
for those keywords.
See the manpage section "Construction Environments" for more details.
</para>

<para>
Example:
</para>

<example_commands>
env2 = env.Clone()
env3 = env.Clone(CCFLAGS='-g')
</example_commands>

<para>
A list of <parameter>tools</parameter>
and a <parameter>toolpath</parameter> may be specified,
as in the &f-link-Environment; constructor:
</para>

<example_commands>
def MyTool(env):
    env['FOO'] = 'bar'

env4 = env.Clone(tools=['msvc', MyTool])
</example_commands>

<para>
The
<parameter>parse_flags</parameter>
keyword argument is also recognized, to allow merging command-line
style arguments into the appropriate &consvars;
(see &f-link-env-MergeFlags;).
</para>

<example_commands>
# create an environment for compiling programs that use wxWidgets
wx_env = env.Clone(parse_flags='!wx-config --cflags --cxxflags')
</example_commands>

<para>
The <parameter>variables</parameter>
keyword argument is also recognized, to allow (re)initializing
&consvars; from a <literal>Variables</literal> object.
</para>

<para>
<emphasis>Changed in version 4.8.0:</emphasis>
the <parameter>variables</parameter> parameter was added.
</para>
</summary>
</scons_function>

<builder name="Command">
<summary>
<para>
There is actually no Builder named &Command;,
rather the term "Command Builder" refers to
a function which, on each call, creates and calls
an anonymous Builder.
This is useful for "one-off" builds
where a full Builder is not needed.
Since the anonymous Builder is never hooked
into the standard Builder framework,
an Action must always be specified.
See the &f-link-Command; function description
for the calling syntax and details.
</para>
</summary>
</builder>

<scons_function name="Command">
<arguments>
(target, source, action, [key=val, ...])
</arguments>
<summary>
<para>
Creates an anonymous builder and calls it,
thus recording <parameter>action</parameter>
to build <parameter>target</parameter>
from <parameter>source</parameter>
into the dependency tree.
This can be more convenient for a single special-case build
than having to define and add a new named Builder.
</para>

<para>
The
&Command; function accepts the
<parameter>source_scanner</parameter> and
<parameter>target_scanner</parameter>
keyword arguments which are used to specify
custom scanners for the specified sources or targets.
The value must be a Scanner object.
For example, the global
<literal>DirScanner</literal>
object can be used
if any of the sources will be directories
that must be scanned on-disk for
changes to files that aren't
already specified in other Builder or function calls.
</para>

<para>
The
&Command; function also accepts the
<parameter>source_factory</parameter> and
<parameter>target_factory</parameter>
keyword arguments which are used to specify
factory functions to create &SCons; Nodes
from any sources or targets specified as strings.
If any sources or targets are already Node objects,
they are not further transformed even if
a factory is specified for them.
The default for each is the &Entry; factory.
</para>

<para>
These four arguments, if given, are used
in the creation of the Builder.
Other Builder-specific keyword arguments
are not recognized as such.
See the manpage section "Builder Objects"
for more information about how these
arguments work in a Builder.
</para>

<para>
Any remaining keyword arguments are passed on to the
generated builder when it is called,
and behave as described in the manpage section "Builder Methods",
in short:
recognized arguments have their specified meanings,
while the rest are used to override
any same-named existing &consvars;
from the &consenv;.
</para>

<para>
<parameter>action</parameter> can be an external command,
specified as a string,
or a callable &Python; object;
see the manpage section "Action Objects"
for more complete information.
Also note that a string specifying an external command
may be preceded by an at-sign
(<literal>@</literal>)
to suppress printing the command in question,
or by a hyphen
(<literal>-</literal>)
to ignore the exit status of the external command.
</para>

<para>
Examples:
</para>

<example_commands>
env.Command(
    target='foo.out',
    source='foo.in',
    action="$FOO_BUILD &lt; $SOURCES &gt; $TARGET"
)

env.Command(
    target='bar.out',
    source='bar.in',
    action=["rm -f $TARGET", "$BAR_BUILD &lt; $SOURCES &gt; $TARGET"],
    ENV={'PATH': '/usr/local/bin/'},
)


import os
def rename(env, target, source):
    os.rename('.tmp', target[0])


env.Command(
    target='baz.out',
    source='baz.in',
    action=["$BAZ_BUILD &lt; $SOURCES &gt; .tmp", rename],
)
</example_commands>

<para>
Note that the
&Command;
function will usually assume, by default,
that the specified targets and/or sources are Files,
if no other part of the configuration
identifies what type of entries they are.
If necessary, you can explicitly specify
that targets or source nodes should
be treated as directories
by using the
&f-link-Dir;
or
&f-link-env-Dir;
functions.
</para>

<para>
Examples:
</para>

<example_commands>
env.Command('ddd.list', Dir('ddd'), 'ls -l $SOURCE > $TARGET')

env['DISTDIR'] = 'destination/directory'
env.Command(env.Dir('$DISTDIR')), None, make_distdir)
</example_commands>

<para>
Also note that SCons will usually
automatically create any directory necessary to hold a target file,
so you normally don't need to create directories by hand.
</para>
</summary>
</scons_function>

<scons_function name="Configure">
<arguments signature="global">
(env, [custom_tests, conf_dir, log_file, config_h])
</arguments>
<arguments signature="env">
([custom_tests, conf_dir, log_file, config_h])
</arguments>
<summary>
<para>
Creates a &Configure; object for integrated
functionality similar to GNU <command>autoconf</command>.
See the manpage section "Configure Contexts"
for a complete explanation of the arguments and behavior.
</para>
</summary>
</scons_function>

<scons_function name="Decider">
<arguments>
(function)
</arguments>
<summary>
<para>
Specifies that all up-to-date decisions for
targets built through this &consenv;
will be handled by <parameter>function</parameter>.
<parameter>function</parameter> can be the name of
a function or one of the following strings
that specify a predefined decider function:
</para>

<para>
<variablelist>
<varlistentry>
<term><literal>"content"</literal></term>
<listitem>
<para>
Specifies that a target shall be considered out-of-date and rebuilt
if the dependency's content has changed since the last time
the target was built,
as determined by performing a checksum
on the dependency's contents using the selected hash function,
and comparing it to the checksum recorded the
last time the target was built.
<literal>content</literal> is the default decider.
</para>
<para>
<emphasis>Changed in version 4.1:</emphasis>
The decider was renamed to <literal>content</literal>
since the hash function is now selectable.
The former name, <literal>MD5</literal>,
can still be used as a synonym, but is deprecated.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>"content-timestamp"</literal></term>
<listitem>
<para>
Specifies that a target shall be considered out-of-date and rebuilt
if the dependency's content has changed since the last time
the target was built,
except that dependencies with a timestamp that matches
the last time the target was rebuilt will be
assumed to be up-to-date and
<emphasis>not</emphasis>
rebuilt.
This provides behavior very similar
to the
<literal>content</literal>
behavior of always checksumming file contents,
with an optimization of not checking
the contents of files whose timestamps haven't changed.
The drawback is that SCons will
<emphasis>not</emphasis>
detect if a file's content has changed
but its timestamp is the same,
as might happen in an automated script
that runs a build,
updates a file,
and runs the build again,
all within a single second.
</para>
<para>
<emphasis>Changed in version 4.1:</emphasis>
The decider was renamed to <literal>content-timestamp</literal>
since the hash function is now selectable.
The former name, <literal>MD5-timestamp</literal>,
can still be used as a synonym, but is deprecated.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>"timestamp-newer"</literal></term>
<listitem>
<para>
Specifies that a target shall be considered out-of-date and rebuilt
if the dependency's timestamp is newer than the target file's timestamp.
This is the behavior of the classic Make utility,
and
<literal>make</literal>
can be used a synonym for
<literal>timestamp-newer</literal>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>"timestamp-match"</literal></term>
<listitem>
<para>
Specifies that a target shall be considered out-of-date and rebuilt
if the dependency's timestamp is different than the
timestamp recorded the last time the target was built.
This provides behavior very similar to the classic Make utility
(in particular, files are not opened up so that their
contents can be checksummed)
except that the target will also be rebuilt if a
dependency file has been restored to a version with an
<emphasis>earlier</emphasis>
timestamp, such as can happen when restoring files from backup archives.
</para>
</listitem>
</varlistentry>
</variablelist>
</para>

<para>
Examples:
</para>

<example_commands>
# Use exact timestamp matches by default.
Decider('timestamp-match')

# Use hash content signatures for any targets built
# with the attached &consenv;.
env.Decider('content')
</example_commands>

<para>
In addition to the above already-available functions, the
<parameter>function</parameter>
argument may be a &Python; function you supply.
Such a function must accept the following four arguments:
</para>

<para>
<variablelist>
<varlistentry>
<term><parameter>dependency</parameter></term>
<listitem>
<para>
The Node (file) which
should cause the
<parameter>target</parameter>
to be rebuilt
if it has "changed" since the last time
<parameter>target</parameter>
was built.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>target</parameter></term>
<listitem>
<para>
The Node (file) being built.
In the normal case,
this is what should get rebuilt
if the
<parameter>dependency</parameter>
has "changed."
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>prev_ni</parameter></term>
<listitem>
<para>
Stored information about the state of the
<parameter>dependency</parameter>
the last time the
<parameter>target</parameter>
was built.
This can be consulted to match various
file characteristics
such as the timestamp,
size, or &contentsig;.
</para>
</listitem>
</varlistentry>
    <varlistentry>
<term><parameter>repo_node</parameter></term>
<listitem>
<para>
If set, use this Node instead of the one specified by
<parameter>dependency</parameter>
to determine if the dependency has changed.
This argument is optional so should be written
as a default argument (typically it would be
written as <parameter>repo_node=None</parameter>).
A caller will normally only set this if the
target only exists in a Repository.
</para>
</listitem>
</varlistentry>

</variablelist>
</para>

<para>
The
<parameter>function</parameter>
should return a value which evaluates
<constant>True</constant>
if the
<parameter>dependency</parameter>
has "changed" since the last time
the
<parameter>target</parameter>
was built
(indicating that the target
<emphasis>should</emphasis>
be rebuilt),
and a value which evaluates
<constant>False</constant>
otherwise
(indicating that the target should
<emphasis>not</emphasis>
be rebuilt).
Note that the decision can be made
using whatever criteria are appropriate.
Ignoring some or all of the function arguments
is perfectly normal.
</para>

<para>
Example:
</para>

<example_commands>
def my_decider(dependency, target, prev_ni, repo_node=None):
    return not os.path.exists(str(target))

env.Decider(my_decider)
</example_commands>
</summary>
</scons_function>

<scons_function name="Depends">
<arguments>
(target, dependency)
</arguments>
<summary>
<para>
Specifies an explicit dependency;
the
<parameter>target</parameter>
will be rebuilt
whenever the
<parameter>dependency</parameter>
has changed.
Both the specified
<parameter>target</parameter>
and
<parameter>dependency</parameter>
can be a string
(usually the path name of a file or directory)
or Node objects,
or a list of strings or Node objects
(such as returned by a Builder call).
This should only be necessary
for cases where the dependency
is not caught by a Scanner
for the file.
</para>

<para>
Example:
</para>

<example_commands>
env.Depends('foo', 'other-input-file-for-foo')

mylib = env.Library('mylib.c')
installed_lib = env.Install('lib', mylib)
bar = env.Program('bar.c')

# Arrange for the library to be copied into the installation
# directory before trying to build the "bar" program.
# (Note that this is for example only.  A "real" library
# dependency would normally be configured through the $LIBS
# and $LIBPATH variables, not using an env.Depends() call.)

env.Depends(bar, installed_lib)
</example_commands>
</summary>
</scons_function>

<scons_function name="Detect">
<arguments signature="env">
(progs)
</arguments>
<summary>
<para>
Find an executable from one or more choices:
<parameter>progs</parameter> may be a string or a list of strings.
Returns the first value from <parameter>progs</parameter>
that was found, or <constant>None</constant>.
Executable is searched by checking the paths in the execution environment
(<varname>env</varname><literal>['ENV']['PATH']</literal>).
On Windows systems, additionally applies the filename suffixes found in
the execution environment
(<varname>env</varname><literal>['ENV']['PATHEXT']</literal>)
but will not include any such extension in the return value.
&f-env-Detect; is a wrapper around &f-link-env-WhereIs;.
</para>
</summary>
</scons_function>

<scons_function name="Dictionary">
<arguments signature="env">
([var, ...], [as_dict=])
</arguments>
<summary>
<para>
Return an object containing &consvars; from
<parameter>env</parameter>.
If <parameter>var</parameter> is omitted,
all the &consvars; with their values
are returned in a <type>dict</type>.
If <parameter>var</parameter> is specified,
and <parameter>as_dict</parameter> is true,
the specified &consvars; are returned in a <type>dict</type>;
otherwise (the default, for backwards compatibility),
values only are returned,
as a scalar if one <parameter>var</parameter> is given,
or as a list if multiples.
</para>

<para>
Example:
</para>

<example_commands>
cvars = env.Dictionary()
cc_values = env.Dictionary('CC', 'CCFLAGS', 'CCCOM')
</example_commands>

<note><para>
The object returned by &f-link-env-Dictionary; should be treated
as a read-only view into the &consvars;.
Some &consvars; require special internal handling,
and modifying them through the &f-env-Dictionary; object can bypass
that handling and cause data inconsistencies.
The primary use of &f-env-Dictionary; is for diagnostic purposes -
it is used widely by test cases specifically because
it bypasses the special handling so that behavior
can be verified.
</para></note>

<para>
<emphasis>Changed in 4.9.0</emphasis>:
<parameter>as_dict</parameter> added.
</para>

</summary>
</scons_function>

<scons_function name="Dir">
<arguments>
(name, [directory])
</arguments>
<summary>
<para>
Returns Directory Node(s).
A Directory Node is an object that represents a directory.
<parameter>name</parameter>
can be a relative or absolute path or a list of such paths.
<parameter>directory</parameter>
is an optional directory that will be used as the parent directory.
If no
<parameter>directory</parameter>
is specified, the current script's directory is used as the parent.
</para>

<para>
If
<parameter>name</parameter>
is a single pathname, the corresponding node is returned.
If
<parameter>name</parameter>
is a list, SCons returns a list of nodes.
Construction variables are expanded in
<parameter>name</parameter>.
</para>

<para>
Directory Nodes can be used anywhere you
would supply a string as a directory name
to a Builder method or function.
Directory Nodes have attributes and methods
that are useful in many situations;
see manpage section "Filesystem Nodes"
for more information.
</para>
</summary>
</scons_function>

<scons_function name="Dump">
<arguments signature="env">
([var, ...], [format=TYPE])
</arguments>
<summary>
<para>
Serialize &consvars; from <parameter>env</parameter> to a string.
If <varname>var</varname> is omitted,
all the &consvars; are serialized.
If one or more <varname>var</varname> values are supplied,
only those variables and their values are serialized.
</para>

<para>
The optional <parameter>format</parameter> string
selects the serialization format:
</para>
<variablelist>
<varlistentry>
<term><literal>pretty</literal></term>
<listitem>
<para>
Returns a pretty-printed representation
of the &consvars; - the result will look like a
&Python; <type>dict</type>
(this is the default).
</para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>json</literal></term>
<listitem>
<para>
Returns a JSON-formatted representation of the variables.
The variables will be presented as a JSON object literal,
the JSON equivalent of a &Python; <type>dict</type>..
</para>
</listitem>
</varlistentry>
</variablelist>

<para>
<emphasis>Changed in 4.9.0</emphasis>:
More than one <parameter>key</parameter> can be specified.
The returned string always looks like a <type>dict</type>
(or equivalent in other formats);
previously a single key serialized only the value,
not the key with the value.
</para>

<para>
Examples: this &SConstruct;
</para>

<example_commands>
env = Environment()
print(env.Dump('CCCOM'))
print(env.Dump('CC', 'CCFLAGS', format='json'))
</example_commands>

<para>
will print something like:
</para>

<example_commands>
{'CCCOM': '$CC -o $TARGET -c $CFLAGS $CCFLAGS $_CCCOMCOM $SOURCES'}
{
    "CC": "gcc",
    "CCFLAGS": []
}
</example_commands>

<para>
While this &SConstruct;:
</para>

<example_commands>
env = Environment()
print(env.Dump())
</example_commands>

<para>
will print something like:
</para>
<example_commands>
{ 'AR': 'ar',
  'ARCOM': '$AR $ARFLAGS $TARGET $SOURCES\n$RANLIB $RANLIBFLAGS $TARGET',
  'ARFLAGS': ['r'],
  'AS': 'as',
  'ASCOM': '$AS $ASFLAGS -o $TARGET $SOURCES',
  'ASFLAGS': [],
  ...
</example_commands>

</summary>
</scons_function>

<scons_function name="Environment">
<arguments>
([key=value, ...])
</arguments>
<summary>
<para>
Return a new &consenv;
initialized with the specified
<parameter>key</parameter>=<replaceable>value</replaceable>
pairs.
The keyword arguments
<parameter>parse_flags</parameter>,
<parameter>platform</parameter>,
<parameter>toolpath</parameter>,
<parameter>tools</parameter>
and <parameter>variables</parameter>
are specially recognized and do not lead to
&consvar; creation.
See the manpage section "Construction Environments" for more details.
</para>
</summary>
</scons_function>

<scons_function name="Execute">
<arguments>
(action, [actionargs ...])
</arguments>
<summary>
<para>
Executes an Action.
<parameter>action</parameter>
may be an Action object
or it may be a command-line string,
list of commands,
or executable &Python; function,
each of which will first be converted
into an Action object
and then executed.
Any additional arguments to &f-Execute;
are passed on to the &f-link-Action; factory function
which actually creates the Action object
(see the manpage section <link linkend="action_objects">Action Objects</link>
for a description). Example:
</para>

<example_commands>
Execute(Copy('file.out', 'file.in'))
</example_commands>

<para>&f-Execute; performs its action immediately,
as part of the SConscript-reading phase.
There are no sources or targets declared in an
&f-Execute; call, so any objects it manipulates
will not be tracked as part of the &SCons; dependency graph.
In the example above, neither
<filename>file.out</filename> nor
<filename>file.in</filename> will be tracked objects.
</para>

<para>
&f-Execute; returns the exit value of the command
or return value of the &Python; function.
&scons;
prints an error message if the executed
<parameter>action</parameter>
fails (exits with or returns a non-zero value),
however it does
<emphasis>not</emphasis>,
automatically terminate the build for such a failure.
If you want the build to stop in response to a failed
&f-Execute;
call,
you must explicitly check for a non-zero return value:
</para>

<example_commands>
if Execute("mkdir sub/dir/ectory"):
    # The mkdir failed, don't try to build.
    Exit(1)
</example_commands>
</summary>
</scons_function>

<scons_function name="File">
<arguments>
(name, [directory])
</arguments>
<summary>
<para>
Returns File Node(s).
A File Node is an object that represents a file.
<parameter>name</parameter>
can be a relative or absolute path or a list of such paths.
<parameter>directory</parameter>
is an optional directory that will be used as the parent directory.
If no
<parameter>directory</parameter>
is specified, the current script's directory is used as the parent.
</para>

<para>
If
<parameter>name</parameter>
is a single pathname, the corresponding node is returned.
If
<parameter>name</parameter>
is a list, SCons returns a list of nodes.
Construction variables are expanded in
<parameter>name</parameter>.
</para>

<para>
File Nodes can be used anywhere you
would supply a string as a file name
to a Builder method or function.
File Nodes have attributes and methods
that are useful in many situations;
see manpage section "Filesystem Nodes"
for more information.
</para>
</summary>
</scons_function>

<scons_function name="FindFile">
<arguments>
(file, dirs)
</arguments>
<summary>
<para>
Search for
<parameter>file</parameter>
in the path specified by
<parameter>dirs</parameter>.
<parameter>dirs</parameter>
may be a list of directory names or a single directory name.
In addition to searching for files that exist in the filesystem,
this function also searches for derived files
that have not yet been built.
</para>

<para>
Example:
</para>

<example_commands>
foo = env.FindFile('foo', ['dir1', 'dir2'])
</example_commands>
</summary>
</scons_function>

<scons_function name="FindInstalledFiles">
<arguments>
()
</arguments>
<summary>
<para>
Returns the list of targets set up by the
&b-link-Install;
or
&b-link-InstallAs;
builders.
</para>

<para>
This function serves as a convenient method to select the contents of
a binary package.
</para>

<para>
Example:
</para>

<example_commands>
Install('/bin', ['executable_a', 'executable_b'])

# will return the file node list
# ['/bin/executable_a', '/bin/executable_b']
FindInstalledFiles()

Install('/lib', ['some_library'])

# will return the file node list
# ['/bin/executable_a', '/bin/executable_b', '/lib/some_library']
FindInstalledFiles()
</example_commands>
</summary>
</scons_function>

<scons_function name="FindSourceFiles">
<arguments>
(node='"."')
</arguments>
<summary>
<para>
Returns the list of nodes which serve as the source of the built files.
It does so by inspecting the dependency tree starting at the optional
argument
<parameter>node</parameter>
which defaults to the '"."'-node. It will then return all leaves of
<parameter>node</parameter>.
These are all children which have no further children.
</para>

<para>
This function is a convenient method to select the contents of a Source
Package.
</para>

<para>
Example:
</para>

<example_commands>
Program('src/main_a.c')
Program('src/main_b.c')
Program('main_c.c')

# returns ['main_c.c', 'src/main_a.c', 'SConstruct', 'src/main_b.c']
FindSourceFiles()

# returns ['src/main_b.c', 'src/main_a.c' ]
FindSourceFiles('src')
</example_commands>

<para>
As you can see, build support files (&SConstruct; in the above example)
will also be returned by this function.
</para>
</summary>
</scons_function>

<scons_function name="Flatten">
<arguments>
(sequence)
</arguments>
<summary>
<para>
Takes a sequence (that is, a &Python; list or tuple)
that may contain nested sequences
and returns a flattened list containing
all of the individual elements in any sequence.
This can be helpful for collecting
the lists returned by calls to Builders;
other Builders will automatically
flatten lists specified as input,
but direct &Python; manipulation of
these lists does not.
</para>

<para>
Examples:
</para>

<example_commands>
foo = Object('foo.c')
bar = Object('bar.c')

# Because `foo' and `bar' are lists returned by the Object() Builder,
# `objects' will be a list containing nested lists:
objects = ['f1.o', foo, 'f2.o', bar, 'f3.o']

# Passing such a list to another Builder is all right because
# the Builder will flatten the list automatically:
Program(source = objects)

# If you need to manipulate the list directly using &Python;, you need to
# call Flatten() yourself, or otherwise handle nested lists:
for object in Flatten(objects):
    print(str(object))
</example_commands>
</summary>
</scons_function>

<scons_function name="GetBuildPath">
<arguments>
(file, [...])
</arguments>
<summary>
<para>
Returns the
&scons;
path name (or names) for the specified
<parameter>file</parameter>
(or files).
The specified
<parameter>file</parameter>
or files
may be
&scons;
Nodes or strings representing path names.
</para>
</summary>
</scons_function>

<scons_function name="Glob">
<arguments>
(pattern, [ondisk=True, source=False, strings=False, exclude=None])
</arguments>
<summary>
<para>
Returns a possibly empty list of Nodes (or strings) that match
pathname specification <parameter>pattern</parameter>.
<parameter>pattern</parameter> can be absolute,
top-relative,
or (most commonly) relative to the directory of the current
&SConscript; file.
&f-Glob; matches both files stored on disk and Nodes
which &SCons; already knows about, even if any corresponding
file is not currently stored on disk.
The environment method form (&f-env-Glob;)
performs string substitution on
<parameter>pattern</parameter>
and returns whatever matches the resulting expanded pattern.
The results are sorted, unlike for the similar &Python;
<systemitem>glob.glob</systemitem> function,
to ensure build order will be stable.
</para>

<para>
<parameter>pattern</parameter>
can contain POSIX-style shell metacharacters for matching:
</para>

<informaltable rowsep="1" colsep="1" frame="topbot">
<tgroup cols="2">
<thead>
  <row>
    <entry>Pattern</entry>
    <entry>Meaning</entry>
  </row>
</thead>
<tbody>
  <row>
    <entry><literal>*</literal></entry>
    <entry>matches everything</entry>
  </row>
  <row>
      <entry><literal>?</literal></entry>
      <entry>matches any single character</entry>
  </row>
  <row>
      <entry><literal>[seq]</literal></entry>
      <entry>matches any character in <emphasis>seq</emphasis>
      (can be a list or a range).</entry>
  </row>
  <row>
      <entry><literal>[!seq]</literal></entry>
      <entry>matches any character not in <emphasis>seq</emphasis></entry>
  </row>
</tbody>
</tgroup>
</informaltable>

<para>
For a literal match, wrap the metacharacter in brackets to
escape the normal behavior.
For example, <literal>'[?]'</literal> matches the character
<literal>'?'</literal>.
</para>

<para>
Filenames starting with a dot are specially handled -
they can only be matched by patterns that start with a dot
(or have a dot immediately following a pathname separator
character, or slash), they are not not matched by the metacharacters.
Metacharacter matches also do not span directory separators.
</para>

<para>
&f-Glob;
understands repositories
(see the
&f-link-Repository;
function)
and source directories
(see the
&f-link-VariantDir;
function)
and returns a Node (or string, if so configured) match
in the local (SConscript) directory
if a matching Node is found
anywhere in a corresponding
repository or source directory.
</para>

<para>
If the optional
<parameter>ondisk</parameter>
argument evaluates false,
the search for matches on disk is disabled,
and only matches from
already-configured File or Dir Nodes are returned.
The default is to return Nodes for
matches on disk as well.
</para>

<para>
If the optional
<parameter>source</parameter>
argument evaluates true,
and the local directory is a variant directory,
then &f-Glob; returns Nodes from
the corresponding source directory,
rather than the local directory.
<!-- XXX what about generated files that don't exist in src but will be sources? -->
</para>

<para>
If the optional
<parameter>strings</parameter>
argument evaluates true,
&f-Glob;
returns matches as strings, rather than Nodes.
The returned strings will be relative to
the local (SConscript) directory.
(Note that while this may make it easier to perform
arbitrary manipulation of file names,
it loses the context &SCons; would have in the Node,
so if the returned strings are
passed to a different
&SConscript;
file,
any Node translation there will be relative
to that
&SConscript;
directory,
not to the original
&SConscript;
directory.)
</para>

<para>
The optional
<parameter>exclude</parameter>
argument may be set to a pattern or a list of patterns
describing files or directories
to filter out of the match list.
Elements matching a least one specified pattern will be excluded.
These patterns use the same syntax as for
<parameter>pattern</parameter>.
</para>

<para>
Examples:
</para>

<example_commands>
Program("foo", Glob("*.c"))
Zip("/tmp/everything", Glob(".??*") + Glob("*"))
sources = Glob("*.cpp", exclude=["os_*_specific_*.cpp"]) \
    + Glob("os_%s_specific_*.cpp" % currentOS)
</example_commands>

</summary>
</scons_function>

<!--
<scons_function name="GlobalBuilders">
<arguments signature="global">
(flag)
</arguments>
<summary>
<para>
When
<parameter>flag</parameter>
is non-zero,
adds the names of the default builders
(Program, Library, etc.)
to the global name space
so they can be called without an explicit &consenv;.
(This is the default.)
When
<parameter>flag</parameter>
is zero,
the names of the default builders are removed
from the global name space
so that an explicit &consenv; is required
to call all builders.
</para>
</summary>
</scons_function>
-->

<scons_function name="Ignore">
<arguments>
(target, dependency)
</arguments>
<summary>
<para>
Ignores <parameter>dependency</parameter>
when deciding if
<parameter>target</parameter> needs to be rebuilt.
<parameter>target</parameter> and
<parameter>dependency</parameter>
can each be a single filename or Node
or a list of filenames or Nodes.
</para>

<para>
&f-Ignore; can also be used to
remove a target from the default build
by specifying the directory the target will be built in as
<parameter>target</parameter>
and the file you want to skip selecting for building as
<parameter>dependency</parameter>.
Note that this only removes the target from
the default target selection algorithm:
if it is a dependency of another object being
built &SCons; still builds it normally.
See the third and forth examples below.
</para>

<para>
Examples:
</para>

<example_commands>
env.Ignore('foo', 'foo.c')
env.Ignore('bar', ['bar1.h', 'bar2.h'])
env.Ignore('.', 'foobar.obj')
env.Ignore('bar', 'bar/foobar.obj')
</example_commands>
</summary>
</scons_function>

<scons_function name="Literal">
<arguments>
(string)
</arguments>
<summary>
<para>
The specified
<parameter>string</parameter>
will be preserved as-is
and not have &consvars; expanded.
</para>
</summary>
</scons_function>

<scons_function name="Local">
<arguments>
(targets)
</arguments>
<summary>
<para>
The specified
<parameter>targets</parameter>
will have copies made in the local tree,
even if an already up-to-date copy
exists in a repository.
Returns a list of the target Node or Nodes.
</para>
</summary>
</scons_function>

<!--
<scons_function name="MergeShellPaths">
<arguments signature="env">
( arg ", [" prepend ])
</arguments>
<summary>
<para>
Merges the elements of the specified
<parameter>arg</parameter>,
which must be a dictionary, to the construction
environment's copy of the shell environment
in env['ENV'].
(This is the environment which is passed
to subshells spawned by SCons.)
Note that
<parameter>arg</parameter>
must be a single value,
so multiple strings must
be passed in as a list,
not as separate arguments to
&f-MergeShellPaths;.
</para>

<para>
New values are prepended to the environment variable by default,
unless prepend=0 is specified.
Duplicate values are always eliminated,
since this function calls
&f-link-AppendENVPath;
or
&f-link-PrependENVPath;
depending on the
<parameter>prepend</parameter>
argument.  See those functions for more details.
</para>

<para>
Examples:
</para>

<example_commands>
# Prepend a path to the shell PATH.
env.MergeShellPaths({'PATH': '/usr/local/bin'})
# Append two dirs to the shell INCLUDE.
env.MergeShellPaths({'INCLUDE': ['c:/inc1', 'c:/inc2']}, prepend=0)
</example_commands>
</summary>
</scons_function>
-->

<scons_function name="MergeFlags">
<arguments signature="env">
(arg, [unique])
</arguments>
<summary>
<para>
Merges values from
<parameter>arg</parameter>
into &consvars; in <parameter>env</parameter>.
If <parameter>arg</parameter> is a dictionary,
each key-value pair represents a
&consvar; name and the corresponding flags to merge.
If <parameter>arg</parameter>
is not a dictionary,
&MergeFlags; attempts to convert it to one
before the values are merged.
&f-link-env-ParseFlags; is used for this,
so values to be converted are subject to the
same limitations:
&ParseFlags; has knowledge of which &consvars; certain
flags should go to, but not all;
and only for GCC and compatible compiler chains.
<parameter>arg</parameter>
must be a single object,
so to pass multiple strings,
enclose them in a list.
</para>

<para>
If <literal>unique</literal> is true (the default),
duplicate values are not retained.
In case of duplication,
any &consvar; names that end in
<literal>PATH</literal>
keep the left-most value so the
path search order is not altered.
All other &consvars; keep
the right-most value.
If <literal>unique</literal> is false,
values are appended even if they are duplicates.
</para>

<para>
Examples:
</para>

<example_commands>
# Add an optimization flag to $CCFLAGS.
env.MergeFlags({'CCFLAGS': '-O3'})

# Combine the flags returned from running pkg-config with an optimization
# flag and merge the result into the construction variables.
env.MergeFlags(['!pkg-config gtk+-2.0 --cflags', '-O3'])

# Combine an optimization flag with the flags returned from running pkg-config
# for two distinct packages and merge into the construction variables.
env.MergeFlags(
    [
        '-O3',
        '!pkg-config gtk+-2.0 --cflags --libs',
        '!pkg-config libpng12 --cflags --libs',
    ]
)
</example_commands>
</summary>
</scons_function>

<scons_function name="NoCache">
<arguments>
(target, ...)
</arguments>
<summary>
<para>
Specifies a list of files which should
<emphasis>not</emphasis>
be cached whenever the
&f-link-CacheDir;
method has been activated.
The specified targets may be a list
or an individual target.
</para>

<para>
Multiple files should be specified
either as separate arguments to the
&f-NoCache;
method, or as a list.
&f-NoCache;
will also accept the return value of any of the &consenv;
Builder methods.
</para>

<para>
Calling
&f-NoCache;
on directories and other non-File Node types has no effect because
only File Nodes are cached.
</para>

<para>
Examples:
</para>

<example_commands>
NoCache('foo.elf')
NoCache(env.Program('hello', 'hello.c'))
</example_commands>
</summary>
</scons_function>

<scons_function name="NoClean">
<arguments>
(targets, ...)
</arguments>
<summary>
<para>
Specifies files or directories which should not
be removed whenever a specified
<parameter>target</parameter> (or its dependencies)
is selected and clean mode is active
(<link linkend="opt-clean"><option>-c</option></link>
command line option).
<parameter>targets</parameter>
may be one or more file or directory names
or nodes,
and/or lists of names or nodes.
&f-NoClean; can be called multiple times.
</para>

<para>
Calling
&f-NoClean;
for a target overrides calling
&f-link-Clean;
for the same target,
so any targets passed to both functions will
<emphasis>not</emphasis>
be removed in clean mode.
</para>

<para>
Examples:
</para>

<example_commands>
NoClean('foo.elf')
NoClean(env.Program('hello', 'hello.c'))
</example_commands>
</summary>
</scons_function>

<scons_function name="ParseConfig">
<arguments signature="env">
(command, [function, unique])
</arguments>
<summary>
<para>
Updates the current &consenv; with the values extracted
from the output of running external <parameter>command</parameter>,
by passing it to a helper <parameter>function</parameter>.
<parameter>command</parameter> may be a string
or a list of strings representing the command and
its arguments.
If <parameter>function</parameter>
is omitted or <constant>None</constant>,
&f-link-env-MergeFlags; is used.
By default,
duplicate values are not
added to any &consvars;;
you can specify
<parameter>unique=False</parameter>
to allow duplicate values to be added.
</para>

<para>
<parameter>command</parameter> is executed using the
SCons execution environment (that is, the &consvar;
&cv-link-ENV; in the current &consenv;).
If <parameter>command</parameter> needs additional information
to operate properly, that needs to be set in the execution environment.
For example, <command>pkg-config</command>
may need a custom value set in the <envar>PKG_CONFIG_PATH</envar>
environment variable.
</para>

<para>
&f-env-MergeFlags; needs to understand
the output produced by <parameter>command</parameter>
in order to distribute it to appropriate &consvars;.
&f-env-MergeFlags; uses a separate function to
do that processing -
see &f-link-env-ParseFlags; for the details, including
a table of options and corresponding &consvars;.
To provide alternative processing of the output of
<parameter>command</parameter>,
you can supply a custom
<parameter>function</parameter>,
which must accept three arguments:
the &consenv; to modify,
a string argument containing the output from running
<parameter>command</parameter>,
and the optional
<parameter>unique</parameter> flag.
</para>
</summary>
</scons_function>

<scons_function name="ParseDepends">
<arguments>
(filename, [must_exist, only_one])
</arguments>
<summary>
<para>
Parses the contents of <parameter>filename</parameter>
as a list of dependencies in the style of
&Make;
or
<application>mkdep</application>,
and explicitly establishes all of the listed dependencies.
</para>

<para>
By default,
it is not an error
if <parameter>filename</parameter>
does not exist.
The optional
<parameter>must_exist</parameter>
argument may be set to <constant>True</constant>
to have &SCons;
raise an exception if the file does not exist,
or is otherwise inaccessible.
</para>

<para>
The optional
<parameter>only_one</parameter>
argument may be set to <constant>True</constant>
to have &SCons; raise an exception
if the file contains dependency
information for more than one target.
This can provide a small sanity check
for files intended to be generated
by, for example, the
<literal>gcc -M</literal>
flag,
which should typically only
write dependency information for
one output file into a corresponding
<filename>.d</filename>
file.
</para>

<para>
<parameter>filename</parameter>
and all of the files listed therein
will be interpreted relative to
the directory of the
&SConscript;
file which calls the
&f-ParseDepends;
function.
</para>
</summary>
</scons_function>

<scons_function name="ParseFlags">
<arguments signature="env">
(flags, ...)
</arguments>
<summary>
<para>
Parses one or more strings containing
typical command-line flags for GCC-style tool chains
and returns a dictionary with the flag values
separated into the appropriate SCons &consvars;.
Intended as a companion to the
&f-link-env-MergeFlags;
method, but allows for the values in the returned dictionary
to be modified, if necessary,
before merging them into the &consenv;.
(Note that
&f-env-MergeFlags;
will call this method if its argument is not a dictionary,
so it is usually not necessary to call
&f-env-ParseFlags;
directly unless you want to manipulate the values.)
</para>

<para>
If the first character in any string is
an exclamation mark (<literal>!</literal>),
the rest of the string is executed as a command,
and the output from the command is
parsed as GCC tool chain command-line flags
and added to the resulting dictionary.
This can be used to call a <filename>*-config</filename>
command typical of the POSIX programming environment
(for example,
<command>pkg-config</command>).
Note that such a command is executed using the
SCons execution environment;
if the command needs additional information,
that information needs to be explicitly provided.
See &f-link-ParseConfig; for more details.
</para>

<para>
Flag values are translated according to the prefix found,
and added to the following &consvars;:
</para>

<example_commands>
-arch                   CCFLAGS, LINKFLAGS
-D                      CPPDEFINES
-framework              FRAMEWORKS
-frameworkdir=          FRAMEWORKPATH
-fmerge-all-constants   CCFLAGS, LINKFLAGS
-fopenmp                CCFLAGS, LINKFLAGS
-fsanitize              CCFLAGS, LINKFLAGS
-include                CCFLAGS
-imacros                CCFLAGS
-isysroot               CCFLAGS, LINKFLAGS
-isystem                CCFLAGS
-iquote                 CCFLAGS
-idirafter              CCFLAGS
-I                      CPPPATH
-l                      LIBS
-L                      LIBPATH
-mno-cygwin             CCFLAGS, LINKFLAGS
-mwindows               LINKFLAGS
-openmp                 CCFLAGS, LINKFLAGS
-pthread                CCFLAGS, LINKFLAGS
-std=                   CFLAGS
-stdlib=                CXXFLAGS
-Wa,                    ASFLAGS, CCFLAGS
-Wl,-rpath=             RPATH
-Wl,-R,                 RPATH
-Wl,-R                  RPATH
-Wl,                    LINKFLAGS
-Wp,                    CPPFLAGS
-                       CCFLAGS
+                       CCFLAGS, LINKFLAGS
</example_commands>

<para>
Any other strings not associated with options
are assumed to be the names of libraries
and added to the
&cv-LIBS; &consvar;.
</para>

<para>
Examples (all of which produce the same result):
</para>

<example_commands>
dict = env.ParseFlags('-O2 -Dfoo -Dbar=1')
dict = env.ParseFlags('-O2', '-Dfoo', '-Dbar=1')
dict = env.ParseFlags(['-O2', '-Dfoo -Dbar=1'])
dict = env.ParseFlags('-O2', '!echo -Dfoo -Dbar=1')
</example_commands>
</summary>
</scons_function>

<scons_function name="Platform">
<arguments signature="global">
(plat)
</arguments>
<arguments signature="env">
(plat)
</arguments>
<summary>
<para>
When called as a global function,
returns a callable platform object
selected by <parameter>plat</parameter>
(defaults to the detected platform for the
current system)
that can be used to initialize
a &consenv; by passing it as the
<parameter>platform</parameter> keyword argument to the
&f-link-Environment; function.
</para>

<para>
Example:
</para>

<example_commands>
env = Environment(platform=Platform('win32'))
</example_commands>

<para>
When called as a method of an environment,
calls the platform object indicated by
<parameter>plat</parameter>
to update that environment.
</para>

<example_commands>
env.Platform('posix')
</example_commands>

<para>
See the manpage section "Construction Environments" for more details.
</para>
</summary>
</scons_function>

<scons_function name="Prepend">
<arguments signature="env">
(key=val, [...])
</arguments>
<summary>
<para>
Prepend values to &consvars; in the current &consenv;,
works like &f-link-env-Append; (see for details),
except that values are added to the front,
rather than the end, of any existing value of the &consvar;
</para>

<para>
Example:
</para>

<example_commands>
env.Prepend(CCFLAGS='-g ', FOO=['foo.yyy'])
</example_commands>

<para>
See also &f-link-env-Append;,
&f-link-env-AppendUnique;
and &f-link-env-PrependUnique;.
</para>
</summary>
</scons_function>

<scons_function name="PrependENVPath">
<arguments signature="env">
(name, newpath, [envname, sep, delete_existing=True])
</arguments>
<summary>
<para>
Prepend directory paths from
<parameter>newpath</parameter> to
a search-path entry <parameter>name</parameter>
in &consvar; <parameter>envname</parameter>
in the current enviromment (<parameter>env</parameter>).
If <parameter>envname</parameter> is not given,
the default is <literal>"ENV"</literal>
(see &cv-link-ENV;).
<parameter>envname</parameter> is expected
to refer to a dictionary-like object;
if it does not exist in <parameter>env</parameter>
it will be created as an initially empty dict.
<parameter>newpath</parameter>
may be specified as a string,
a directory node, or a list of strings.
If a string, it may contain multiple paths separated
by the system path separator
(<systemitem>os.pathsep</systemitem>),
or, if specified, by the value of <parameter>sep</parameter>.
Top-relative path strings (starting with <literal>#</literal>) are recognized.
The type of the existing value
of <parameter>name</parameter> is preserved.
</para>

<para>
Paths will only appear once.
Duplicate paths in <parameter>newpath</parameter> are removed,
preserving the first occurrence to maintain path order.
If <parameter>delete_existing</parameter> is true (the default),
existing duplicates are removed before prepending,
otherwise, new duplicates are skipped.
During comparisons, paths are normalized, to avoid
issues with case differences (on case-insensitive filesystems)
and with relative paths that may refer back to the same directory.
The stored values are not modified by this process.
</para>

<para>
Example:
</para>

<example_commands>
print('before:', env['ENV']['INCLUDE'])
include_path = '/foo/bar:/foo'
env.PrependENVPath('INCLUDE', include_path)
print('after:', env['ENV']['INCLUDE'])
</example_commands>

<para>Yields:</para>

<screen>
before: /biz:/foo
after: /foo/bar:/foo:/biz
</screen>

<para>
See also &f-link-env-AppendENVPath;.
</para>

</summary>
</scons_function>

<scons_function name="PrependUnique">
<arguments signature="env">
(key=val, [...], [delete_existing=False])
</arguments>
<summary>
<para>
Prepend values to &consvars; in the current &consenv;,
maintaining uniqueness.
Works like &f-link-env-Append;,
except that values are added to the front,
rather than the end, of the &consvar;,
and values that would become duplicates
are not added.
If <parameter>delete_existing</parameter>
is set to a true value, then for any duplicate,
the existing instance of <parameter>val</parameter> is first removed,
then <parameter>val</parameter> is inserted,
having the effect of moving it to the front.
</para>

<para>
Example:
</para>

<example_commands>
env.PrependUnique(CCFLAGS='-g', FOO=['foo.yyy'])
</example_commands>

<para>
See also &f-link-env-Append;,
&f-link-env-AppendUnique;
and &f-link-env-Prepend;.
</para>
</summary>
</scons_function>

<scons_function name="PyPackageDir">
<arguments>
(modulename)
</arguments>
<summary>
<para>
Finds the location of <parameter>modulename</parameter>,
which can be a string or a sequence of strings,
each representing the name of a &Python; module.
Construction variables are expanded in
<parameter>modulename</parameter>.
Returns a Directory Node (see &f-link-Dir;),
or a list of Directory Nodes if
<parameter>modulename</parameter> is a sequence.
<literal>None</literal> is returned for any module not found.
</para>

<para>
When a Tool module which is installed as a
&Python; module is used, you need
to specify a <parameter>toolpath</parameter> argument to
&f-link-Tool;,
&f-link-Environment;
or &f-link-Clone;,
as tools outside the standard project locations
(<filename>site_scons/site_tools</filename>)
will not be found otherwise.
Using &f-PyPackageDir; allows this path to be
discovered at runtime instead of hardcoding the path.
</para>

<para>
Example:
</para>

<example_commands>
env = Environment(
    tools=["default", "ExampleTool"],
    toolpath=[PyPackageDir("example_tool")]
)
</example_commands>
</summary>
</scons_function>

<scons_function name="Replace">
<arguments signature="env">
(key=val, [...])
</arguments>
<summary>
<para>
Replaces &consvars; in the Environment
with the specified keyword arguments.
</para>

<para>
Example:
</para>

<example_commands>
env.Replace(CCFLAGS='-g', FOO='foo.xxx')
</example_commands>
</summary>
</scons_function>

<scons_function name="Repository">
<arguments>
(directory)
</arguments>
<summary>
<para>
Sets
<parameter>directory</parameter>
as a repository to be searched for files contributing to the build.
Multiple calls to
&f-Repository;
are allowed,
with repositories searched in the given order.
Repositories specified via command-line option
have higher priority.
</para>

<para>
In
&scons;,
a repository is partial or complete copy of the source tree,
from the top-level directory down,
containing source files
that can be used to build targets in
the current worktree.
Repositories can also contain derived files.
An example might be an official source tree maintained by an integrator.
If a repository contains derived files,
they should be the result of building with &SCons;,
so a signature database (sconsign) is present
in the repository,
allowing better decisions on whether they are
up-to-date or not.
</para>

<para>
Note that if an up-to-date derived file
already exists in a repository,
&scons; will
<emphasis>not</emphasis>
make a copy in the local directory tree.
If you need a local copy to be made,
use the &f-link-Local; method.
</para>
</summary>
</scons_function>

<scons_function name="Requires">
<arguments>
(target, prerequisite)
</arguments>
<summary>
<para>
Specifies an order-only relationship
between <parameter>target</parameter>
and <parameter>prerequisite</parameter>.
The prerequisites
will be (re)built, if necessary,
<emphasis>before</emphasis>
the target file(s),
but the target file(s) do not actually
depend on the prerequisites
and will not be rebuilt simply because
the prerequisite file(s) change.
<parameter>target</parameter> and
<parameter>prerequisite</parameter> may each
be a string or Node, or a list of strings or Nodes.
If there are multiple
<parameter>target</parameter> values,
the prerequisite(s) are added to each one.
Returns a list of the affected target nodes.
</para>

<para>
Example:
</para>

<example_commands>
env.Requires('foo', 'file-that-must-be-built-before-foo')
</example_commands>
</summary>
</scons_function>

<scons_function name="Scanner">
<arguments>
(function, [name, argument, skeys, path_function, node_class, node_factory, scan_check, recursive])
</arguments>
<summary>
<para>
Creates a Scanner object for
the specified
<parameter>function</parameter>.
See manpage section "Scanner Objects"
for a complete explanation of the arguments and behavior.
</para>
</summary>
</scons_function>

<scons_function name="SConscriptChdir">
<arguments signature="global">
(value)
</arguments>
<summary>
<para>
By default,
&scons;
changes its working directory
to the directory in which each
subsidiary SConscript file lives
while reading and processing that script.
This behavior may be disabled
by specifying an argument which
evaluates false, in which case
&scons;
will stay in the top-level directory
while reading all SConscript files.
(This may be necessary when building from repositories,
when all the directories in which SConscript files may be found
don't necessarily exist locally.)
You may enable and disable
this ability by calling
&f-SConscriptChdir;
multiple times.
</para>

<para>
Example:
</para>

<example_commands>
SConscriptChdir(False)
SConscript('foo/SConscript')	# will not chdir to foo
SConscriptChdir(True)
SConscript('bar/SConscript')	# will chdir to bar
</example_commands>
</summary>
</scons_function>

<scons_function name="SConsignFile">
<arguments>
([name, dbm_module])
</arguments>
<summary>
<para>
Specify where to store the &SCons; file signature database,
and which database format to use.
This may be useful to specify alternate
database files and/or file locations for different types of builds.
</para>
<para>
The optional <parameter>name</parameter> argument
is the base name of the database file(s).
If not an absolute path name,
these are placed relative to the directory containing the
top-level &SConstruct; file.
The default is
<filename>.sconsign</filename>.
The actual database file(s) stored on disk
may have an appropriate suffix appended
by the chosen
<parameter>dbm_module</parameter>
</para>
<para>
The optional <parameter>dbm_module</parameter>
argument specifies which
&Python; database module to use
for reading/writing the file.
The module must be imported first;
then the imported module name
is passed as the argument.
The default is a custom
<systemitem>SCons.dblite</systemitem>
module that uses pickled
&Python; data structures,
which works on all &Python; versions.
See documentation of the &Python;
<systemitem>dbm</systemitem> module
for other available types.
</para>
<para>
If called with no arguments,
the database will default to
<filename>.sconsign.dblite</filename>
in the top directory of the project,
which is also the default if
if &f-SConsignFile; is not called.
</para>
<para>
The setting is global, so the only difference
between the global function and the environment method form
is variable expansion on <parameter>name</parameter>.
There should only be one active call to this
function/method in a given build setup.
</para>
<para>
If
<parameter>name</parameter>
is set to
<constant>None</constant>,
&scons;
will store file signatures
in a separate
<filename>.sconsign</filename>
file in each directory,
not in a single combined database file.
This is a backwards-compatibility measure to support
what was the default behavior
prior to &SCons; 0.97 (i.e. before 2008).
Use of this mode is discouraged and may be
deprecated in a future &SCons; release.
</para>

<para>
Examples:
</para>

<example_commands>
# Explicitly stores signatures in ".sconsign.dblite"
# in the top-level SConstruct directory (the default behavior).
SConsignFile()

# Stores signatures in the file "etc/scons-signatures"
# relative to the top-level SConstruct directory.
# SCons will add a database suffix to this name.
SConsignFile("etc/scons-signatures")

# Stores signatures in the specified absolute file name.
# SCons will add a database suffix to this name.
SConsignFile("/home/me/SCons/signatures")

# Stores signatures in a separate .sconsign file
# in each directory.
SConsignFile(None)

# Stores signatures in a GNU dbm format .sconsign file
import dbm.gnu
SConsignFile(dbm_module=dbm.gnu)
</example_commands>
</summary>
</scons_function>

<scons_function name="SetDefault">
<arguments signature="env">
(key=val, [...])
</arguments>
<summary>
<para>
Sets &consvars; to default values specified with the keyword
arguments if (and only if) the variables are not already set.
The following statements are equivalent:
</para>

<example_commands>
env.SetDefault(FOO='foo')
if 'FOO' not in env:
    env['FOO'] = 'foo'
</example_commands>
</summary>
</scons_function>

<scons_function name="SideEffect">
<arguments>
(side_effect, target)
</arguments>
<summary>
<para>
Declares
<parameter>side_effect</parameter>
as a side effect of building
<parameter>target</parameter>.
Both
<parameter>side_effect</parameter>
and
<parameter>target</parameter>
can be a list, a file name, or a node.
A side effect is a target file that is created or updated
as a side effect of building other targets.
For example, a Windows PDB
file is created as a side effect of building the .obj
files for a static library,
and various log files are created updated
as side effects of various TeX commands.
If a target is a side effect of multiple build commands,
&scons;
will ensure that only one set of commands
is executed at a time.
Consequently, you only need to use this method
for side-effect targets that are built as a result of
multiple build commands.
</para>

<para>
Because multiple build commands may update
the same side effect file,
by default the
<parameter>side_effect</parameter>
target is
<emphasis>not</emphasis>
automatically removed
when the
<parameter>target</parameter>
is removed by the
<option>-c</option>
option.
(Note, however, that the
<parameter>side_effect</parameter>
might be removed as part of
cleaning the directory in which it lives.)
If you want to make sure the
<parameter>side_effect</parameter>
is cleaned whenever a specific
<parameter>target</parameter>
is cleaned,
you must specify this explicitly
with the
&f-link-Clean;
or
&f-env-Clean;
function.
</para>

<para>
This function returns the list of side effect Node objects that were successfully added.
If the list of side effects contained any side effects that had already been added,
they are not added and included in the returned list.
</para>
</summary>
</scons_function>

<scons_function name="Split">
<arguments>(arg)</arguments>
<summary>
<para>
If <parameter>arg</parameter> is a string,
splits on whitespace and returns a list of
strings without whitespace.
This mode is the most common case,
and can be used to split a list of filenames
(for example) rather than having to type them as a
list of individually quoted words.
If <parameter>arg</parameter> is a list or tuple
returns the list or tuple unchanged.
If <parameter>arg</parameter> is any other type of object,
returns a list containing just the object.
These non-string cases do not actually do any spliting,
but allow an argument variable to be passed to
&f-Split; without having to first check its type.
</para>

<para>
Example:
</para>

<example_commands>
files = Split("f1.c f2.c f3.c")
files = env.Split("f4.c f5.c f6.c")
files = Split("""
    f7.c
    f8.c
    f9.c
""")
</example_commands>
</summary>
</scons_function>

<scons_function name="subst">
<arguments signature="env">
(input, [raw, target, source, conv])
</arguments>
<summary>
<para>
Performs &consvar; interpolation
(<firstterm>substitution</firstterm>)
on <parameter>input</parameter>,
which can be a string or a sequence.
Substitutable elements take the form
<literal>${<replaceable>expression</replaceable>}</literal>,
although if there is no ambiguity in recognizing the element,
the braces can be omitted.
A literal <emphasis role="bold">$</emphasis> can be entered by
using <emphasis role="bold">$$</emphasis>.
</para>

<para>
By default,
leading or trailing white space will
be removed from the result,
and all sequences of white space
will be compressed to a single space character.
Additionally, any
<literal>$(</literal>
and
<literal>$)</literal>
character sequences will be stripped from the returned string,
The optional
<parameter>raw</parameter>
argument may be set to
<literal>1</literal>
if you want to preserve white space and
<literal>$(</literal>-<literal>$)</literal>
sequences.
The
<parameter>raw</parameter>
argument may be set to
<literal>2</literal>
if you want to additionally discard
all characters between any
<literal>$(</literal>
and
<literal>$)</literal>
pairs
(as is done for signature calculation).
</para>

<para>
If <parameter>input</parameter> is a sequence
(list or tuple),
the individual elements of
the sequence will be expanded,
and the results will be returned as a list.
</para>

<para>
The optional
<parameter>target</parameter>
and
<parameter>source</parameter>
keyword arguments
must be set to lists of
target and source nodes, respectively,
if you want the
&cv-TARGET;,
&cv-TARGETS;,
&cv-SOURCE;
and
&cv-SOURCES;
to be available for expansion.
This is usually necessary if you are
calling
&f-env-subst;
from within a &Python; function used
as an SCons action.
</para>

<para>
Returned string values or sequence elements
are converted to their string representation by default.
The optional
<parameter>conv</parameter>
argument
may specify a conversion function
that will be used in place of
the default.
For example, if you want &Python; objects
(including SCons Nodes)
to be returned as &Python; objects,
you can use a &Python;
lambda expression to pass in an unnamed function
that simply returns its unconverted argument.
</para>

<para>
Example:
</para>

<example_commands>
print(env.subst("The C compiler is: $CC"))

def compile(target, source, env):
    sourceDir = env.subst(
        "${SOURCE.srcdir}",
        target=target,
        source=source
    )

source_nodes = env.subst('$EXPAND_TO_NODELIST', conv=lambda x: x)
</example_commands>
</summary>
</scons_function>

<scons_function name="Tool">
<arguments>
(name, [toolpath, key=value, ...])
</arguments>
<summary>

<para>
Locates the tool specification module <parameter>name</parameter>
and returns a callable tool object for that tool.
When the environment method (&f-env-Tool;) form is used,
the tool object is automatically called before the method returns
to update <varname>env</varname>,
and <parameter>name</parameter> is
appended to the &cv-link-TOOLS;
&consvar; in that environment.
When the global function &f-Tool; form is used,
the tool object is constructed but not called,
as it lacks the context of an environment to update,
and the returned object needs to be used to arrange for the call.
</para>

<para>
The tool module is searched for in the tool search paths (see the
<emphasis role="bold">Tools</emphasis> section in the manual page
for details)
and in any paths specified by the optional
<parameter>toolpath</parameter> parameter,
which must be a list of strings.
If <parameter>toolpath</parameter> is omitted,
the <parameter>toolpath</parameter>
supplied when the environment was created,
if any, is used.
</para>

<para>
Any remaining keyword arguments are saved in
the tool object,
and will be passed to the tool module's
<function>generate</function> function
when the tool object is actually called.
The <function>generate</function> function
can update the &consenv; with &consvars; and arrange
any other initialization
needed to use the mechanisms that tool describes,
and can use these extra arguments to help
guide its actions.
</para>

<para>
<emphasis>Changed in version  4.2:</emphasis>
&f-env-Tool; now returns the tool object,
previously it did not return (i.e. returned <constant>None</constant>).
</para>

<para>
Examples:
</para>

<example_commands>
env.Tool('gcc')
env.Tool('opengl', toolpath=['build/tools'])
</example_commands>

<para>
The returned tool object can be passed to an
&f-link-Environment; or &f-link-Clone; call
as part of the <parameter>tools</parameter> keyword argument,
in which case the tool is applied to the environment being constructed,
or it can be called directly,
in which case a &consenv; to update must be
passed as the argument.
Either approach will also update the
&cv-TOOLS; &consvar;.
</para>

<para>
Examples:
</para>

<example_commands>
env = Environment(tools=[Tool('msvc')])

env = Environment()
msvctool = Tool('msvc')
msvctool(env)  # adds 'msvc' to the TOOLS variable
gltool = Tool('opengl', toolpath = ['tools'])
gltool(env)  # adds 'opengl' to the TOOLS variable
</example_commands>
</summary>
</scons_function>

<scons_function name="Value">
<arguments>
(value, [built_value], [name])
</arguments>
<summary>
<para>
Returns a Node object representing the specified &Python;
<parameter>value</parameter>.
Value Nodes can be used as dependencies of targets.
If the string representation of the Value Node
changes between &SCons; runs, it is considered
out-of-date and any targets depending on it will be rebuilt.
Since Value Nodes have no filesystem representation,
timestamps are not used; the timestamp deciders
perform the same content-based up to date check.
</para>
<para>
The optional
<parameter>built_value</parameter>
argument can be specified
when the Value Node is created
to indicate the Node should already be considered "built."
</para>

<para>
The optional <parameter>name</parameter> parameter can be provided as an
alternative name for the resulting <literal>Value</literal> node;
this is advised if the <parameter>value</parameter> parameter
cannot be converted to a string.
</para>

<para>
Value Nodes have a
<methodname>write</methodname>
method that can be used to "build" a Value Node
by setting a new value.
The corresponding
<methodname>read</methodname>
method returns the built value of the Node.
</para>

<para>
<emphasis>Changed in version 4.0:</emphasis>
the <parameter>name</parameter> parameter was added.
</para>

<para>
Examples:
</para>

<!-- TODO fix second example or replace - still doesn't work -->
<example_commands>
env = Environment()

def create(target, source, env):
    """Action function to create a file from a Value.

    Writes 'prefix=$SOURCE' into the file name given as $TARGET.
    """
    with open(target[0], 'wb') as f:
        f.write(b'prefix=' + source[0].get_contents() + b'\n')

# Fetch the prefix= argument, if any, from the command line.
# Use /usr/local as the default.
prefix = ARGUMENTS.get('prefix', '/usr/local')

# Attach builder named Config to the construction environment
# using the 'create' action function above.
env['BUILDERS']['Config'] = Builder(action=create)
env.Config(target='package-config', source=Value(prefix))

def build_value(target, source, env):
    """Action function to "build" a Value.

    Writes contents of $SOURCE into $TARGET, thus updating if it existed.
    """
    target[0].write(source[0].get_contents())

output = env.Value('before')
input = env.Value('after')

# Attach a builder named UpdateValue to the construction environment
# using the 'build_value' action function above.
env['BUILDERS']['UpdateValue'] = Builder(action=build_value)
env.UpdateValue(target=Value(output), source=Value(input))
</example_commands>
</summary>
</scons_function>

<scons_function name="VariantDir">
<arguments>
(variant_dir, src_dir, [duplicate])
</arguments>
<summary>
<para>
Sets up a mapping to define a variant build directory in
<parameter>variant_dir</parameter>.
<parameter>src_dir</parameter> must not be underneath
<parameter>variant_dir</parameter>.
A &f-VariantDir; mapping is global, even if called using the
&f-env-VariantDir; form.
&f-VariantDir;
can be called multiple times with the same
<parameter>src_dir</parameter>
to set up multiple variant builds with different options.
</para>

<para>
Note if <parameter>variant_dir</parameter>
is not under the project top directory,
target selection rules will not pick targets in the
variant directory unless they are explicitly specified.
</para>

<para>
When files in <parameter>variant_dir</parameter> are referenced,
&SCons; backfills as needed with files from <parameter>src_dir</parameter>
to create a complete build directory.
By default, &SCons;
physically duplicates the source files, SConscript files,
and directory structure as needed into the variant directory.
Thus, a build performed in the variant directory is guaranteed to be identical
to a build performed in the source directory even if
intermediate source files are generated during the build,
or if preprocessors or other scanners search for included files
using paths relative to the source file,
or if individual compilers or other invoked tools are hard-coded
to put derived files in the same directory as source files.
Only the files &SCons; calculates are needed for the build are
duplicated into <parameter>variant_dir</parameter>.
If possible on the platform,
the duplication is performed by linking rather than copying.
This behavior is affected by the
<option>--duplicate</option>
command-line option.
</para>

<para>
Duplicating the source files may be disabled by setting the
<parameter>duplicate</parameter>
argument to
<constant>False</constant>.
This will cause
&SCons;
to invoke Builders using the path names of source files in
<parameter>src_dir</parameter>
and the path names of derived files within
<parameter>variant_dir</parameter>.
This is more efficient than duplicating,
and is safe for most builds;
revert to <literal>duplicate=True</literal>
if it causes problems.
</para>

<para>
&f-VariantDir;
works most naturally when used with a subsidiary SConscript file.
The subsidiary SConscript file must be called as if it were in
<parameter>variant_dir</parameter>,
regardless of the value of
<parameter>duplicate</parameter>.
When calling an SConscript file, you can use the
<parameter>exports</parameter> keyword argument
to pass parameters (individually or as an appropriately set up environment)
so the SConscript can pick up the right settings for that variant build.
The SConscript must &f-link-Import; these to use them. Example:
</para>

<example_commands>
env1 = Environment(...settings for variant1...)
env2 = Environment(...settings for variant2...)

# run src/SConscript in two variant directories
VariantDir('build/variant1', 'src')
SConscript('build/variant1/SConscript', exports={"env": env1})
VariantDir('build/variant2', 'src')
SConscript('build/variant2/SConscript', exports={"env": env2})
</example_commands>

<para>
See also the
&f-link-SConscript; function
for another way to specify a variant directory
in conjunction with calling a subsidiary SConscript file.
</para>

<para>
More examples:
</para>

<example_commands>
# use names in the build directory, not the source directory
VariantDir('build', 'src', duplicate=0)
Program('build/prog', 'build/source.c')

# this builds both the source and docs in a separate subtree
VariantDir('build', '.', duplicate=0)
SConscript(dirs=['build/src','build/doc'])

# same as previous example, but only uses SConscript
SConscript(dirs='src', variant_dir='build/src', duplicate=0)
SConscript(dirs='doc', variant_dir='build/doc', duplicate=0)
</example_commands>
</summary>
</scons_function>

<scons_function name="WhereIs">
<arguments>
(program, [path, pathext, reject])
</arguments>
<summary>
<para>
Searches for the specified executable
<parameter>program</parameter>,
returning the full path to the program
or <constant>None</constant>.
</para>
<para>
When called as a &consenv; method,
searches the paths in the
<parameter>path</parameter> keyword argument,
or if <constant>None</constant> (the default)
the paths listed in the &consenv;
(<varname>env</varname><literal>['ENV']['PATH']</literal>).
The external environment's path list
(<literal>os.environ['PATH']</literal>)
is used as a fallback if the key
<varname>env</varname><literal>['ENV']['PATH']</literal>
does not exist.
</para>
<para>
On Windows systems, searches for executable
programs with any of the file extensions listed in the
<parameter>pathext</parameter> keyword argument,
or if <constant>None</constant> (the default)
the pathname extensions listed in the &consenv;
(<varname>env</varname><literal>['ENV']['PATHEXT']</literal>).
The external environment's pathname extensions list
(<literal>os.environ['PATHEXT']</literal>)
is used as a fallback if the key
<varname>env</varname><literal>['ENV']['PATHEXT']</literal>
does not exist.
</para>
<para>
When called as a global function, uses the external
environment's path
<literal>os.environ['PATH']</literal>
and path extensions
<literal>os.environ['PATHEXT']</literal>,
respectively, if
<parameter>path</parameter> and
<parameter>pathext</parameter> are
<constant>None</constant>.
</para>
<para>
Will not select any
path name or names
in the optional
<parameter>reject</parameter>
list.
</para>

</summary>
</scons_function>

</sconsdoc>
