From 8b856a11f0719c8f14f96e714c6fa335139ae8842b03a13b447a91ec46d23ef4 Mon Sep 17 00:00:00 2001
From: OBS User unknown Copyright © 2004, 2005, 2006, 2007 Steven KnightSteven Knight
Glob
$LIBPATH
Node
Node
Decider
Decider
SourceSignatures
TargetSignatures
$CPPPATH
Depends
ParseDepends
+ FunctionIgnore
FunctionRequires
FunctionAlwaysBuild
Environment
Functionsubst
MethodDefaultEnvironment
FunctionClone
MethodReplace
MethodSetDefault
MethodAppend
MethodAppendUnique
MethodPrepend
MethodPrependUnique
MethodPATH
From the External EnvironmentPATH
Values in the Execution EnvironmentMergeFlags
FunctionSCONSFLAGS
Environment Variablevariable
=value
Build OptionsSeparating Compile Arguments into their Variables: the BoolOption
Build Option
ParseFlags FunctionEnumOption
Build OptionListOption
Build OptionPathOption
Build OptionPackageOption
Build OptionParseConfig
FunctionSCONSFLAGS
Environment VariableGetOption
FunctionSetOption
FunctionAddOption
Functionvariable
=value
Build VariablesUnknownVariables
Function- 12. 14. Platform-Independent File System Manipulation
- 12.1. 14.1. Copying Files or Directories: The
Copy
Factory - 12.2. 14.2. Deleting Files or Directories: The
Delete
Factory - 12.3. 14.3. Moving (Renaming) Files or Directories: The
Move
Factory - 12.4. 14.4. Updating the Modification Time of a File: The
Touch
Factory - 12.5. 14.5. Creating a Directory: The
Mkdir
Factory - 12.6. 14.6. Changing File or Directory Permissions: The
Chmod
Factory - 12.7. 14.7. Executing an action immediately: the
Execute
- 13. 15. Preventing Removal of TargetsControlling Removal of Targets
VariantDir
FunctionVariantDir
File17.6. Using Glob
with VariantDir
Builder
EnsurePythonVersion
FunctionEnsureSConsVersion
FunctionExit
FunctionFindFile
FunctionFlatten
FunctionGetLaunchDir
FunctionDump
Method$ python - Python 2.2.2 (#1, Feb 24 2003, 19:13:11) - [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 - Type "help", "copyright", "credits" or "license" for more information. - >>> ^Dpython -V + Python 2.5.1
@@ -1941,38 +2171,11 @@ CLASS="userinput" CLASS="screen" > C:\>python - Python 2.2.2 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 - Type "help", "copyright", "credits" or "license" for more information. - >>> ^Zpython -V + Python 2.5.1
- The >>> is the input prompt - for the Python interpreter. - The ^D and ^Z - represent the CTRL-D and CTRL-Z characters - that you will need to type to get out of the interpreter - before proceeding to installing SCons. - -
If Python is not installed on your system, you will see an error message @@ -1989,6 +2192,22 @@ CLASS="application"
+ (Note that the -V
option
+ was added to Python version 2.0,
+ so if your system only has an earlier version available
+ you may see an
+ "Unknown option: -V"
+ error message.)
+
+
The standard location for information about downloading and installing Python is @@ -2000,6 +2219,21 @@ TARGET="_top" See that page for information about how to download and install Python on your system. +
+ SCons will work with any version of Python from 1.5.2 or later. + If you need to install Python and have a choice, + we recommend using the most recent Python 2.5 version available. + Python 2.5 has significant improvements + the help speed up the performance of SCons'. +
Glob
- You can also use the Glob() function to find all files matching a - certain template, using standard the shell pattern matching - characters *, ?, and [abc] to match any of a, b, or c. [!abc] is - also supported, to match any character Glob function to find all files matching a + certain template, using the standard shell pattern matching + characters *, ? + and [abc] to match any of + a, b or c. + [!abc] is also supported, + to match any character except - a, b, or c. This makes many multi-source-file builds quite easy: + a, b or c. + This makes many multi-source-file builds quite easy:
- The SCons man page has more details on using Glob() with Variant - dirs and Repositories and returning strings rather than Nodes. + The SCons man page has more details on using
Glob
with Variant + directories and Repositories, and returning strings rather than Nodes.
list = Split('main.c file1.c file2.c') - Program('program', list) +> src_files = Split('main.c file1.c file2.c') + Program('program', src_files)
@@ -4000,10 +4277,10 @@ CLASS="function"
list = Split("""main.c - file1.c - file2.c""") - Program('program', list) +> src_files = Split("""main.c + file1.c + file2.c""") + Program('program', src_files)
@@ -4021,7 +4298,7 @@ CLASS="section" >
list = Split('main.c file1.c file2.c') - Program(target = 'program', source = list) +> src_files = Split('main.c file1.c file2.c') + Program(target = 'program', source = src_files)
@@ -4065,8 +4342,8 @@ CLASS="programlisting"
list = Split('main.c file1.c file2.c') - Program(source = list, target = 'program') +> src_files = Split('main.c file1.c file2.c') + Program(source = src_files, target = 'program')
@@ -4087,7 +4364,7 @@ CLASS="section" >
StaticLibrary
SharedLibrary
$LIBPATH
Node
Node
Decider
scons -Q hello - scons: `hello' is up to date. + cc -o hello.o -c hello.c + cc -o hello hello.o
@@ -5981,7 +6259,7 @@ CLASS="section" >
Decider
Note that in the function definition,
- the dependencydependency
(input file) is the first argument,
- and then the targettarget.
Both of these are passed to the functions as
SCons str()
.
- The third argument, prev_ni
+ The third argument, prev_ni
,
is an object that holds the
signature or timestamp information
that was recorded about the dependency
the last time the target was built.
+ A prev_ni
object can hold
+ different information,
+ depending on the type of thing that the
+ dependency
argument represents.
+ For normal files,
+ the prev_ni
object
+ has the following attributes:
The content signature,
+ or MD5 checksum, of the contents of the
+ dependency
+ file the list time the target
was built.
+
The size in bytes of the dependency
+ file the list time the target was built.
+
The modification time of the dependency
+ file the list time the target
was built.
+
Note that ignoring some of the arguments
in your custom
+ Note that the dependency
+ (the second argument to
+ in which case the dependency or dependencies
+ will be built before the target(s):
+
+
+ SCons has built-in scanners for a number of languages. Sometimes
+ these scanners fail to extract certain implicit dependencies due
+ to limitations of the scanner implementation.
+
+
+ The following example illustrates a case where the built-in C
+ scanner is unable to extract the implicit dependency on a header
+ file.
+
+
+ Apparently, the scanner does not know about the header dependency.
+ Being not a full-fledged C preprocessor, the scanner does not
+ expand the macro.
+
+
+ In these cases, you may also use the compiler to extract the
+ implicit dependencies.
+ The following example uses
+ Parsing dependencies from a compiler-generated
+ .d file has a chicken-and-egg problem, that
+ causes unnecessary rebuilds:
+
+
+ In the first pass, the dependency file is generated while the
+ object file is compiled. At that time, SCons does not know about
+ the dependency on foo.h. In the second pass,
+ the object file is regenerated because foo.h
+ is detected as a new dependency.
+
+
+
+ Occasionally,
+ it may be useful to specify that a certain
+ file or directory must, if necessary,
+ be built or created before some other target is built,
+ but that changes to that file or directory
+ do not
+ require that the target itself be rebuilt.
+ Such a relationship is called an
+ order-only dependency
+ because it only affects the order in which
+ things must be built--the dependency before the target--but
+ it is not a strict dependency relationship
+ because the target should not
+ change in response to changes in the dependent file.
+
+
+ For example, suppose that you want to create a file
+ every time you run a build
+ that identifies the time the build was performed,
+ the version number, etc.,
+ and which is included in every program that you build.
+ The version file's contents will change every build.
+ If you specify a normal dependency relationship,
+ then every program that depends on
+ that file would be rebuilt every time you ran SCons.
+ For example, we could use some Python code in
+ a SConstruct file to create a new version.c file
+ with a string containing the current date every time
+ we run SCons,
+ and then link a program with the resulting object file
+ by listing version.c in the sources:
+
+
+ If we list version.c as an actual source file,
+ though, then version.o
+ will get rebuilt every time we run SCons
+ (because the SConstruct file itself changes
+ the contents of version.c)
+ and the hello executable
+ will get re-linked every time
+ (because the version.o file changes):
+
+
+ One solution is to use the
+ Notice that because we can no longer list version.c
+ as one of the sources for the hello program,
+ we have to find some other way to get it into the link command line.
+ For this example, we're cheating a bit and stuffing the
+ object file name (extracted from version_obj
+ list returned by the
+ With these changes,
+ we get the desired behavior of
+ re-building the version.o file,
+ and therefore re-linking the hello executable,
+ only when the hello.c has changed:
+
+
- It is rare that all of the software in a large,
- complicated system needs to be built the same way.
- For example, different source files may need different options
- enabled on the command line,
- or different executable programs need to be linked
- with different libraries.
- environment
+ is a collection of values that
+ can affect how a program executes.
+ SCons accommodates these different build
- requirements by allowing you to create and
- configure multiple distinguishes between three
+ different types of environments
+ that can affect the behavior of SCons itself
+ (subject to the configuration in the SConscript files),
+ as well as the compilers and other tools it executes:
+
+
+ The external environment
+ is the set of variables in the user's environment
+ at the time the user runs SCons.
+ These variables are available within the SConscript files
+ through the Python os.environ dictionary.
+ See Section 7.1, below.
+
+
+ A construction environment
+ is a distinct object creating within
+ a SConscript file and
+ and which contains values that
+ affect how SCons decides
+ what action to use to build a target,
+ and even to define which targets
+ should be built from which sources.
+ One of the most powerful features of SCons
+ is the ability to create multiple construction environments,
+ including the ability to clone a new, customized
+ construction environment from an existing construction environment.
+ See Section 7.2, below.
+
+
+ An execution environment
+ is the values that SCons sets
+ when executing an external
+ command (such as a compiler or linker)
+ to build one or more targets.
+ Note that this is not the same as
+ the external environment
+ (see above).
+ See Section 7.3, below.
+
+
+ Unlike Make, SCons does not automatically
+ copy or import values between different environments
+ (with the exception of explicit clones of construction environments,
+ which inherit values from their parent).
+ This is a deliberate design choice
+ to make sure that builds are,
+ by default, repeatable regardless of
+ the values in the user's external environment.
+ This avoids a whole class of problems with builds
+ where a developer's local build works
+ because a custom variable setting
+ causes a different comiler or build option to be used,
+ but the checked-in change breaks the official build
+ because it uses different environment variable settings.
+
+
+ Note that the SConscript writer can
+ easily arrange for variables to be
+ copied or imported between environments,
+ and this is often very useful
+ (or even downright necessary)
+ to make it easy for developers
+ to customize the build in appropriate ways.
+ The point is not
+ that copying variables between different environments
+ is evil and must always be avoided.
+ Instead, it should be up to the
+ implementer of the build system
+ to make conscious choices
+ about how and when to import
+ a variable from one environment to another,
+ making informed decisions about
+ striking the right balance
+ between making the build
+ repeatable on the one hand
+ and convenient to use on the other.
+
+
+ The external environment
+ variable settings that
+ the user has in force
+ when executing SCons
+ are available through the normal Python
+
+ More usefully, you can use the
+
+ It is rare that all of the software in a large,
+ complicated system needs to be built the same way.
+ For example, different source files may need different options
+ enabled on the command line,
+ or different executable programs need to be linked
+ with different libraries.
+ SCons accommodates these different build
+ requirements by allowing you to create and
+ configure multiple construction environments
+ that control how the software is built.
+ A construction environment is an object
- that has a number of associated
- construction variables, each with a name and a value.
- (A construction environment also has an attached
- set of
- A construction environment is created by the
- By default, SCons initializes every
- new construction environment
- with a set of construction variables
- based on the tools that it finds on your system,
- plus the default set of builder methods
- necessary for using those tools.
- The construction variables
- are initialized with values describing
- the C compiler,
- the Fortran compiler,
- the linker,
- etc.,
- as well as the command lines to invoke them.
+ based on the tools that it finds on your system,
+ plus the default set of builder methods
+ necessary for using those tools.
+ The construction variables
+ are initialized with values describing
+ the C compiler,
+ the Fortran compiler,
+ the linker,
+ etc.,
+ as well as the command lines to invoke them.
-
- When you initialize a construction environment
- you can set the values of the
- environment's construction variables
- to control how a program is built.
- For example:
+ to control how a program is built.
+ For example:
-
- The construction environment in this example
- is still initialized with the same default
- construction variable values,
- except that the user has explicitly specified use of the
- GNU C compiler gcc,
- and further specifies that the -O2
- (optimization level two)
- flag should be used when compiling the object file.
- In other words, the explicit initializations of
-
- The real advantage of construction environments
- is that you can create as many different construction
- environments as you need,
- each tailored to a different way to build
- some piece of software or other file.
- If, for example, we need to build
- one program with the -O2 flag
- and another with the -g (debug) flag,
- we would do this like so:
-
-
- We can even use multiple construction environments to build
- multiple versions of a single program.
- If you do this by simply trying to use the
-
- Then SCons generates the following error:
-
-
- This is because the two
- Notice that each call to the
- Sometimes you want more than one construction environment
- to share the same values for one or more variables.
- Rather than always having to repeat all of the common
- variables when you create each construction environment,
- you can use the
- Like the
- Then our output would look like:
-
-
- You can fetch individual construction variables
- using the normal syntax
- for accessing individual named items in a Python dictionary:
+ You can fetch individual construction variables
+ using the normal syntax
+ for accessing individual named items in a Python dictionary:
-
- This example SConstruct file doesn't build anything,
- but because it's actually a Python script,
- it will print the value of
- A construction environment, however,
- is actually an object with associated methods, etc.
- If you want to have direct access to only the
- dictionary of construction variables,
- you can fetch this using the Dictionary method:
-
- This SConstruct file
- will print the specified dictionary items for us on POSIX
- systems as follows:
+ will print the specified dictionary items for us on POSIX
+ systems as follows:
-
- And on Windows:
+ And on Windows:
-
- If you want to loop through and print the values of
- all of the construction variables in a construction environment,
- the Python code to do that in sorted order might look something like:
+ If you want to loop and print the values of
+ all of the construction variables in a construction environment,
+ the Python code to do that in sorted order might look something like:
-
- Another way to get information from
- a construction environment.
- is to use the
- The real advantage of using
-
- Will print the unexpanded value of
- Calling the
- Will recursively expand all of
- the $-prefixed construction variables,
- showing us the final output:
+ Will recursively expand all of
+ the construction variables prefixed
+ with $ (dollar signs),
+ showing us the final output:
-
- (Note that because we're not expanding this
- in the context of building something
- there are no target or source files
- for
- SCons provides various methods that
- support modifying existing values in a construction environment.
-
-
+ All of the
+ You can, however, control the settings
+ in the default contstruction environment
+ by using the
+ When configured as above,
+ all calls to the
+ Note that the
+ One very common use of the
+ So the above example would tell SCons
+ to explicitly configure the default environment
+ to use its normal GNU Compiler and GNU Linker settings
+ (without having to search for them,
+ or any other utilities for that matter),
+ and specifically to use the compiler found at
+ /usr/local/bin/gcc.
+
+
- You can replace existing construction variable values
- using the
+ We can even use multiple construction environments to build
+ multiple versions of a single program.
+ If you do this by simply trying to use the
+
+ Then SCons generates the following error:
+
+
+ This is because the two
+ Notice that each call to the
+ Sometimes you want more than one construction environment
+ to share the same values for one or more variables.
+ Rather than always having to repeat all of the common
+ variables when you create each construction environment,
+ you can use the
+ Like the
+ Then our output would look like:
+
+
+ You can replace existing construction variable values
+ using the
- The replacing value
- (-DDEFINE2 in the above example)
- completely replaces the value in the
- construction environment:
+ completely replaces the value in the
+ construction environment:
-
- You can safely call
- In this case,
- the construction variable simply
- gets added to the construction environment:
+ In this case,
+ the construction variable simply
+ gets added to the construction environment:
-
- Because the variables
- aren't expanded until the construction environment
- is actually used to build the targets,
- and because SCons function and method calls
- are order-independent,
- the last replacement "wins"
- and is used to build all targets,
- regardless of the order in which
- the calls to Replace() are
- interspersed with calls to
- builder methods:
+ are order-independent,
+ the last replacement "wins"
+ and is used to build all targets,
+ regardless of the order in which
+ the calls to Replace() are
+ interspersed with calls to
+ builder methods:
-
- The timing of when the replacement
- actually occurs relative
- to when the targets get built
- becomes apparent
- if we run scons without the -Q
- option:
+ option:
-
- Because the replacement occurs while
- the SConscript files are being read,
- the
- You can append a value to
- an existing construction variable
- using the
+ This is especially useful
+ when writing your own Tool modules
+ to apply variables to construction environments.
+
+
+
+ You can append a value to
+ an existing construction variable
+ using the
- SCons then supplies both the -DMY_VALUE and
- -DLAST flags when compiling the object file:
-
- If the construction variable doesn't already exist,
- the
- Which yields:
+ Which yields:
-
+ Note that the
- You can append a value to the beginning of
- an existing construction variable
- using the
+ In the above example,
+ the -g would be added
+ only if the
+ You can append a value to the beginning of
+ an existing construction variable
+ using the
- SCons then supplies both the -DFIRST and
- -DMY_VALUE flags when compiling the object file:
-
- If the construction variable doesn't already exist,
- the
- Which yields:
+ Which yields:
-
+ Like the
+ Some times it's useful to add a new value
+ to the beginning of a construction variable
+ only if the existing value
+ doesn't already contain the to-be-added value.
+ This can be done using the
+ In the above example,
+ the -g would be added
+ only if the
+ When SCons builds a target file,
+ it does not execute the commands with
+ the same external environment
+ that you used to execute SCons.
+ Instead, it uses the dictionary
+ stored in the
+ The most important ramification of this behavior
+ is that the
+ The default value of the
+ The simplest way to do this is to initialize explicitly
+ the value when you create the construction environment;
+ this is one way to do that:
+
+
+ Assign a dictionary to the
+ Note that SCons does allow you to define
+ the directories in the
+ But doing so makes your SConscript file less portable,
+ (although in this case that may not be a huge concern
+ since the directories you list are likley system-specific, anyway).
+
+
+ You may want to propagate the external
+ Alternatively, you may find it easier
+ to just propagate the entire external
+ environment to the execution environment
+ for commands.
+ This is simpler to code than explicity
+ selecting the
+ Either of these will guarantee that
+ SCons will be able to execute
+ any command that you can execute from the command line.
+ The drawback is that the build can behave
+ differently if it's run by people with
+ different
+ One of the most common requirements
+ for manipulating a variable in the execution environment
+ is to add one or more custom directories to a search
+ like the
+ Note that the added values are strings,
+ and if you want to add multiple directories to
+ a variable like
- When SCons builds a target file,
- it does not execute the commands with
- the same external environment
- that you used to execute SCons.
- Instead, it uses the dictionary
- stored in the
- The most important ramification of this behavior
- is that the
- The default value of the
- The simplest way to do this is to initialize explicitly
- the value when you create the construction environment;
- this is one way to do that:
-
-
- Assign a dictionary to the
- Note that
- But doing so makes your
+ If
+ In the combined example above,
+
+ SCons has a bewildering array of construction variables
+ for different types of options when building programs.
+ Sometimes you may not know exactly which variable
+ should be used for a particular option.
+
+
+ SCons construction environments have a
+
+ Note that if the options are limited to generic types
+ like those above,
+ they will be correctly translated for other platform types:
+
+
+ Since the assumption is that the flags are used for the GCC toolchain,
+ unrecognized flags are placed in
+
+ If a string begins with a "!" (an exclamation mark, often called a bang),
+ the string is passed to the shell for execution.
+ The output of the command is then parsed:
+
+
+
+ Configuring the right options to build programs to work with
+ libraries--especially shared libraries--that are available
+ on POSIX systems can be very complicated.
+ To help this situation,
+ various utilies with names that end in SConscript file less portable,
- (although in this case that may not be a huge concern
- since the directories you list are likley system-specific, anyway).
+>config
+ return the command-line options for the GNU Compiler Collection (GCC)
+ that are needed to use these libraries;
+ for example, the command-line options
+ to use a library named lib
+ would be found by calling a utility named lib-config.
+
+
+ A more recent convention is that these options
+ are available from the generic pkg-config program,
+ which has common framework, error handling, and the like,
+ so that all the package creator has to do is provide the set of strings
+ for his particular package.
+
+
+ SCons construction environments have a
+ SCons will execute the specified command string,
+ parse the resultant flags,
+ and add the flags to the appropriate environment variables.
+
+
+ In the example above, SCons has added the include directory to
+
+ Note that the options are merged with existing options using
+ the
+ A key aspect of creating a usable build configuration
+ is providing good output from the build
+ so its users can readily understand
+ what the build is doing
+ and get information about how to control the build.
+ SCons provides several ways of
+ controlling output from the build configuration
+ to help make the build
+ more useful and understandable.
- You may want to propagate the external
- Alternatively, you may find it easier
- to just propagate the entire external
- environment to the execution environment
- for commands.
- This is simpler to code than explicity
- selecting the
- Either of these will guarantee that
+ It's often very useful to be able to give
+ users some help that describes the
+ specific targets, build options, etc.,
+ that can be used for your build.
SCons will be able to execute
- any command that you can execute from the command line.
- The drawback is that the build can behave
- differently if it's run by people with
- different
+ (Note the above use of the Python triple-quote syntax,
+ which comes in very handy for
+ specifying multi-line strings like help text.)
+
+
+ When the SConstruct or SConscript files
+ contain such a call to the
+ The SConscript files may contain
+ multiple calls to the
+ Another use would be to make the help text conditional
+ on some variable.
+ For example, suppose you only want to display
+ a line about building a Windows-only
+ version of a program when actually
+ run on Windows.
+ The following SConstruct file:
+
+
+ Will display the complete help text on Windows:
+
+
+ But only show the relevant option on a Linux or UNIX system:
+
+
+ If there is no
+ Sometimes the commands executed
+ to compile object files or link programs
+ (or build other targets)
+ can get very long,
+ long enough to make it difficult for users
+ to distinguish error messages or
+ other important build output
+ from the commands themselves.
+ All of the default
+ For example, suppose you want to
+ have SCons display a
+ "Compiling"
+ message whenever it's compiling an object file,
+ and a
+ "Linking"
+ when it's linking an executable.
+ You could write a SConstruct file
+ that looks like:
+
+
+ Which would then yield the output:
+
+
+ SCons performs complete variable substitution
+ on
+ Of course, sometimes it's still important to
+ be able to see the exact command
+ that SCons will execute to build a target.
+ For example, you may simply need to verify
+ that SCons is configured to supply
+ the right options to the compiler,
+ or a developer may want to
+ cut-and-paste a comiloe command
+ to add a few options
+ for a custom test.
+
+
+ One common way to give users
+ control over whether or not
+ SCons should print the actual command line
+ or a short, configured summary
+ is to add support for a
+
+
+ By only setting the appropriate
+
+ Another aspect of providing good build output
+ is to give the user feedback
+ about what SCons is doing
+ even when nothing is being built at the moment.
+ This can be especially true for large builds
+ when most of the targets are already up-to-date.
+ Because SCons can take a long time
+ making absolutely sure that every
+ target is, in fact, up-to-date
+ with respect to a lot of dependency files,
+ it can be easy for users to mistakenly
+ conclude that SCons is hung
+ or that there is some other problem with the build.
+
+
+ One way to deal with this perception
+ is to configure SCons to print something to
+ let the user know what it's "thinking about."
+ The
+ Note that the
+ Of course, normally you don't want to add
+ all of these additional lines to your build output,
+ as that can make it difficult for the user
+ to find errors or other important messages.
+ A more useful way to display
+ this progress might be
+ to have the file names printed
+ directly to the user's screen,
+ not to the same standard output
+ stream where build output is printed,
+ and to use a carriage return character
+ (\r)
+ so that each file name gets re-printed on the same line.
+ Such a configuration would look like:
+
+
+ Note that we also specified the
+ overwrite=True argument
+ to the
+ Also, it's important to know that although you can use
+ $TARGET to substitute the name of
+ the node in the string,
+ the
+ You can also specify a list of strings
+ to the
+ Note that here we have also used the
+ interval=
+ keyword argument to have SCons
+ only print a new "spinner" string
+ once every five evaluated nodes.
+ Using an interval= count,
+ even with strings that use $TARGET like
+ our examples above,
+ can be a good way to lessen the
+ work that SCons expends printing
+ Lastly, you can have direct control
+ over how to print each evaluated node
+ by passing a Python function
+ (or other Python callable)
+ to the
+ Of course, if you choose,
+ you could completely ignore the
+
+ (Note that there's an obvious follow-on question here:
+ how would you find the total number of nodes
+ that will be
+ evaluated so you can tell the user how
+ close the build is to finishing?
+ Unfortunately, in the general case,
+ there isn't a good way to do that,
+ short of having SCons evaluate its
+ dependency graph twice,
+ first to count the total and
+ the second time to actually build the targets.
+ This would be necessary because
+ you can't know in advance which
+ target(s) the user actually requested
+ to be built.
+ The entire build may consist of thousands of Nodes,
+ for example,
+ but maybe the user specifically requested
+ that only a single object file be built.)
+
+
+ SCons, like most build tools, returns zero status to
+ the shell on success and nonzero status on failure.
+ Sometimes it's useful to give more information about
+ the build status at the end of the run, for instance
+ to print an informative message, send an email, or
+ page the poor slob who broke the build.
+
+
+ SCons provides a
+ The
+
+ Here is a more complete example showing how to
+ turn each element of
+ When this runs, you'll see the appropriate output:
+
+
SCons provides a number of ways that
- allow the writer of the provides a number of ways
+ for the writer of the SConscript files
- to give users a great deal of control over how to run the builds.
+ to give the users who will run SCons
+ a great deal of control over the build execution.
+ The arguments that the user can specify on
+ the command line are broken down into three types:
- Users may find themselves supplying
- the same command-line options every time
- they run SCons.
- For example, a user might find that it saves time
- to specify a value of -j 2
- to run the builds in parallel.
- To avoid having to type -j 2 by hand
- every time,
- you can set the external environment variable
-
- If, for example,
- you're using a POSIX shell that's
- compatible with the Bourne shell,
- and you always want SCons to use the
- -Q option,
- you can set the
- Users of csh-style shells on POSIX systems
- can set the
- Windows users may typically want to set the
-
+>- (hyphen) characters.
SCons supports a
- Then, running SCons with the default target
- works as it always does,
- but explicity specifying the bar target
- on the command line generates the warning message:
-
-
- Another practical use for the
+ Any command-line argument containing an =
+ (equal sign) is considered a variable setting with the form
+
+ Any command-line argument that is not an option
+ or a variable setting
+ (does not begin with a hyphen
+ and does not contain an equal sign)
+ is considered a target that the user
+ (presumably) wants SCons to build.
+ A list of Node objects representing
+ the target or targets to build.
+ SCons provides access to the list of specified targets,
+ as well as ways to set the default list of targets
+ from within the SConscript files.
+ See Section 12.3, below.
+
+
- One of the most basic things you can control
- is which targets SCons will build by default--that is,
- when there are no targets specified on the command line.
- As mentioned previously,
SCons will normally build every target
- in or below the current directory
- by default--that is, when you don't
- explicitly specify one or more targets
- on the command line.
- Sometimes, however, you may want
- to specify explicitly that only
- certain programs, or programs in certain directories,
- should be built by default.
- You do this with the
- This SConstruct file knows how to build two programs,
- has many command-line options
+ that control its behavior.
+ A hello and goodbye,
- but only builds the
- hello program by default:
-
-
- Note that, even when you use the
- You can also call the
- Or you can specify more than one target
- in a single call to the
- Either of these last two examples
- will build only the
- prog1
- and
- prog3
- programs by default:
-
-
- You can list a directory as
- an argument to
- In which case only the target(s) in that
- directory will be built by default:
-
-
- Lastly, if for some reason you don't want
- any targets built by default,
- you can use the Python None
- variable:
-
-
- Which would produce build output like:
-
-
+ Users may find themselves supplying
+ the same command-line options every time
+ they run SCons.
+ For example, you might find it saves time
+ to specify a value of -j 2
+ to have SCons run up to two build commands in parallel.
+ To avoid having to type -j 2 by hand
+ every time,
+ you can set the external environment variable
+
+ If, for example,
+ you're using a POSIX shell that's
+ compatible with the Bourne shell,
+ and you always want SCons to use the
+ -Q option,
+ you can set the
+ Users of csh-style shells on POSIX systems
+ can set the
+ Windows users may typically want to set the
+
SCons supports a
- (Keep in mind that all of the manipulation of the
-
- Second,
- the contents of the
- Which yields the output:
-
-
- In practice, this simply means that you
- need to pay attention to the order in
- which you call the
- We've already been introduced to the
-
- SCons, however, provides a convenient
-
- Because
- Notice how the value of
+ One use of the
+ For example, suppose the administrators
+ of your development systems
+ have standardized on setting a
+
+ The above snippet of code
+ sets the value of the --jobs option
+ to the value specified in the
+
+ But if the
+ But any explicit
+ -j or --jobs
+ value the user specifies an the command line is used first,
+ regardless of whether or not
+ the
+ The strings that you can pass to the
+ The full list of strings and the variables they
+ correspond to is as follows:
+
+
+ SCons also allows you to define your own
+ command-line options with the
+ One useful example of using this functionality
+ is to provide a
+ The above code uses the
+ But specifying --prefix=/tmp/install
+ on the command line causes the file to be installed in the
+ /tmp/install/usr/bin/ directory:
+
+
@@ -9488,7 +13056,7 @@ CLASS="emphasis"
>always
- specify an option,
+ specify a variable,
you probably want to use
the Python
- Being able to use a command-line build option like
- debug=1 is handy,
- but it can be a chore to write specific Python code
- to recognize each such option
- and apply the values to a construction variable.
- To help with this,
- SCons supports a class to
- define such build options easily,
- and a mechanism to apply the
- build options to a construction environment.
- This allows you to control how the build options affect
- construction environments.
+ The
- For example, suppose that you want users to set
- a
+ Yields the followig output:
+
+
+ Note that the
+ Being able to use a command-line build variable like
+ debug=1 is handy,
+ but it can be a chore to write specific Python code
+ to recognize each such variable,
+ check for errors and provide appropriate messages,
+ and apply the values to a construction variable.
+ To help with this,
+ SCons supports a class to
+ define such build variables easily,
+ and a mechanism to apply the
+ build variables to a construction environment.
+ This allows you to control how the build variables affect
+ construction environments.
+
+
+ For example, suppose that you want users to set
+ a
- This SConstruct file first creates an
-
- We then pass the created
- To make command-line build options most useful,
- you ideally want to provide
- some help text that will describe
- the available options
- when the user runs scons -h.
- You could write this text by hand,
- but SCons provides an easier way.
-
- SCons will now display some useful text
- when the -h option is used:
-
-
- Notice that the help output shows the default value,
- and the current actual value of the build option.
-
-
- Being able to use a command-line build option like
- debug=1 is handy,
- but it can be a chore to write specific Python code
- to recognize each such option
- and apply the values to a construction variable.
- To help with this,
- SCons supports a class to
- define such build options easily
- and to read build option values from a file.
- This allows you to control how the build options affect
- construction environments.
- The way you do this is by specifying
- a file name when you call
- This then allows us to control the
- Note that this file is actually executed
- like a Python script.
- Now when we run SCons:
-
-
- And if we change the contents of custom.py to:
+>SConstruct file first creates a
- The object files are rebuilt appropriately
- with the new option:
+ We then pass the created
- SCons provides a number of functions
- that provide ready-made behaviors
- for various types of command-line build options.
+> release 0.98.1, these build variables
+ were known as "command-line build options."
+ The class was actually named the
- It's often handy to be able to specify an
- option that controls a simple Boolean variable
- with a scons -h.
+ You could write this text by hand,
+ but SCons provides an easier way.
+
+ SCons will now display some useful text
+ when the -h option is used:
+
+
+ Notice that the help output shows the default value,
+ and the current actual value of the build variable.
+
+
+ Giving the user a way to specify the
+ value of a build variable on the command line
+ is useful,
+ but can still be tedious
+ if users must specify the variable
+ every time they run SCons.
+ We can let users provide customized build variable settings
+ in a local file by providing a
+ file name when we create the
+
+ This then allows the user to control the
+ Note that this file is actually executed
+ like a Python script.
+ Now when we run SCons:
+
+
+ And if we change the contents of custom.py to:
+
+
+ The object files are rebuilt appropriately
+ with the new variable:
+
+
+ SCons provides a number of functions
+ that provide ready-made behaviors
+ for various types of command-line build variables.
+
+
+ It's often handy to be able to specify a
+ variable that controls a simple Boolean variable
+ with a true or false value.
- It would be even more handy to accomodate
- users who have different preferences for how to represent
- true or false values.
- The
- The
- With this build option,
- the
- Other values that equate to true include
- y,
- 1,
- on
- and
- all.
-
- Conversely,
- Other values that equate to false include
- n,
- 0,
- off
- and
- none.
-
- Lastly, if a user tries to specify
- any other value,
- SCons supplies an appropriate error message:
-
- Suppose that we want a user to be able to
- set a
- The user can now explicity set the
- But, almost more importantly,
- an attempt to set
- The
- As desired, the user can then use
- navy on the command line,
- and SCons will translate it into blue
- when it comes time to use the
- By default, when using the
- The
- Which yields the output:
+ Which yields the output:
-
- Notice that an
- Now SCons will use values of
- red,
- green or
- blue
- regardless of how the user spells
- those values on the command line:
+ regardless of how the user spells
+ those values on the command line:
-
- Another way in which you might want to allow users
- to control build option is to
- specify a list of one or more legal values.
- SCons supports this through the
- A user can now specify a comma-separated list
- of legal values,
- which will get translated into a space-separated
- list for passing to the any build commands:
+ A user can now specify a comma-separated list
+ of legal values,
+ which will get translated into a space-separated
+ list for passing to the any build commands:
-
- In addition, the
- And, of course, an illegal value
- still generates an error message:
+ And, of course, an illegal value
+ still generates an error message:
-
- SCons supports a
- This then allows the user to
- override the
- By default,
-
- Conversely, to ensure that any specified paths are
- directories and not files,
- use the
- If you want to make sure that any specified paths
- are directories,
- and you would like the directory created
- if it doesn't already exist,
- use the
- Lastly, if you don't care whether the path exists,
- is a file, or a directory,
- use the
- Sometimes you want to give users
- even more control over a path name variable,
- allowing them to explicitly enable or
- disable the path name
- by using yes or no keywords,
- in addition to allow them
- to supply an explicit path name.
- SCons supports the
- When the SConscript file uses the
+ Lastly, SCons provides a way to add
+ multiple build variables to a
+ Users may, of course,
+ occasionally misspell variable names in their command-line settings.
+ SCons does not generate an error or warning
+ for any unknown variables the users specifies on the command line.
+ (This is in no small part because you may be
+ processing the arguments directly using the
+ If, however, you're using a
+ The
+ Of course, you can process the items in the
+ dictionary returned by the
+ Note that you must delay the call of
- Lastly, SCons provides a way to add
- multiple build options to an
- It's often very useful to be able to give
- users some help that describes the
- specific targets, build options, etc.,
- that can be used for your build.
- SCons provides the
- (Note the above use of the Python triple-quote syntax,
- which comes in very handy for
- specifying multi-line strings like help text.)
-
-
- When the SConstruct or SConscript files
- contain such a call to the
- The COMMAND_LINE_TARGETS variable
+ might be to speed up a build
+ by only reading certain subsidiary SConscript files may contain
- multiple calls to the
- Another use would be to make the help text conditional
- on some variable.
- For example, suppose you only want to display
- a line about building a Windows-only
- version of a program when actually
- run on Windows.
- The following SCons will build by default--that is,
+ when there are no targets specified on the command line.
+ As mentioned previously,
+ SCons will normally build every target
+ in or below the current directory
+ by default--that is, when you don't
+ explicitly specify one or more targets
+ on the command line.
+ Sometimes, however, you may want
+ to specify explicitly that only
+ certain programs, or programs in certain directories,
+ should be built by default.
+ You do this with the
+ This SConstruct file knows how to build two programs,
+ hello and goodbye,
+ but only builds the
+ hello program by default:
+
+
+ Note that, even when you use the
+ You can also call the
+ Or you can specify more than one target
+ in a single call to the
+ Either of these last two examples
+ will build only the
+ prog1
+ and
+ prog3
+ programs by default:
+
+
+ You can list a directory as
+ an argument to
+ In which case only the target(s) in that
+ directory will be built by default:
+
+
+ Lastly, if for some reason you don't want
+ any targets built by default,
+ you can use the Python None
+ variable:
+
+
+ Which would produce build output like:
+
+
+ SCons supports a
+ (Keep in mind that all of the manipulation of the
+
+ Second,
+ the contents of the
- Will display the complete help text on Windows:
+ Which yields the output:
-
- But only show the relevant option on a Linux or UNIX system:
-
-
- If there is no
+ We've already been introduced to the
+
+ SCons, however, provides a convenient
+
+ Because
+ Notice how the value of
@@ -11288,8 +15670,8 @@ CLASS="section"
>
@@ -11342,8 +15724,8 @@ CLASS="section"
>
@@ -11400,7 +15782,7 @@ CLASS="chapter"
>Chapter 12. Platform-Independent File System ManipulationChapter 14. Platform-Independent File System Manipulation
Suppose you want to arrange to make a copy of a file,
- and the
- (Note, however, that you typically don't need to
+ Note, however, that you typically don't need to
call the
+ One word of caution about using the
+ The
There are two occasions when
The source code for large software projects
@@ -12335,8 +16778,8 @@ CLASS="section"
>
@@ -12738,7 +17181,7 @@ CLASS="literal"
is built in the same directory as its source file.
See Chapter 15Chapter 17, below,
for information about
how to build the object file in a different subdirectory.)
@@ -12750,8 +17193,8 @@ CLASS="section"
>
@@ -12940,8 +17383,8 @@ CLASS="section"
>
@@ -13050,8 +17493,8 @@ CLASS="section"
>
It's often useful to keep any built files completely
@@ -13228,8 +17671,8 @@ CLASS="section"
>
- The Glob() file name pattern matching function
+ The
- The Glob function returns Nodes in the build/ tree, as
- you'd expect.
+ The
The
Although
@@ -14019,8 +18481,8 @@ CLASS="section"
>6.1.5. Mixing Different Ways of Deciding If a File Has Changed
6.2. Older Functions for Deciding When an Input File Has Changed
6.2.1. The
SourceSignatures
6.2.2. The
TargetSignatures
[2]6.3. Implicit Dependencies: The
$CPPPATH
6.4. Caching Implicit Dependencies
6.4.1. The --implicit-deps-changed
6.4.2. The --implicit-deps-unchanged
6.5. Explicit Dependencies: the
Depends
Depends
)
+ may also be a list of Node objects
+ (for example, as returned by a call to a Builder):
+
+
hello = Program('hello.c')
+ goodbye = Program('goodbye.c')
+ Depends(hello, goodbye)
+
% scons -Q hello
+ cc -c goodbye.c -o goodbye.o
+ cc -o goodbye goodbye.o
+ cc -c hello.c -o hello.o
+ cc -o hello hello.o
+
6.6. Ignoring Dependencies: the
6.6. Dependencies From External Files: the
ParseDepends
+ Function
#define FOO_HEADER <foo.h>
+ #include FOO_HEADER
+
+ int main() {
+ return FOO;
+ }
+
% scons -Q
+ cc -o hello.o -c -I. hello.c
+ cc -o hello hello.o
+ % edit foo.h
+ [CHANGE CONTENTS OF foo.h]
+ % scons -Q
+ scons: `.' is up to date.
+
ParseDepends
can parse the contents of
+ the compiler output in the style of Make, and explicitly
+ establish all of the listed dependencies.
+
+ ParseDepends
to process a compiler
+ generated dependency file which is generated as a side effect
+ during compilation of the object file:
+
+
obj = Object('hello.c', CCFLAGS='-MD -MF hello.d', CPPPATH='.')
+ SideEffect('hello.d', obj)
+ ParseDepends('hello.d')
+ Program('hello', obj)
+
% scons -Q
+ cc -o hello.o -c -MD -MF hello.d -I. hello.c
+ cc -o hello hello.o
+ % edit foo.h
+ [CHANGE CONTENTS OF foo.h]
+ % scons -Q
+ cc -o hello.o -c -MD -MF hello.d -I. hello.c
+
% scons -Q
+ cc -o hello.o -c -MD -MF hello.d -I. hello.c
+ cc -o hello hello.o
+ % scons -Q --debug=explain
+ scons: rebuilding `hello.o' because `foo.h' is a new dependency
+ cc -o hello.o -c -MD -MF hello.d -I. hello.c
+ % scons -Q
+ scons: `.' is up to date.
+
ParseDepends
immediately reads the specified file at invocation
+ time and just returns if the file does not exist. A dependency
+ file generated during the build process is not automatically
+ parsed again. Hence, the compiler-extracted dependencies are not
+ stored in the signature database during the same build pass. This
+ limitation of ParseDepends
leads to unnecessary recompilations.
+ Therefore, ParseDepends
should only be used if scanners are not
+ available for the employed language or not powerful enough for the
+ specific task.
+
+ 6.7. Ignoring Dependencies: the
Ignore
Function
hello = Program('hello.c')
+>
hello = Program('hello.c', CPPPATH=['/usr/include'])
Ignore(hello, '/usr/include/stdio.h')
Ignore
can also be used to prevent a generated file from being built
+ by default. This is due to the fact that directories depend on
+ their contents. So to ignore a generated file from the default build,
+ you specify that the directory should ignore the generated file.
+ Note that the file will still be built if the user specifically
+ requests the target on scons command line, or if the file is
+ a dependency of another file which is requested and/or is built
+ by default.
+
hello_obj=Object('hello.c')
+ hello = Program(hello_obj)
+ Ignore('.',[hello,hello_obj])
+
% scons -Q
+ scons: `.' is up to date.
+ % scons -Q hello
+ cc -o hello.o -c hello.c
+ cc -o hello hello.o
+ % scons -Q hello
+ scons: `hello' is up to date.
+
6.7. The
6.8. Order-Only Dependencies: the
Requires
Function
import time
+
+ version_c_text = """
+ char *date = "%s";
+ """ % time.ctime(time.time())
+ open('version.c', 'w').write(version_c_text)
+
+ hello = Program(['hello.c', 'version.c'])
+
% scons -Q
+ gcc -o hello.o -c hello.c
+ gcc -o version.o -c version.c
+ gcc -o hello hello.o version.o
+ % scons -Q
+ gcc -o version.o -c version.c
+ gcc -o hello hello.o version.o
+ % scons -Q
+ gcc -o version.o -c version.c
+ gcc -o hello hello.o version.o
+
Requires
function
+ to specify that the version.o
+ must be rebuilt before it is used by the link step,
+ but that changes to version.o
+ should not actually cause the hello
+ executable to be re-linked:
+
+
import time
+
+ version_c_text = """
+ char *date = "%s";
+ """ % time.ctime(time.time())
+ open('version.c', 'w').write(version_c_text)
+
+ version_obj = Object('version.c')
+
+ hello = Program('hello.c',
+ LINKFLAGS = str(version_obj[0]))
+
+ Requires(hello, version_obj)
+
Object
call)
+ into the $LINKFLAGS
variable,
+ because $LINKFLAGS
is already included
+ in the $LINKCOM
command line.
+
+
% scons -Q
+ cc -o hello.o -c hello.c
+ cc -o version.o -c version.c
+ cc -o hello version.o hello.o
+ % scons -Q
+ scons: `.' is up to date.
+ % edit hello.c
+ [CHANGE THE CONTENTS OF hello.c]
+ % scons -Q
+ cc -o hello.o -c hello.c
+ cc -o hello version.o hello.o
+ % scons -Q
+ scons: `.' is up to date.
+
6.9. The
AlwaysBuild
FunctionChapter 7. Construction EnvironmentsChapter 7. Environments7.1. Using Values From the External Environment
os.environ
+ dictionary.
+ This means that you must add an
+ import os statuement
+ to any SConscript file
+ in which you want to use
+ values from the user's external environment.
+
+
import os
+
os.environ
+ dictionary in your SConscript
+ files to initialize construction environments
- that control how the software is built.
- Technically, a Section 7.2,
+ for information on how to do this.
+
+ 7.2. Construction Environments
Builder
methods,
- about which we'll learn more later.)
+ about which we'll learn more later.)
- 7.2.1. Creating a Construction Environment: the
Environment
FunctionEnvironment
method:
-
env = Environment()
-
env = Environment()
+
env = Environment(CC = 'gcc',
- CCFLAGS = '-O2')
+>
import os
- env.Program('foo.c')
-
$CCFLAGS
- override the default values in the newly-created
- construction environment.
- So a run from this example would look like:
+ override the default values in the newly-created
+ construction environment.
+ So a run from this example would look like:
-
%
% scons -Q
- gcc -o foo.o -c -O2 foo.c
- gcc -o foo foo.o
-
7.1. Multiple Construction Environments
opt = Environment(CCFLAGS = '-O2')
- dbg = Environment(CCFLAGS = '-g')
-
- opt.Program('foo', 'foo.c')
-
- dbg.Program('bar', 'bar.c')
-
% scons -Q
- cc -o bar.o -c -g bar.c
- cc -o bar bar.o
- cc -o foo.o -c -O2 foo.c
- cc -o foo foo.o
-
Program
builder with both environments, though,
- like this:
-
-
opt = Environment(CCFLAGS = '-O2')
- dbg = Environment(CCFLAGS = '-g')
-
- opt.Program('foo', 'foo.c')
-
- dbg.Program('foo', 'foo.c')
-
% scons -Q
-
- scons: *** Two environments with different actions were specified for the same target: foo.o
- File "/home/my/project/SConstruct", line 6, in <module>
-
Program
calls have
- each implicitly told SCons to generate an object file named
- foo.o,
- one with a $CCFLAGS
value of
- -O2
- and one with a $CCFLAGS
value of
- -g.
- SCons can't just decide that one of them
- should take precedence over the other,
- so it generates the error.
- To avoid this problem,
- we must explicitly specify
- that each environment compile
- foo.c
- to a separately-named object file
- using the Object
builder, like so:
-
-
opt = Environment(CCFLAGS = '-O2')
- dbg = Environment(CCFLAGS = '-g')
-
- o = opt.Object('foo-opt', 'foo.c')
- opt.Program(o)
-
- d = dbg.Object('foo-dbg', 'foo.c')
- dbg.Program(d)
-
Object
builder
- returns a value,
- an internal SCons object that
- represents the object file that will be built.
- We then use that object
- as input to the Program
builder.
- This avoids having to specify explicitly
- the object file name in multiple places,
- and makes for a compact, readable
- SConstruct file.
- Our SCons output then looks like:
-
-
% scons -Q
- cc -o foo-dbg.o -c -g foo.c
- cc -o foo-dbg foo-dbg.o
- cc -o foo-opt.o -c -O2 foo.c
- cc -o foo-opt foo-opt.o
-
7.2. Copying Construction Environments
Clone
method
- to create a copy of a construction environment.
-
- Environment
call that creates a construction environment,
- the Clone
method takes construction variable assignments,
- which will override the values in the copied construction environment.
- For example, suppose we want to use gcc
- to create three versions of a program,
- one optimized, one debug, and one with neither.
- We could do this by creating a "base" construction environment
- that sets $CC
to gcc,
- and then creating two copies,
- one which sets $CCFLAGS
for optimization
- and the other which sets $CCFLAGS
for debugging:
-
-
env = Environment(CC = 'gcc')
- opt = env.Clone(CCFLAGS = '-O2')
- dbg = env.Clone(CCFLAGS = '-g')
-
- env.Program('foo', 'foo.c')
-
- o = opt.Object('foo-opt', 'foo.c')
- opt.Program(o)
-
- d = dbg.Object('foo-dbg', 'foo.c')
- dbg.Program(d)
-
% scons -Q
- gcc -o foo.o -c foo.c
- gcc -o foo foo.o
- gcc -o foo-dbg.o -c -g foo.c
- gcc -o foo-dbg foo-dbg.o
- gcc -o foo-opt.o -c -O2 foo.c
- gcc -o foo-opt foo-opt.o
-
7.3. Fetching Values From a 7.2.2. Fetching Values From a Construction Environment
env = Environment()
- print "CC is:", env['CC']
-
env = Environment()
+ print "CC is:", env['CC']
+ for us:
-
%
% scons -Q
- CC is: cc
- scons: `.' is up to date.
-
env = Environment(FOO = 'foo', BAR = 'bar')
- dict = env.Dictionary()
- for key in ['OBJSUFFIX', 'LIBSUFFIX', 'PROGSUFFIX']:
- print "key = %s, value = %s" % (key, dict[key])
-
env = Environment(FOO = 'foo', BAR = 'bar')
+ dict = env.Dictionary()
+ for key in ['OBJSUFFIX', 'LIBSUFFIX', 'PROGSUFFIX']:
+ print "key = %s, value = %s" % (key, dict[key])
+
%
% scons -Q
- key = OBJSUFFIX, value = .o
- key = LIBSUFFIX, value = .a
- key = PROGSUFFIX, value =
- scons: `.' is up to date.
-
C:\>
C:\>scons -Q
- key = OBJSUFFIX, value = .obj
- key = LIBSUFFIX, value = .lib
- key = PROGSUFFIX, value = .exe
- scons: `.' is up to date.
-
env = Environment()
- dict = env.Dictionary()
- keys = dict.keys()
- keys.sort()
- for key in keys:
- print "construction variable = '%s', value = '%s'" % (key, dict[key])
-
env = Environment()
+ dict = env.Dictionary()
+ keys = dict.keys()
+ keys.sort()
+ for key in keys:
+ print "construction variable = '%s', value = '%s'" % (key, dict[key])
+
: the 7.4. Expanding Values From a 7.2.3. Expanding Values From a Construction Environment
subst
Methodsubst
method
- on a string containing $-expansions
- of construction variable names.
- As a simple example,
- the example from the previous
- section that used
- $ expansions
+ of construction variable names.
+ As a simple example,
+ the example from the previous
+ section that used
+ env['CC']
- to fetch the value of $CC
- could also be written as:
+ could also be written as:
-
env = Environment()
- print "CC is:", env.subst('$CC')
-
env = Environment()
+ print "CC is:", env.subst('$CC')
+ subst
to expand strings is
- that construction variables
- in the result get
- re-expanded until
- there are no expansions left in the string.
- So a simple fetch of a value like
- :
-
env = Environment(CCFLAGS = '-DFOO')
- print "CCCOM is:", env['CCCOM']
-
env = Environment(CCFLAGS = '-DFOO')
+ print "CCCOM is:", env['CCCOM']
+ $CCCOM
,
- showing us the construction
- variables that still need to be expanded:
+ showing us the construction
+ variables that still need to be expanded:
-
%
% scons -Q
- CCCOM is: $CC $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES
- scons: `.' is up to date.
-
subst
method on $CCOM
,
- however:
+ however:
-
env = Environment(CCFLAGS = '-DFOO')
- print "CCCOM is:", env.subst('$CCCOM')
-
env = Environment(CCFLAGS = '-DFOO')
+ print "CCCOM is:", env.subst('$CCCOM')
+
%
% scons -Q
- CCCOM is: gcc -DFOO -c -o
- scons: `.' is up to date.
-
$SOURCES
to expand.)
+> to expand.
- 7.5. Modifying a Construction Environment
7.5.1. Replacing Values in a 7.2.4. Controlling the Default Construction Environment: the
DefaultEnvironment
FunctionBuilder
functions that we've introduced so far,
+ like Program
and Library
,
+ actually use a default construction environment
+ that contains settings
+ for the various compilers
+ and other tools that
+ SCons configures by default,
+ or otherwise knows about
+ and has discovered on your system.
+ The goal of the default construction environment
+ is to make many configurations to "just work"
+ to build software using
+ readily available tools
+ with a minimum of configuration changes.
+
+ DefaultEnvironment
function
+ to initialize various settings:
+
+
+ DefaultEnvironment(CC = '/usr/local/bin/gcc')
+
+
Program
+ or Object
Builder
+ will build object files with the
+ /usr/local/bin/gcc
+ compiler.
+
+ DefaultEnvironment
function
+ returns the initialized
+ default construction environment object,
+ which can then be manipulated like any
+ other construction environment.
+ So the following
+ would be equivalent to the
+ previous example,
+ setting the $CC
+ variable to /usr/local/bin/gcc
+ but as a separate step after
+ the default construction environment has been initialized:
+
+
+ env = DefaultEnvironment()
+ env['CC'] = '/usr/local/bin/gcc'
+
+
DefaultEnvironment
function
+ is to speed up SCons initialization.
+ As part of trying to make most default
+ configurations "just work,"
+ SCons will actually
+ search the local system for installed
+ compilers and other utilities.
+ This search can take time,
+ especially on systems with
+ slow or networked file systems.
+ If you know which compiler(s) and/or
+ other utilities you want to configure,
+ you can control the search
+ that SCons performs
+ by specifying some specific
+ tool modules with which to
+ initialize the default construction environment:
+
+
+ env = DefaultEnvironment(tools = ['gcc', 'gnulink'],
+ CC = '/usr/local/bin/gcc')
+
+
7.2.5. Multiple Construction Environments
-O2 flag
+ and another with the -g (debug) flag,
+ we would do this like so:
+
+
opt = Environment(CCFLAGS = '-O2')
+ dbg = Environment(CCFLAGS = '-g')
+
+ opt.Program('foo', 'foo.c')
+
+ dbg.Program('bar', 'bar.c')
+
% scons -Q
+ cc -o bar.o -c -g bar.c
+ cc -o bar bar.o
+ cc -o foo.o -c -O2 foo.c
+ cc -o foo foo.o
+
Program
builder with both environments, though,
+ like this:
+
+
opt = Environment(CCFLAGS = '-O2')
+ dbg = Environment(CCFLAGS = '-g')
+
+ opt.Program('foo', 'foo.c')
+
+ dbg.Program('foo', 'foo.c')
+
% scons -Q
+
+ scons: *** Two environments with different actions were specified for the same target: foo.o
+ File "/home/my/project/SConstruct", line 6, in <module>
+
Program
calls have
+ each implicitly told SCons to generate an object file named
+ foo.o,
+ one with a $CCFLAGS
value of
+ -O2
+ and one with a $CCFLAGS
value of
+ -g.
+ SCons can't just decide that one of them
+ should take precedence over the other,
+ so it generates the error.
+ To avoid this problem,
+ we must explicitly specify
+ that each environment compile
+ foo.c
+ to a separately-named object file
+ using the Object
builder, like so:
+
+
opt = Environment(CCFLAGS = '-O2')
+ dbg = Environment(CCFLAGS = '-g')
+
+ o = opt.Object('foo-opt', 'foo.c')
+ opt.Program(o)
+
+ d = dbg.Object('foo-dbg', 'foo.c')
+ dbg.Program(d)
+
Object
builder
+ returns a value,
+ an internal SCons object that
+ represents the object file that will be built.
+ We then use that object
+ as input to the Program
builder.
+ This avoids having to specify explicitly
+ the object file name in multiple places,
+ and makes for a compact, readable
+ SConstruct file.
+ Our SCons output then looks like:
+
+
% scons -Q
+ cc -o foo-dbg.o -c -g foo.c
+ cc -o foo-dbg foo-dbg.o
+ cc -o foo-opt.o -c -O2 foo.c
+ cc -o foo-opt foo-opt.o
+
7.2.6. Making Copies of Construction Environments: the
Clone
MethodClone
method
+ to create a copy of a construction environment.
+
+ Environment
call that creates a construction environment,
+ the Clone
method takes construction variable assignments,
+ which will override the values in the copied construction environment.
+ For example, suppose we want to use gcc
+ to create three versions of a program,
+ one optimized, one debug, and one with neither.
+ We could do this by creating a "base" construction environment
+ that sets $CC
to gcc,
+ and then creating two copies,
+ one which sets $CCFLAGS
for optimization
+ and the other which sets $CCFLAGS
for debugging:
+
+
env = Environment(CC = 'gcc')
+ opt = env.Clone(CCFLAGS = '-O2')
+ dbg = env.Clone(CCFLAGS = '-g')
+
+ env.Program('foo', 'foo.c')
+
+ o = opt.Object('foo-opt', 'foo.c')
+ opt.Program(o)
+
+ d = dbg.Object('foo-dbg', 'foo.c')
+ dbg.Program(d)
+
% scons -Q
+ gcc -o foo.o -c foo.c
+ gcc -o foo foo.o
+ gcc -o foo-dbg.o -c -g foo.c
+ gcc -o foo-dbg foo-dbg.o
+ gcc -o foo-opt.o -c -O2 foo.c
+ gcc -o foo-opt foo-opt.o
+
7.2.7. Replacing Values: the
Replace
MethodReplace
method:
-
env = Environment(CCFLAGS = '-DDEFINE1')
- env.Replace(CCFLAGS = '-DDEFINE2')
- env.Program('foo.c')
-
env = Environment(CCFLAGS = '-DDEFINE1')
+ env.Replace(CCFLAGS = '-DDEFINE2')
+ env.Program('foo.c')
+
%
% scons -Q
- cc -o foo.o -c -DDEFINE2 foo.c
- cc -o foo foo.o
-
Replace
- for construction variables that
- don't exist in the construction environment:
+ for construction variables that
+ don't exist in the construction environment:
-
env = Environment()
- env.Replace(NEW_VARIABLE = 'xyzzy')
- print "NEW_VARIABLE =", env['NEW_VARIABLE']
-
env = Environment()
+ env.Replace(NEW_VARIABLE = 'xyzzy')
+ print "NEW_VARIABLE =", env['NEW_VARIABLE']
+
%
% scons -Q
- NEW_VARIABLE = xyzzy
- scons: `.' is up to date.
-
env = Environment(CCFLAGS = '-DDEFINE1')
- print "CCFLAGS =", env['CCFLAGS']
- env.Program('foo.c')
+>
env = Environment(CCFLAGS = '-DDEFINE1')
+ print "CCFLAGS =", env['CCFLAGS']
+ env.Program('foo.c')
- env.Replace(CCFLAGS = '-DDEFINE2')
- print "CCFLAGS =", env['CCFLAGS']
- env.Program('bar.c')
-
%
% scons
- scons: Reading SConscript files ...
- CCFLAGS = -DDEFINE1
- CCFLAGS = -DDEFINE2
- scons: done reading SConscript files.
- scons: Building targets ...
- cc -o bar.o -c -DDEFINE2 bar.c
- cc -o bar bar.o
- cc -o foo.o -c -DDEFINE2 foo.c
- cc -o foo foo.o
- scons: done building targets.
-
$CCFLAGS
- variable has already been set to
- -DDEFINE2
- by the time the foo.o target is built,
- even though the call to the Replace
- method does not occur until later in
- the SConscript file.
- 7.5.2. Appending to the End of Values in a Construction Environment7.2.8. Setting Values Only If They're Not Already Defined: the
SetDefault
MethodSetDefault
method,
+ which behaves similarly to the set_default
+ method of Python dictionary objects:
+
+
env.SetDefault(SPECIAL_FLAG = '-extra-option')
+
7.2.9. Appending to the End of Values: the
Append
MethodAppend
method:
-
env = Environment(CCFLAGS = '-DMY_VALUE')
- env.Append(CCFLAGS = ' -DLAST')
- env.Program('foo.c')
-
env = Environment(CCFLAGS = ['-DMY_VALUE'])
+ env.Append(CCFLAGS = ['-DLAST'])
+ env.Program('foo.c')
+
%
% scons -Q
- cc -o foo.o -c -DMY_VALUE -DLAST foo.c
- cc -o foo foo.o
-
Append
method will create it:
-
env = Environment()
- env.Append(NEW_VARIABLE = 'added')
- print "NEW_VARIABLE =", env['NEW_VARIABLE']
-
env = Environment()
+ env.Append(NEW_VARIABLE = 'added')
+ print "NEW_VARIABLE =", env['NEW_VARIABLE']
+
%
% scons -Q
- NEW_VARIABLE = added
- scons: `.' is up to date.
-
Append
function tries to be "smart"
+ about how the new value is appended to the old value.
+ If both are strings, the previous and new strings
+ are simply concatenated.
+ Similarly, if both are lists,
+ the lists are concatenated.
+ If, however, one is a string and the other is a list,
+ the string is added as a new element to the list.
+
+ 7.5.3. Appending to the Beginning of Values in a Construction Environment7.2.10. Appending Unique Values: the
AppendUnique
MethodAppendUnique
method:
+
+
env.AppendUnique(CCFLAGS=['-g'])
+
$CCFLAGS
variable
+ does not already contain a -g value.
+
+ 7.2.11. Appending to the Beginning of Values: the
Prepend
MethodPrepend
method:
-
env = Environment(CCFLAGS = '-DMY_VALUE')
- env.Prepend(CCFLAGS = '-DFIRST ')
- env.Program('foo.c')
-
env = Environment(CCFLAGS = ['-DMY_VALUE'])
+ env.Prepend(CCFLAGS = ['-DFIRST'])
+ env.Program('foo.c')
+
%
% scons -Q
- cc -o foo.o -c -DFIRST -DMY_VALUE foo.c
- cc -o foo foo.o
-
Prepend
method will create it:
-
env = Environment()
- env.Prepend(NEW_VARIABLE = 'added')
- print "NEW_VARIABLE =", env['NEW_VARIABLE']
-
env = Environment()
+ env.Prepend(NEW_VARIABLE = 'added')
+ print "NEW_VARIABLE =", env['NEW_VARIABLE']
+
%
% scons -Q
- NEW_VARIABLE = added
- scons: `.' is up to date.
-
Append
function,
+ the Prepend
function tries to be "smart"
+ about how the new value is appended to the old value.
+ If both are strings, the previous and new strings
+ are simply concatenated.
+ Similarly, if both are lists,
+ the lists are concatenated.
+ If, however, one is a string and the other is a list,
+ the string is added as a new element to the list.
+
+ 7.2.12. Prepending Unique Values: the
PrependUnique
MethodPrependUnique
method:
+
+
env.PrependUnique(CCFLAGS=['-g'])
+
$CCFLAGS
variable
+ does not already contain a -g value.
+
+ 7.3. Controlling the Execution Environment for Issued Commands
$ENV
construction variable
+ as the external environment
+ for executing commands.
+
+ PATH
environment variable,
+ which controls where the operating system
+ will look for commands and utilities,
+ is not the same as in the external environment
+ from which you called SCons.
+ This means that SCons will not, by default,
+ necessarily find all of the tools
+ that you can execute from the command line.
+
+ PATH
environment variable
+ on a POSIX system
+ is /usr/local/bin:/bin:/usr/bin.
+ The default value of the PATH
environment variable
+ on a Windows system comes from the Windows registry
+ value for the command interpreter.
+ If you want to execute any commands--compilers, linkers, etc.--that
+ are not in these default locations,
+ you need to set the PATH
value
+ in the $ENV
dictionary
+ in your construction environment.
+
+
path = ['/usr/local/bin', '/bin', '/usr/bin']
+ env = Environment(ENV = {'PATH' : path})
+
$ENV
+ construction variable in this way
+ completely resets the external environment
+ so that the only variable that will be
+ set when external commands are executed
+ will be the PATH
value.
+ If you want to use the rest of
+ the values in $ENV
and only
+ set the value of PATH
,
+ the most straightforward way is probably:
+
+
env['ENV']['PATH'] = ['/usr/local/bin', '/bin', '/usr/bin']
+
PATH
in a string,
+ separated by the pathname-separator character
+ for your system (':' on POSIX systems, ';' on Windows):
+
+
env['ENV']['PATH'] = '/usr/local/bin:/bin:/usr/bin'
+
7.3.1. Propagating
PATH
From the External EnvironmentPATH
+ to the execution environment for commands.
+ You do this by initializing the PATH
+ variable with the PATH
value from
+ the os.environ
+ dictionary,
+ which is Python's way of letting you
+ get at the external environment:
+
+
import os
+ env = Environment(ENV = {'PATH' : os.environ['PATH']})
+
PATH
value:
+
+
import os
+ env = Environment(ENV = os.environ)
+
PATH
values in their environment--for example,
+ if both the /bin and
+ /usr/local/bin directories
+ have different cc commands,
+ then which one will be used to compile programs
+ will depend on which directory is listed
+ first in the user's PATH
variable.
+
+ 7.3.2. Adding to
PATH
Values in the Execution Environment$PATH
variable on Linux or POSIX systems,
+ or the %PATH%
variable on Windows,
+ so that a locally-installed compiler or other utility
+ can be found when SCons tries to execute it to update a target.
+ SCons provides PrependENVPath
and AppendENVPath
functions
+ to make adding things to execution variables convenient.
+ You call these functions by specifying the variable
+ to which you want the value added,
+ and then value itself.
+ So to add some /usr/local directories
+ to the $PATH
and $LIB
variables,
+ you might:
+
+
env = Environment(ENV = os.environ)
+ env.PrependENVPath('PATH', '/usr/local/bin')
+ env.AppendENVPath('LIB', '/usr/local/lib')
+
$PATH
,
+ you must include the path separate character
+ (: on Linux or POSIX,
+ ; on Windows)
+ in the string.
+
+ Chapter 8. Controlling the External Environment Used to Execute Build Commands
Chapter 8. Merging Options into the Environment: the MergeFlags
Function$ENV
construction variable
- as the external environment
- for executing commands.
+> construction environments have a MergeFlags
method
+ that merges a dictionary of values into the construction environment.
+ MergeFlags
treats each value in the dictionary
+ as a list of options such as one might pass to a command
+ (such as a compiler or linker).
+ MergeFlags
will not duplicate an option
+ if it already exists in the construction environment variable.
- PATH
environment variable,
- which controls where the operating system
- will look for commands and utilities,
- is not the same as in the external environment
- from which you called SCons.
- This means that SCons will not, by default,
- necessarily find all of the tools
- that you can execute from the command line.
-
- PATH
environment variable
- on a POSIX system
- is /usr/local/bin:/bin:/usr/bin.
- The default value of the PATH
environment variable
- on a Windows system comes from the Windows registry
- value for the command interpreter.
- If you want to execute any commands--compilers, linkers, etc.--that
- are not in these default locations,
- you need to set the PATH
value
- in the $ENV
dictionary
- in your construction environment.
-
-
path = ['/usr/local/bin', '/bin', '/usr/bin']
- env = Environment(ENV = {'PATH' : path})
-
$ENV
- construction variable in this way
- completely resets the external environment
- so that the only variable that will be
- set when external commands are executed
- will be the PATH
value.
- If you want to use the rest of
- the values in $ENV
and only
- set the value of MergeFlags
tries to be intelligent about merging options.
+ When merging options to any variable
+ whose name ends in PATH
,
- the most straightforward way is probably:
+ MergeFlags
keeps the leftmost occurrence of the option,
+ because in typical lists of directory paths,
+ the first occurrence "wins."
+ When merging options to any other variable name,
+ MergeFlags
keeps the rightmost occurrence of the option,
+ because in a list of typical command-line options,
+ the last occurrence "wins."
-
env['ENV']['PATH'] = ['/usr/local/bin', '/bin', '/usr/bin']
-
env = Environment()
+ env.Append(CCFLAGS = '-option -O3 -O1')
+ flags = { 'CCFLAGS' : '-whatever -O3' }
+ env.MergeFlags(flags)
+ print env['CCFLAGS']
+
% scons -Q
+ ['-option', '-O1', '-whatever', '-O3']
+ scons: `.' is up to date.
+
$CCFLAGS
+
+ is an internal SCons does allow you to define
- the directories in the PATH
in a string,
- separated by the pathname-separator character
- for your system (':' on POSIX systems, ';' on Windows):
+> object
+ which automatically converts
+ the options we specified as a string into a list.
-
env['ENV']['PATH'] = '/usr/local/bin:/bin:/usr/bin'
-
env = Environment()
+ env.Append(CPPPATH = ['/include', '/usr/local/include', '/usr/include'])
+ flags = { 'CPPPATH' : ['/usr/opt/include', '/usr/local/include'] }
+ env.MergeFlags(flags)
+ print env['CPPPATH']
+
% scons -Q
+ ['/include', '/usr/local/include', '/usr/include', '/usr/opt/include']
+ scons: `.' is up to date.
+
$CPPPATH
+
+ is a normal Python list,
+ so we must specify its values as a list
+ in the dictionary we pass to the MergeFlags
function.
+
+ MergeFlags
is passed anything other than a dictionary,
+ it calls the ParseFlags
method to convert it into a dictionary.
+
+
env = Environment()
+ env.Append(CCFLAGS = '-option -O3 -O1')
+ env.Append(CPPPATH = ['/include', '/usr/local/include', '/usr/include'])
+ env.MergeFlags('-whatever -I/usr/opt/include -O3 -I/usr/local/include')
+ print env['CCFLAGS']
+ print env['CPPPATH']
+
% scons -Q
+ ['-option', '-O1', '-whatever', '-O3']
+ ['/include', '/usr/local/include', '/usr/include', '/usr/opt/include']
+ scons: `.' is up to date.
+
ParseFlags
has sorted the options into their corresponding variables
+ and returned a dictionary for MergeFlags
to apply
+ to the construction variables
+ in the specified construction environment.
+
+ Chapter 9. Separating Compile Arguments into their Variables: the
ParseFlags
FunctionParseFlags
method
+ that takes a set of typical command-line options
+ and distrbutes them into the appropriate construction variables.
+ Historically, it was created to support the ParseConfig
method,
+ so it focuses on options used by the GNU Compiler Collection (GCC)
+ for the C and C++ toolchains.
+
+ ParseFlags
returns a dictionary containing the options
+ distributed into their respective construction variables.
+ Normally, this dictionary would be passed to MergeFlags
+ to merge the options into a construction environment,
+ but the dictionary can be edited if desired to provide
+ additional functionality.
+ (Note that if the flags are not going to be edited,
+ calling MergeFlags
with the options directly
+ will avoid an additional step.)
+
+
env = Environment()
+ d = env.ParseFlags("-I/opt/include -L/opt/lib -lfoo")
+ l = d.items()
+ l.sort()
+ for k,v in l:
+ if v:
+ print k, v
+ env.MergeFlags(d)
+ env.Program('f1.c')
+
% scons -Q
+ CPPPATH ['/opt/include']
+ LIBPATH ['/opt/lib']
+ LIBS ['foo']
+ cc -o f1.o -c -I/opt/include f1.c
+ cc -o f1 f1.o -L/opt/lib -lfoo
+
C:\>scons -Q
+ CPPPATH ['/opt/include']
+ LIBPATH ['/opt/lib']
+ LIBS ['foo']
+ cl /nologo /I\opt\include /c f1.c /Fof1.obj
+ link /nologo /OUT:f1.exe /LIBPATH:\opt\lib foo.lib f1.obj
+
$CCFLAGS
+ so they will be used for both C and C++ compiles:
+
+
env = Environment()
+ d = env.ParseFlags("-whatever")
+ l = d.items()
+ l.sort()
+ for k,v in l:
+ if v:
+ print k, v
+ env.MergeFlags(d)
+ env.Program('f1.c')
+
% scons -Q
+ CCFLAGS -whatever
+ cc -o f1.o -c -whatever f1.c
+ cc -o f1 f1.o
+
ParseFlags
will also accept a (recursive) list of strings as input;
+ the list is flattened before the strings are processed:
+
+
env = Environment()
+ d = env.ParseFlags(["-I/opt/include", ["-L/opt/lib", "-lfoo"]])
+ l = d.items()
+ l.sort()
+ for k,v in l:
+ if v:
+ print k, v
+ env.MergeFlags(d)
+ env.Program('f1.c')
+
% scons -Q
+ CPPPATH ['/opt/include']
+ LIBPATH ['/opt/lib']
+ LIBS ['foo']
+ cc -o f1.o -c -I/opt/include f1.c
+ cc -o f1 f1.o -L/opt/lib -lfoo
+
env = Environment()
+ d = env.ParseFlags(["!echo -I/opt/include", "!echo -L/opt/lib", "-lfoo"])
+ l = d.items()
+ l.sort()
+ for k,v in l:
+ if v:
+ print k, v
+ env.MergeFlags(d)
+ env.Program('f1.c')
+
% scons -Q
+ CPPPATH ['/opt/include']
+ LIBPATH ['/opt/lib']
+ LIBS ['foo']
+ cc -o f1.o -c -I/opt/include f1.c
+ cc -o f1 f1.o -L/opt/lib -lfoo
+
ParseFlags
is regularly updated for new options;
+ consult the man page for details about those currently recognized.
+
+ Chapter 10. Finding Installed Library Information: the
ParseConfig
FunctionParseConfig
method
+ that executes a *config utility
+ (either pkg-config or a
+ more specific utility)
+ and configures the appropriate construction variables
+ in the environment
+ based on the command-line options
+ returned by the specified command.
+
+
env = Environment()
+ env['CPPPATH'] = ['/lib/compat']
+ env.ParseConfig("pkg-config x11 --cflags --libs")
+ print env['CPPPATH']
+
% scons -Q
+ ['/lib/compat', '/usr/X11/include']
+ scons: `.' is up to date.
+
CPPPATH
.
+ (Depending upon what other flags are emitted by the
+ pkg-config command,
+ other variables may have been extended as well.)
+
+ MergeFlags
method,
+ so that each option only occurs once in the construction variable:
+
+
env = Environment()
+ env.ParseConfig("pkg-config x11 --cflags --libs")
+ env.ParseConfig("pkg-config x11 --cflags --libs")
+ print env['CPPPATH']
+
% scons -Q
+ ['/usr/X11/include']
+ scons: `.' is up to date.
+
Chapter 11. Controlling Build Output
8.1. Propagating
PATH
From the External Environment11.1. Providing Build Help: the Help
FunctionPATH
- to the execution environment for commands.
- You do this by initializing the PATH
- variable with the PATH
value from
- the os.environ
- dictionary,
- which is Python's way of letting you
- get at the external environment:
-
-
import os
- env = Environment(ENV = {'PATH' : os.environ['PATH']})
-
PATH
value:
-
-
import os
- env = Environment(ENV = os.environ)
-
PATH
values in their environment--for example,
- if both the /bin and
- /usr/local/bin directories
- have different cc commands,
- then which one will be used to compile programs
- will depend on which directory is listed
- first in the user's PATH
variable.
+> provides the Help
function
+ to allow you to specify this help text:
Help("""
+ Type: 'scons program' to build the production program,
+ 'scons debug' to build the debug version.
+ """)
+
Help
function,
+ the specified help text will be displayed in response to
+ the SCons -h option:
+
+
% scons -h
+ scons: Reading SConscript files ...
+ scons: done reading SConscript files.
+
+ Type: 'scons program' to build the production program,
+ 'scons debug' to build the debug version.
+
+ Use scons -H for help about command-line options.
+
Help
function,
+ in which case the specified text(s)
+ will be concatenated when displayed.
+ This allows you to split up the
+ help text across multiple SConscript files.
+ In this situation, the order in
+ which the SConscript files are called
+ will determine the order in which the Help
functions are called,
+ which will determine the order in which
+ the various bits of text will get concatenated.
+
+
env = Environment()
+
+ Help("\nType: 'scons program' to build the production program.\n")
+
+ if env['PLATFORM'] == 'win32':
+ Help("\nType: 'scons windebug' to build the Windows debug version.\n")
+
C:\>scons -h
+ scons: Reading SConscript files ...
+ scons: done reading SConscript files.
+
+ Type: 'scons program' to build the production program.
+
+ Type: 'scons windebug' to build the Windows debug version.
+
+ Use scons -H for help about command-line options.
+
% scons -h
+ scons: Reading SConscript files ...
+ scons: done reading SConscript files.
+
+ Type: 'scons program' to build the production program.
+
+ Use scons -H for help about command-line options.
+
Help
text in the SConstruct or
+ SConscript files,
+ SCons will revert to displaying its
+ standard list that describes the SCons command-line
+ options.
+ This list is also always displayed whenever
+ the -H option is used.
+
+ 11.2. Controlling How SCons Prints Build Commands: the
$*COMSTR
Variables$*COM
variables
+ that specify the command lines
+ used to build various types of target files
+ have a corresponding $*COMSTR
variable
+ that can be set to an alternative
+ string that will be displayed
+ when the target is built.
+
+
env = Environment(CCCOMSTR = "Compiling $TARGET",
+ LINKCOMSTR = "Linking $TARGET")
+ env.Program('foo.c')
+
% scons -Q
+ Compiling foo.o
+ Linking foo
+
$*COMSTR
variables,
+ so they have access to all of the
+ standard variables like $TARGET
$SOURCES
, etc.,
+ as well as any construction variables
+ that happen to be configured in
+ the construction environment
+ used to build a specific target.
+
+ VERBOSE
+ command-line variable to your SConstruct file.
+ A simple configuration for this might look like:
+
+
env = Environment()
+ if ARGUMENTS.get('VERBOSE') != "1':
+ env['CCCOMSTR'] = "Compiling $TARGET"
+ env['LINKCOMSTR'] = "Linking $TARGET"
+ env.Program('foo.c')
+
$*COMSTR
variables
+ if the user specifies
+ VERBOSE=1
+ on the command line,
+ the user has control
+ over how SCons
+ displays these particular command lines:
+
+
% scons -Q
+ Compiling foo.o
+ Linking foo
+ % scons -Q -c
+ Removed foo.o
+ Removed foo
+ % scons -Q VERBOSE=1
+ cc -o foo.o -c foo.c
+ cc -o foo foo.o
+
11.3. Providing Build Progress Output: the
Progress
FunctionProgress
function
+ allows you to specify a string
+ that will be printed for every file
+ that SCons is "considering"
+ while it is traversing the dependency graph
+ to decide what targets are or are not up-to-date.
+
+
Progress('Evaluating $TARGET\n')
+ Program('f1.c')
+ Program('f2.c')
+
Progress
function does not
+ arrange for a newline to be printed automatically
+ at the end of the string (as does the Python
+ print statement),
+ and we must specify the
+ \n
+ that we want printed at the end of the configured string.
+ This configuration, then,
+ will have SCons
+ print that it is Evaluating
+ each file that it encounters
+ in turn as it traverses the dependency graph:
+
+
% scons -Q
+ Evaluating SConstruct
+ Evaluating f1.c
+ Evaluating f1.o
+ cc -o f1.o -c f1.c
+ Evaluating f1
+ cc -o f1 f1.o
+ Evaluating f2.c
+ Evaluating f2.o
+ cc -o f2.o -c f2.c
+ Evaluating f2
+ cc -o f2 f2.o
+ Evaluating .
+
Progress('$TARGET\r',
+ file=open('/dev/tty', 'w'),
+ overwrite=True)
+ Program('f1.c')
+ Program('f2.c')
+
Progress
function,
+ which causes SCons to
+ "wipe out" the previous string with space characters
+ before printing the next Progress
string.
+ Without the
+ overwrite=True argument,
+ a shorter file name would not overwrite
+ all of the charactes in a longer file name that
+ precedes it,
+ making it difficult to tell what the
+ actual file name is on the output.
+ Also note that we opened up the
+ /dev/tty file
+ for direct access (on POSIX) to
+ the user's screen.
+ On Windows, the equivalent would be to open
+ the con: file name.
+
+ Progress
function does not
+ perform general variable substitution
+ (because there's not necessarily a construction
+ environment involved in evaluating a node
+ like a source file, for example).
+
+ Progress
function,
+ in which case SCons will
+ display each string in turn.
+ This can be used to implement a "spinner"
+ by having SCons cycle through a
+ sequence of strings:
+
+
Progress(['-\r', '\\\r', '|\r', '/\r'], interval=5)
+ Program('f1.c')
+ Program('f2.c')
+
Progress
strings,
+ while still giving the user feedback
+ that indicates SCons is still
+ working on evaluating the build.
+
+ Progress
function.
+ Your function will be called
+ for each evaluated node,
+ allowing you to
+ implement more sophisticated logic
+ like adding a counter:
+
+
screen = open('/dev/tty', 'w')
+ count = 0
+ def progress_function(node)
+ count += 1
+ screen.write('Node %4d: %s\r' % (count, node))
+
+ Progress(progress_function)
+
node
argument to the function,
+ and just print a count,
+ or anything else you wish.
+
+ 11.4. Printing Detailed Build Status: the
GetBuildFailures
FunctionGetBuildFailures
method that
+ you can use in a python atexit
function
+ to get a list of objects describing the actions that failed
+ while attempting to build targets. There can be more
+ than one if you're using -j. Here's a
+ simple example:
+
+
import atexit
+
+ def print_build_failures():
+ from SCons.Script import GetBuildFailures
+ for bf in GetBuildFailures():
+ print "%s failed: %s" % (bf.node, bf.errstr)
+ atexit.register(print_build_failures)
+
atexit.register
call
+ registers print_build_failures
+ as an atexit
callback, to be called
+ before SCons exits. When that function is called,
+ it calls GetBuildFailures
to fetch the list of failed objects.
+ See the man page
+ for the detailed contents of the returned objects;
+ some of the more useful attributes are
+ .node,
+ .errstr,
+ .filename, and
+ .command.
+ The filename is not necessarily
+ the same file as the node; the
+ node is the target that was
+ being built when the error occurred, while the
+ filenameis the file or dir that
+ actually caused the error.
+ Note: only call GetBuildFailures
at the end of the
+ build; calling it at any other time is undefined.
+
+ GetBuildFailures
into a string:
+
+
# Make the build fail if we pass fail=1 on the command line
+ if ARGUMENTS.get('fail', 0):
+ Command('target', 'source', ['/bin/false'])
+
+ def bf_to_str(bf):
+ """Convert an element of GetBuildFailures() to a string
+ in a useful way."""
+ import SCons.Errors
+ if bf is None: # unknown targets product None in list
+ return '(unknown tgt)'
+ elif isinstance(bf, SCons.Errors.StopError):
+ return str(bf)
+ elif bf.node:
+ return str(bf.node) + ': ' + bf.errstr
+ elif bf.filename:
+ return bf.filename + ': ' + bf.errstr
+ return 'unknown failure: ' + bf.errstr
+ import atexit
+
+ def build_status():
+ """Convert the build status to a 2-tuple, (status, msg)."""
+ from SCons.Script import GetBuildFailures
+ bf = GetBuildFailures()
+ if bf:
+ # bf is normally a list of build failures; if an element is None,
+ # it's because of a target that scons doesn't know anything about.
+ status = 'failed'
+ failures_message = "\n".join(["Failed building %s" % bf_to_str(x)
+ for x in bf if x is not None])
+ else:
+ # if bf is None, the build completed successfully.
+ status = 'ok'
+ failures_message = ''
+ return (status, failures_message)
+
+ def display_build_status():
+ """Display the build status. Called by atexit.
+ Here you could do all kinds of complicated things."""
+ status, failures_message = build_status()
+ if status == 'failed':
+ print "FAILED!!!!" # could display alert, ring bell, etc.
+ elif status == 'ok':
+ print "Build succeeded."
+ print failures_message
+
+ atexit.register(display_build_status)
+
% scons -Q
+ scons: `.' is up to date.
+ Build succeeded.
+ % scons -Q fail=1
+ scons: *** Source `source' not found, needed by target `target'. Stop.
+ FAILED!!!!
+ Failed building Source `source' not found, needed by target `target'.
+
9.1. Not Having to Specify Command-Line Options Each Time: the
SCONSFLAGS
Environment VariableSCONSFLAGS
to a string containing
- command-line options that you want SCons to use.
-
- SCONSFLAGS
- environment as follows:
-
-
% scons
- scons: Reading SConscript files ...
- scons: done reading SConscript files.
- scons: Building targets ...
- ... [build output] ...
- scons: done building targets.
- % export SCONSFLAGS="-Q"
- % scons
- ... [build output] ...
-
SCONSFLAGS
environment as follows:
-
-
$ setenv SCONSFLAGS "-Q"
-
SCONSFLAGS
in the appropriate tab of the
- System Properties window.
-
- 9.2. Getting at Command-Line Targets
COMMAND_LINE_TARGETS
variable
- that lets you get at the list of targets that the
- user specified on the command line.
- You can use the targets to manipulate the
- build in any way you wish.
- As a simple example,
- suppose that you want to print a reminder
- to the user whenever a specific program is built.
- You can do this by checking for the
- target in the COMMAND_LINE_TARGETS
list:
-
-
if 'bar' in COMMAND_LINE_TARGETS:
- print "Don't forget to copy `bar' to the archive!"
- Default(Program('foo.c'))
- Program('bar.c')
-
% scons -Q
- cc -o foo.o -c foo.c
- cc -o foo foo.o
- % scons -Q bar
- Don't forget to copy `bar' to the archive!
- cc -o bar.o -c bar.c
- cc -o bar bar.o
-
COMMAND_LINE_TARGETS
variable
- might be to speed up a build
- by only reading certain subsidiary provides ways for you to examind
+ and set options values from within your SConscript
- files if a specific target is requested.
+> files,
+ as well as the ability to define your own
+ custom options.
+ See Section 12.1, below.
variable
=value
+ SCons provides direct access to
+ all of the command-line variable settings,
+ the ability to apply command-line variable settings
+ to construction environments,
+ and functions for configuring
+ specific types of variables
+ (Boolean values, path names, etc.)
+ with automatic validation of the user's specified values.
+ See Section 12.2, below.
+
+ 9.3. Controlling the Default Targets12.1. Command-Line Options
Default
function:
-
-
env = Environment()
- hello = env.Program('hello.c')
- env.Program('goodbye.c')
- Default(hello)
-
% scons -QSCons command-line option
- cc -o hello.o -c hello.c
- cc -o hello hello.o
- % scons -Q
- scons: `hello' is up to date.
- % scons -Q goodbye
- cc -o goodbye.o -c goodbye.c
- cc -o goodbye goodbye.o
-
Default
- function in your SConstruct file,
- you can still explicitly specify the current directory
- (.) on the command line
- to tell SCons to build
- everything in (or below) the current directory:
+>- (hyphen)
+ characters.
% scons -Q .
- cc -o goodbye.o -c goodbye.c
- cc -o goodbye goodbye.o
- cc -o hello.o -c hello.c
- cc -o hello hello.o
-
Default
- function more than once,
- in which case each call
- adds to the list of targets to be built by default:
-
-
env = Environment()
- prog1 = env.Program('prog1.c')
- Default(prog1)
- prog2 = env.Program('prog2.c')
- prog3 = env.Program('prog3.c')
- Default(prog3)
-
Default
function:
-
-
env = Environment()
- prog1 = env.Program('prog1.c')
- prog2 = env.Program('prog2.c')
- prog3 = env.Program('prog3.c')
- Default(prog1, prog3)
-
% scons -Q
- cc -o prog1.o -c prog1.c
- cc -o prog1 prog1.o
- cc -o prog3.o -c prog3.c
- cc -o prog3 prog3.o
- % scons -Q .
- cc -o prog2.o -c prog2.c
- cc -o prog2 prog2.o
-
Default
:
-
-
env = Environment()
- env.Program(['prog1/main.c', 'prog1/foo.c'])
- env.Program(['prog2/main.c', 'prog2/bar.c'])
- Default('prog1')
-
% scons -Q
- cc -o prog1/foo.o -c prog1/foo.c
- cc -o prog1/main.o -c prog1/main.c
- cc -o prog1/main prog1/main.o prog1/foo.o
- % scons -Q
- scons: `prog1' is up to date.
- % scons -Q .
- cc -o prog2/bar.o -c prog2/bar.c
- cc -o prog2/main.o -c prog2/main.c
- cc -o prog2/main prog2/main.o prog2/bar.o
-
env = Environment()
- prog1 = env.Program('prog1.c')
- prog2 = env.Program('prog2.c')
- Default(None)
-
% scons -Q
- scons: *** No targets specified and no Default() targets found. Stop.
- % scons -Q .
- cc -o prog1.o -c prog1.c
- cc -o prog1 prog1.o
- cc -o prog2.o -c prog2.c
- cc -o prog2 prog2.o
-
9.3.1. Getting at the List of Default Targets12.1.1. Not Having to Specify Command-Line Options Each Time: the
SCONSFLAGS
Environment VariableSCONSFLAGS
to a string containing
+ command-line options that you want SCons to use.
+
+ SCONSFLAGS
+ environment as follows:
+
+
% scons
+ scons: Reading SConscript files ...
+ scons: done reading SConscript files.
+ scons: Building targets ...
+ ... [build output] ...
+ scons: done building targets.
+ % export SCONSFLAGS="-Q"
+ % scons
+ ... [build output] ...
+
SCONSFLAGS
environment as follows:
+
+
$ setenv SCONSFLAGS "-Q"
+
SCONSFLAGS
in the appropriate tab of the
+ System Properties window.
+
+ 12.1.2. Getting Values Set by Command-Line Options: the
GetOption
FunctionDEFAULT_TARGETS
variable
- that lets you get at the current list of default targets.
- The DEFAULT_TARGETS
variable has
- two important differences from the COMMAND_LINE_TARGETS
variable.
- First, the DEFAULT_TARGETS
variable is a list of
- internal SCons nodes,
- so you need to convert the list elements to strings
- if you want to print them or look for a specific target name.
- Fortunately, you can do this easily
- by using the Python provides the
function
- to run the list through map
GetOptionstr
:
-
-
prog1 = Program('prog1.c')
- Default(prog1)
- print "DEFAULT_TARGETS is", map(str, DEFAULT_TARGETS)
-
DEFAULT_TARGETS
list takes place during the
- first phase when -h or --help option
+ has been specified.
+ Normally, SCons is reading up the does not print its help text
+ until after it has read all of the SConscript files,
- which is obvious if
- we leave off the -Q flag when we run SCons:)
+ because it's possible that help text has been added
+ by some subsidiary SConscript file deep in the
+ source tree hierarchy.
+ Of course, reading all of the SConscript files
+ takes extra time.
% scons
- scons: Reading SConscript files ...
- DEFAULT_TARGETS is ['prog1']
- scons: done reading SConscript files.
- scons: Building targets ...
- cc -o prog1.o -c prog1.c
- cc -o prog1 prog1.o
- scons: done building targets.
-
DEFAULT_TARGETS
list change
- in response to calls to the Default
: function,
- as you can see from the following SConstruct file:
+>SConscript files,
+ you can speed up the command-line help available to users
+ by using the GetOption
function to load the
+ subsidiary SConscript files only if the
+ the user has not specified
+ the -h or --help option,
+ like so:
prog1 = Program('prog1.c')
- Default(prog1)
- print "DEFAULT_TARGETS is now", map(str, DEFAULT_TARGETS)
- prog2 = Program('prog2.c')
- Default(prog2)
- print "DEFAULT_TARGETS is now", map(str, DEFAULT_TARGETS)
-
% scons
- scons: Reading SConscript files ...
- DEFAULT_TARGETS is now ['prog1']
- DEFAULT_TARGETS is now ['prog1', 'prog2']
- scons: done reading SConscript files.
- scons: Building targets ...
- cc -o prog1.o -c prog1.c
- cc -o prog1 prog1.o
- cc -o prog2.o -c prog2.c
- cc -o prog2 prog2.o
- scons: done building targets.
-
Default
function
- and refer to the DEFAULT_TARGETS
list,
- to make sure that you don't examine the
- list before you've added the default targets
- you expect to find in it.
+>GetOption function to fetch the value of a command-line
+ option setting is the same as the "most common" long option name
+ (beginning with two hyphen characters),
+ although there are some exceptions.
+ The list of SCons command-line options
+ and the GetOption
strings for fetching them,
+ are available in the
+ Section 12.1.4 section,
+ below.
12.1.3. Setting Values of Command-Line Options: the 9.4. Getting at the List of Build Targets, Regardless of Origin
SetOption
FunctionCOMMAND_LINE_TARGETS
variable,
- which contains a list of targets specified on the command line,
- and the DEFAULT_TARGETS
variable,
- which contains a list of targets specified
- via calls to the Default
method or function.
- Sometimes, however,
- you want a list of whatever targets
- SCons will try to build,
- regardless of whether the targets came from the
- command line or a Default
call.
- You could code this up by hand, as follows:
-
-
if COMMAND_LINE_TARGETS:
- targets = COMMAND_LINE_TARGETS
- else:
- targets = DEFAULT_TARGETS
-
BUILD_TARGETS
variable
- that eliminates the need for this by-hand manipulation.
- Essentially, the BUILD_TARGETS
variable
- contains a list of the command-line targets,
- if any were specified,
- and if no command-line targets were specified,
- it contains a list of the targets specified
- via the Default
method or function.
-
- BUILD_TARGETS
may contain a list of SCons nodes,
- you must convert the list elements to strings
- if you want to print them or look for a specific target name,
- just like the DEFAULT_TARGETS
list:
-
-
prog1 = Program('prog1.c')
- Program('prog2.c')
- Default(prog1)
- print "BUILD_TARGETS is", map(str, BUILD_TARGETS)
-
BUILD_TARGETS
- changes depending on whether a target is
- specified on the command line:
+ command-line options from within the SConscript files
+ by using the SetOption
function.
+ The strings that you use to set the values of SCons
+ command-line options are available in the
+ Section 12.1.4 section,
+ below.
- SetOption
function is to
+ specify a value for the -j
+ or --jobs option,
+ so that users get the improved performance
+ of a parallel build without having to specify the option by hand.
+ A complicating factor is that a good value
+ for the -j option is
+ somewhat system-dependent.
+ One rough guideline is that the more processors
+ your system has,
+ the higher you want to set the
+ -j value,
+ in order to take advantage of the number of CPUs.
+
+ NUM_CPU
environment variable
+ to the number of processors on each system.
+ A little bit of Python code
+ to access the environment variable
+ and the SetOption
function
+ provide the right level of flexibility:
+
+
import os
+ num_cpu = int(os.environ.get('NUM_CPU', 2))
+ SetOption('num_jobs', num_cpu)
+ print "running with -j", GetOption('num_jobs')
+
$NUM_CPU
environment variable.
+ (This is one of the exception cases
+ where the string is spelled differently from
+ the from command-line option.
+ The string for fetching or setting the --jobs
+ value is num_jobs
+ for historical reasons.)
+ The code in this example prints the num_jobs
+ value for illustrative purposes.
+ It uses a default value of 2
+ to provide some minimal parallelism even on
+ single-processor systems:
+
+
%
% scons -Q
- BUILD_TARGETS is ['prog1']
- cc -o prog1.o -c prog1.c
- cc -o prog1 prog1.o
- % scons -Q prog2
scons -Q
+ running with -j 4
+ scons: `.' is up to date.
+ $NUM_CPU
- BUILD_TARGETS is ['prog2']
- cc -o prog2.o -c prog2.c
- cc -o prog2 prog2.o
- %
% scons -Q -c .export NUM_CPU="4"
- BUILD_TARGETS is ['.']
- Removed prog1.o
- Removed prog1
- Removed prog2.o
- Removed prog2
- $NUM_CPU
environment
+ variable is set:
+
+
% scons -Q -j 7
+ running with -j 7
+ scons: `.' is up to date.
+ % export NUM_CPU="4"
+ % scons -Q -j 3
+ running with -j 3
+ scons: `.' is up to date.
+
12.1.4. Strings for Getting or Setting Values of SCons Command-Line Options
GetOption
+ and SetOption
functions usually correspond to the
+ first long-form option name
+ (beginning with two hyphen characters: --),
+ after replacing any remaining hyphen characters
+ with underscores.
+
+ String for GetOption
and SetOption
Command-Line Option(s) cache_debug --cache-debug
cache_disable --cache-disable
cache_force --cache-force
cache_show --cache-show
clean -c
,
+ --clean
,
+ --remove
config --config
directory -C
,
+ --directory
diskcheck --diskcheck
duplicate --duplicate
file -f
,
+ --file
,
+ --makefile
,
+ --sconstruct
help -h
,
+ --help
ignore_errors --ignore-errors
implicit_cache --implicit-cache
implicit_deps_changed --implicit-deps-changed
implicit_deps_unchanged --implicit-deps-unchanged
interactive --interact
,
+ --interactive
keep_going -k
,
+ --keep-going
max_drift --max-drift
no_exec -n
,
+ --no-exec
,
+ --just-print
,
+ --dry-run
,
+ --recon
no_site_dir --no-site-dir
num_jobs -j
,
+ --jobs
profile_file --profile
question -q
,
+ --question
random --random
repository -Y
,
+ --repository
,
+ --srcdir
silent -s
,
+ --silent
,
+ --quiet
site_dir --site-dir
stack_size --stack-size
taskmastertrace_file --taskmastertrace
warn --warn
--warning
12.1.5. Adding Custom Command-Line Options: the
AddOption
FunctionAddOption
function.
+ The AddOption
function takes the same arguments
+ as the optparse.add_option
function
+ from the standard Python library.
+ [3]
+ Once you have added a custom command-line option
+ with the AddOption
function,
+ the value of the option (if any) is immediately available
+ using the standard GetOption
function.
+ (The value can also be set using SetOption
,
+ although that's not very useful in practice
+ because a default value can be specified in
+ directly in the AddOption
call.)
+
+ --prefix
for users:
+
+
AddOption('--prefix',
+ dest='prefix',
+ type='string',
+ nargs=1,
+ action='store',
+ metavar='DIR',
+ help='installation prefix')
+
+ env = Environment(PREFIX = GetOption('prefix'))
+
+ installed_foo = env.Install('$PREFIX/usr/bin', 'foo.in')
+ Default(installed_foo)
+
GetOption
function
+ to set the $PREFIX
+ construction variable to any
+ value that the user specifies with a command-line
+ option of --prefix.
+ Because $PREFIX
+ will expand to a null string if it's not initialized,
+ running SCons without the
+ option of --prefix
+ will install the file in the
+ /usr/bin/ directory:
+
+
% scons -Q -n
+ Install file: "foo.in" as "/usr/bin/foo.in"
+
% scons -Q -n --prefix=/tmp/install
+ Install file: "foo.in" as "/tmp/install/usr/bin/foo.in"
+
9.5. Command-Line
12.2. Command-Line
Build Variablesvariable
=value
Build Options9.6. Controlling Command-Line Build Options
ARGUMENTS
dictionary has two minor drawbacks.
+ First, because it is a dictionary,
+ it can only store one value for each specified keyword,
+ and thus only "remembers" the last setting
+ for each keyword on the command line.
+ This makes the ARGUMENTS
dictionary
+ inappropriate if users should be able to
+ specify multiple values
+ on the command line for a given keyword.
+ Second, it does not preserve
+ the order in which the variable settings
+ were specified,
+ which is a problem if
+ you want the configuration to
+ behave differently in response
+ to the order in which the build
+ variable settings were specified on the command line.
SCons provides an
ARGLIST
variable
+ that gives you direct access to
+ variable
=value
+ settings on the command line,
+ in the exact order they were specified,
+ and without removing any duplicate settings.
+ Each element in the ARGLIST
variable
+ is itself a two-element list
+ containing the keyword and the value
+ of the setting,
+ and you must loop through,
+ or otherwise select from,
+ the elements of ARGLIST
to
+ process the specific settings you want
+ in whatever way is appropriate for your configuration.
+ For example,
+ the following code to let the user
+ add to the CPPDEFINES
construction variable
+ by specifying multiple
+ define=
+ settings on the command line:
+
+
cppdefines = []
+ for key, value in ARGLIST:
+ if key == 'define':
+ cppdefines.append(value)
+ env = Environment(CPPDEFINES = cppdefines)
+ env.Object('prog.c')
+
% scons -Q define=FOO
+ cc -o prog.o -c -DFOO prog.c
+ % scons -Q define=FOO define=BAR
+ cc -o prog.o -c -DFOO -DBAR prog.c
+
ARGLIST
and ARGUMENTS
+ variables do not interfere with each other,
+ but merely provide slightly different views
+ into how the user specified
+ variable
=value
+ settings on the command line.
+ You can use both variables in the same
+ SCons configuration.
+ In general, the ARGUMENTS
dictionary
+ is more convenient to use,
+ (since you can just fetch variable
+ settings through a dictionary access),
+ and the ARGLIST
list
+ is more flexible
+ (since you can examine the
+ specific order in which
+ the user's command-line variabe settings).
+
+ 12.2.1. Controlling Command-Line Build Variables
RELEASE
construction variable on the
- command line whenever the time comes to build
- a program for release,
- and that the value of this variable
- should be added to the command line
- with the appropriate -D option
- (or other command line option)
- to pass the value to the C compiler.
- Here's how you might do that by setting
- the appropriate value in a dictionary for the
- construction variable:
-
opts = Options()
- opts.Add('RELEASE', 'Set to 1 to build for release', 0)
- env = Environment(options = opts,
- CPPDEFINES={'RELEASE_BUILD' : '${RELEASE}'})
- env.Program(['foo.c', 'bar.c'])
-
Options
object
- (the opts = Options() call),
- and then uses the object's Add
- method to indicate that the RELEASE
- option can be set on the command line,
- and that it's default value will be 0
- (the third argument to the Add
method).
- The second argument is a line of help text;
- we'll learn how to use it in the next section.
-
- Options
- object as an options
keyword argument
- to the Environment
call
- used to create the construction environment.
- This then allows a user to set the
- RELEASE
build option on the command line
- and have the variable show up in
- the command line used to build each object from
- a C source file:
-
-
% scons -Q RELEASE=1
- cc -o bar.o -c -DRELEASE_BUILD=1 bar.c
- cc -o foo.o -c -DRELEASE_BUILD=1 foo.c
- cc -o foo foo.o bar.o
-
9.7. Providing Help for Command-Line Build Options
Options
objects support a
- GenerateHelpText
method
- that will, as its name indicates,
- generate text that describes
- the various options that
- have been added to it.
- You then pass the output from this method to
- the Help
function:
-
-
opts = Options('custom.py')
- opts.Add('RELEASE', 'Set to 1 to build for release', 0)
- env = Environment(options = opts)
- Help(opts.GenerateHelpText(env))
-
% scons -Q -h
-
- RELEASE: Set to 1 to build for release
- default: 0
- actual: 0
-
- Use scons -H for help about command-line options.
-
9.8. Reading Build Options From a File
Options
,
- like custom.py in the following example:
-
-
opts = Options('custom.py')
- opts.Add('RELEASE', 'Set to 1 to build for release', 0)
- env = Environment(options = opts,
- CPPDEFINES={'RELEASE_BUILD' : '${RELEASE}'})
- env.Program(['foo.c', 'bar.c'])
- Help(opts.GenerateHelpText(env))
-
RELEASE
- variable by setting it in the custom.py file:
-
-
RELEASE = 1
+>
vars = Variables()
+ vars.Add('RELEASE', 'Set to 1 to build for release', 0)
+ env = Environment(variables = vars,
+ CPPDEFINES={'RELEASE_BUILD' : '${RELEASE}'})
+ env.Program(['foo.c', 'bar.c'])
% scons -Q
- cc -o bar.o -c -DRELEASE_BUILD=1 bar.c
- cc -o foo.o -c -DRELEASE_BUILD=1 foo.c
- cc -o foo foo.o bar.o
-
Variables
object
+ (the vars = Variables() call),
+ and then uses the object's Add
+ method to indicate that the RELEASE
+ variable can be set on the command line,
+ and that its default value will be 0
+ (the third argument to the Add
method).
+ The second argument is a line of help text;
+ we'll learn how to use it in the next section.
-
RELEASE = 0
-
Variables
+ object as a variables
keyword argument
+ to the Environment
call
+ used to create the construction environment.
+ This then allows a user to set the
+ RELEASE
build variable on the command line
+ and have the variable show up in
+ the command line used to build each object from
+ a C source file:
-
%
% scons -Qscons -Q RELEASE=1
- cc -o bar.o -c -DRELEASE_BUILD=0 bar.c
- cc -o foo.o -c -DRELEASE_BUILD=0 foo.c
- cc -o foo foo.o bar.o
-
9.9. Canned Build Options
Options
class,
+ and in the sections below,
+ the various functions were named
+ BoolOption
, EnumOption
, ListOption
,
+ PathOption
, PackageOption
and AddOptions
.
+ These older names still work,
+ and you may encounter them in older
+ SConscript fles,
+ but their use is discouraged
+ and will be officially deprecated some day.
- 9.9.1. True/False Values: the
BoolOption
Build Option12.2.2. Providing Help for Command-Line Build VariablesVariables
objects support a
+ GenerateHelpText
method
+ that will, as its name suggests,
+ generate text that describes
+ the various variables that
+ have been added to it.
+ You then pass the output from this method to
+ the Help
function:
+
+
vars = Variables('custom.py')
+ vars.Add('RELEASE', 'Set to 1 to build for release', 0)
+ env = Environment(variables = vars)
+ Help(vars.GenerateHelpText(env))
+
% scons -Q -h
+
+ RELEASE: Set to 1 to build for release
+ default: 0
+ actual: 0
+
+ Use scons -H for help about command-line options.
+
12.2.3. Reading Build Variables From a File
Variables
object:
+
+
vars = Variables('custom.py')
+ vars.Add('RELEASE', 'Set to 1 to build for release', 0)
+ env = Environment(variables = vars,
+ CPPDEFINES={'RELEASE_BUILD' : '${RELEASE}'})
+ env.Program(['foo.c', 'bar.c'])
+ Help(vars.GenerateHelpText(env))
+
RELEASE
+ variable by setting it in the custom.py file:
+
+
RELEASE = 1
+
% scons -Q
+ cc -o bar.o -c -DRELEASE_BUILD=1 bar.c
+ cc -o foo.o -c -DRELEASE_BUILD=1 foo.c
+ cc -o foo foo.o bar.o
+
RELEASE = 0
+
% scons -Q
+ cc -o bar.o -c -DRELEASE_BUILD=0 bar.c
+ cc -o foo.o -c -DRELEASE_BUILD=0 foo.c
+ cc -o foo foo.o bar.o
+
12.2.4. Pre-Defined Build Variable Functions
12.2.4.1. True/False Values: the
BoolVariable
Build Variable FunctionBoolOption
BoolVariable function
- makes it easy to accomodate a variety of
- common values that represent
- true or false.
- BoolOption
BoolVariable function takes three arguments:
- the name of the build option,
- the default value of the build option,
- and the help string for the option.
- It then returns appropriate information for
- passing to the Add
method of an method of a
object, like so:
- Options
Variables
opts = Options('custom.py')
- opts.Add(BoolOption('RELEASE', 'Set to build for release', 0))
- env = Environment(options = opts,
- CPPDEFINES={'RELEASE_BUILD' : '${RELEASE}'})
- env.Program('foo.c')
-
vars = Variables('custom.py')
+ vars.Add(BoolVariable('RELEASE', 'Set to build for release', 0))
+ env = Environment(variables = vars,
+ CPPDEFINES={'RELEASE_BUILD' : '${RELEASE}'})
+ env.Program('foo.c')
+ RELEASE
variable can now be enabled by
- setting it to the value yes
- or t:
-
%
% scons -Q RELEASE=yes foo.o
- cc -o foo.o -c -DRELEASE_BUILD=True foo.c
-
%
% scons -Q RELEASE=t foo.o
- cc -o foo.o -c -DRELEASE_BUILD=True foo.c
-
RELEASE
may now be given a false
- value by setting it to
- no
- or
- f:
-
%
% scons -Q RELEASE=no foo.o
- cc -o foo.o -c -DRELEASE_BUILD=False foo.c
-
%
% scons -Q RELEASE=f foo.o
- cc -o foo.o -c -DRELEASE_BUILD=False foo.c
-
%
% scons -Q RELEASE=bad_value foo.o
-
- scons: *** Error converting option: RELEASE
- Invalid value for boolean option: bad_value
- File "/home/my/project/SConstruct", line 4, in <module>
-
EnumVariable Build Variable Function9.9.2. Single Value From a List: the
12.2.4.2. Single Value From a List: the
EnumOption
Build OptionCOLOR
option
- that selects a background color to be
- displayed by an application,
- but that we want to restrict the
- choices to a specific set of allowed colors.
- This can be set up quite easily
- using the variable
+ that selects a background color to be
+ displayed by an application,
+ but that we want to restrict the
+ choices to a specific set of allowed colors.
+ This can be set up quite easily
+ using the
,
- which takes a list of EnumOption
EnumVariableallowed_values
in addition to the variable name,
- default value,
- and help text arguments:
+> in addition to the variable name,
+ default value,
+ and help text arguments:
-
opts = Options('custom.py')
- opts.Add(EnumOption('COLOR', 'Set background color', 'red',
- allowed_values=('red', 'green', 'blue')))
- env = Environment(options = opts,
- CPPDEFINES={'COLOR' : '"${COLOR}"'})
- env.Program('foo.c')
-
vars = Variables('custom.py')
+ vars.Add(EnumVariable('COLOR', 'Set background color', 'red',
+ allowed_values=('red', 'green', 'blue')))
+ env = Environment(variables = vars,
+ CPPDEFINES={'COLOR' : '"${COLOR}"'})
+ env.Program('foo.c')
+ COLOR
build option
- to any of the specified allowed values:
+> build variable
+ to any of the specified allowed values:
-
%
% scons -Q COLOR=red foo.o
- cc -o foo.o -c -DCOLOR="red" foo.c
- % scons -Q COLOR=blue foo.o
- cc -o foo.o -c -DCOLOR="blue" foo.c
- % scons -Q COLOR=green foo.o
- cc -o foo.o -c -DCOLOR="green" foo.c
-
COLOR
- to a value that's not in the list
- generates an error message:
+ to a value that's not in the list
+ generates an error message:
-
%
% scons -Q COLOR=magenta foo.o
-
- scons: *** Invalid value for option COLOR: magenta
- File "/home/my/project/SConstruct", line 5, in <module>
-
EnumOption
EnumVariable function also supports a way
- to map alternate names to allowed values.
- Suppose, for example,
- that we want to allow the user
- to use the word navy as a synonym for
- blue.
- We do this by adding a map
dictionary
- that will map its key values
- to the desired legal value:
+ that will map its key values
+ to the desired legal value:
-
opts = Options('custom.py')
- opts.Add(EnumOption('COLOR', 'Set background color', 'red',
- allowed_values=('red', 'green', 'blue'),
- map={'navy':'blue'}))
- env = Environment(options = opts,
- CPPDEFINES={'COLOR' : '"${COLOR}"'})
- env.Program('foo.c')
-
vars = Variables('custom.py')
+ vars.Add(EnumVariable('COLOR', 'Set background color', 'red',
+ allowed_values=('red', 'green', 'blue'),
+ map={'navy':'blue'}))
+ env = Environment(variables = vars,
+ CPPDEFINES={'COLOR' : '"${COLOR}"'})
+ env.Program('foo.c')
+ COLOR
- option to build a target:
+ variable to build a target:
-
%
% scons -Q COLOR=navy foo.o
- cc -o foo.o -c -DCOLOR="blue" foo.c
-
EnumOption
EnumVariable function,
- arguments that differ
- from the legal values
- only in case
- are treated as illegal values:
+ arguments that differ
+ from the legal values
+ only in case
+ are treated as illegal values:
-
%
% scons -Q COLOR=Red foo.o
-
- scons: *** Invalid value for option COLOR: Red
- File "/home/my/project/SConstruct", line 5, in <module>
- % scons -Q COLOR=BLUE foo.o
-
- scons: *** Invalid value for option COLOR: BLUE
- File "/home/my/project/SConstruct", line 5, in <module>
- % scons -Q COLOR=nAvY foo.o
-
- scons: *** Invalid value for option COLOR: nAvY
- File "/home/my/project/SConstruct", line 5, in <module>
-
EnumOption
EnumVariable function can take an additional
- ignorecase
keyword argument that,
- when set to 1,
- tells SCons to allow case differences
- when the values are specified:
+ when the values are specified:
-
opts = Options('custom.py')
- opts.Add(EnumOption('COLOR', 'Set background color', 'red',
- allowed_values=('red', 'green', 'blue'),
- map={'navy':'blue'},
- ignorecase=1))
- env = Environment(options = opts,
- CPPDEFINES={'COLOR' : '"${COLOR}"'})
- env.Program('foo.c')
-
vars = Variables('custom.py')
+ vars.Add(EnumVariable('COLOR', 'Set background color', 'red',
+ allowed_values=('red', 'green', 'blue'),
+ map={'navy':'blue'},
+ ignorecase=1))
+ env = Environment(variables = vars,
+ CPPDEFINES={'COLOR' : '"${COLOR}"'})
+ env.Program('foo.c')
+
%
% scons -Q COLOR=Red foo.o
- cc -o foo.o -c -DCOLOR="Red" foo.c
- % scons -Q COLOR=BLUE foo.o
- cc -o foo.o -c -DCOLOR="BLUE" foo.c
- % scons -Q COLOR=nAvY foo.o
- cc -o foo.o -c -DCOLOR="blue" foo.c
- % scons -Q COLOR=green foo.o
- cc -o foo.o -c -DCOLOR="green" foo.c
-
ignorecase
value of 1
- preserves the case-spelling that the user supplied.
- If you want SCons to translate the names
- into lower-case,
- regardless of the case used by the user,
- specify an ignorecase
value of 2:
-
opts = Options('custom.py')
- opts.Add(EnumOption('COLOR', 'Set background color', 'red',
- allowed_values=('red', 'green', 'blue'),
- map={'navy':'blue'},
- ignorecase=2))
- env = Environment(options = opts,
- CPPDEFINES={'COLOR' : '"${COLOR}"'})
- env.Program('foo.c')
-
vars = Variables('custom.py')
+ vars.Add(EnumVariable('COLOR', 'Set background color', 'red',
+ allowed_values=('red', 'green', 'blue'),
+ map={'navy':'blue'},
+ ignorecase=2))
+ env = Environment(variables = vars,
+ CPPDEFINES={'COLOR' : '"${COLOR}"'})
+ env.Program('foo.c')
+
%
% scons -Q COLOR=Red foo.o
- cc -o foo.o -c -DCOLOR="red" foo.c
- % scons -Q COLOR=nAvY foo.o
- cc -o foo.o -c -DCOLOR="blue" foo.c
- % scons -Q COLOR=GREEN foo.o
- cc -o foo.o -c -DCOLOR="green" foo.c
-
ListVariable Build Variable Function9.9.3. Multiple Values From a List: the
12.2.4.3. Multiple Values From a List: the
ListOption
Build OptionListOption
ListVariable function.
- If, for example, we want a user to be able to set a
- COLORS
option to one or more of the legal list of values:
+> variable to one or more of the legal list of values:
-
opts = Options('custom.py')
- opts.Add(ListOption('COLORS', 'List of colors', 0,
- ['red', 'green', 'blue']))
- env = Environment(options = opts,
- CPPDEFINES={'COLORS' : '"${COLORS}"'})
- env.Program('foo.c')
-
vars = Variables('custom.py')
+ vars.Add(ListVariable('COLORS', 'List of colors', 0,
+ ['red', 'green', 'blue']))
+ env = Environment(variables = vars,
+ CPPDEFINES={'COLORS' : '"${COLORS}"'})
+ env.Program('foo.c')
+
%
% scons -Q COLORS=red,blue foo.o
- cc -o foo.o -c -DCOLORS="red blue" foo.c
- % scons -Q COLORS=blue,green,red foo.o
- cc -o foo.o -c -DCOLORS="blue green red" foo.c
-
ListOption
ListVariable function
- allows the user to specify explicit keywords of
- all or none
- to select all of the legal values,
- or none of them, respectively:
+ to select all of the legal values,
+ or none of them, respectively:
-
%
% scons -Q COLORS=all foo.o
- cc -o foo.o -c -DCOLORS="red green blue" foo.c
- % scons -Q COLORS=none foo.o
- cc -o foo.o -c -DCOLORS="" foo.c
-
%
% scons -Q COLORS=magenta foo.o
-
- scons: *** Error converting option: COLORS
- Invalid value(s) for option: magenta
- File "/home/my/project/SConstruct", line 5, in <module>
-
PathVariable Build Variable Function9.9.4. Path Names: the
12.2.4.4. Path Names: the
PathOption
Build OptionPathOption
PathVariable function
- to make it easy to create a build option
- to control an expected path name.
- If, for example, you need to
- define a variable in the preprocessor
- that controls the location of a
- configuration file:
+ to make it easy to create a build variable
+ to control an expected path name.
+ If, for example, you need to
+ define a variable in the preprocessor
+ that controls the location of a
+ configuration file:
-
opts = Options('custom.py')
- opts.Add(PathOption('CONFIG',
- 'Path to configuration file',
- '/etc/my_config'))
- env = Environment(options = opts,
- CPPDEFINES={'CONFIG_FILE' : '"$CONFIG"'})
- env.Program('foo.c')
-
vars = Variables('custom.py')
+ vars.Add(PathVariable('CONFIG',
+ 'Path to configuration file',
+ '/etc/my_config'))
+ env = Environment(variables = vars,
+ CPPDEFINES={'CONFIG_FILE' : '"$CONFIG"'})
+ env.Program('foo.c')
+ CONFIG
build option
- on the command line as necessary:
+> build variable
+ on the command line as necessary:
-
%
% scons -Q foo.o
- cc -o foo.o -c -DCONFIG_FILE="/etc/my_config" foo.c
- % scons -Q CONFIG=/usr/local/etc/other_config foo.o
- scons: `foo.o' is up to date.
-
PathOption
PathVariable checks to make sure
- that the specified path exists and generates an error if it
- doesn't:
+ that the specified path exists and generates an error if it
+ doesn't:
-
%
% scons -Q CONFIG=/does/not/exist foo.o
-
- scons: *** Path for option CONFIG does not exist: /does/not/exist
- File "/home/my/project/SConstruct", line 6, in <module>
-
PathOption
PathVariable provides a number of methods
- that you can use to change this behavior.
- If you want to ensure that any specified paths are,
- in fact, files and not directories,
- use the PathOption.PathIsFile
PathVariable.PathIsFile method:
-
opts = Options('custom.py')
- opts.Add(PathOption('CONFIG',
- 'Path to configuration file',
- '/etc/my_config',
- PathOption.PathIsFile))
- env = Environment(options = opts,
- CPPDEFINES={'CONFIG_FILE' : '"$CONFIG"'})
- env.Program('foo.c')
-
vars = Variables('custom.py')
+ vars.Add(PathVariable('CONFIG',
+ 'Path to configuration file',
+ '/etc/my_config',
+ PathVariable.PathIsFile))
+ env = Environment(variables = vars,
+ CPPDEFINES={'CONFIG_FILE' : '"$CONFIG"'})
+ env.Program('foo.c')
+ PathOption.PathIsDir
PathVariable.PathIsDir method:
-
opts = Options('custom.py')
- opts.Add(PathOption('DBDIR',
- 'Path to database directory',
- '/var/my_dbdir',
- PathOption.PathIsDir))
- env = Environment(options = opts,
- CPPDEFINES={'DBDIR' : '"$DBDIR"'})
- env.Program('foo.c')
-
vars = Variables('custom.py')
+ vars.Add(PathVariable('DBDIR',
+ 'Path to database directory',
+ '/var/my_dbdir',
+ PathVariable.PathIsDir))
+ env = Environment(variables = vars,
+ CPPDEFINES={'DBDIR' : '"$DBDIR"'})
+ env.Program('foo.c')
+ PathOption.PathIsDirCreate
PathVariable.PathIsDirCreate method:
-
opts = Options('custom.py')
- opts.Add(PathOption('DBDIR',
- 'Path to database directory',
- '/var/my_dbdir',
- PathOption.PathIsDirCreate))
- env = Environment(options = opts,
- CPPDEFINES={'DBDIR' : '"$DBDIR"'})
- env.Program('foo.c')
-
vars = Variables('custom.py')
+ vars.Add(PathVariable('DBDIR',
+ 'Path to database directory',
+ '/var/my_dbdir',
+ PathVariable.PathIsDirCreate))
+ env = Environment(variables = vars,
+ CPPDEFINES={'DBDIR' : '"$DBDIR"'})
+ env.Program('foo.c')
+ PathOption.PathAccept
PathVariable.PathAccept method
- to accept any path that the user supplies:
+ to accept any path that the user supplies:
-
opts = Options('custom.py')
- opts.Add(PathOption('OUTPUT',
- 'Path to output file or directory',
- None,
- PathOption.PathAccept))
- env = Environment(options = opts,
- CPPDEFINES={'OUTPUT' : '"$OUTPUT"'})
- env.Program('foo.c')
-
vars = Variables('custom.py')
+ vars.Add(PathVariable('OUTPUT',
+ 'Path to output file or directory',
+ None,
+ PathVariable.PathAccept))
+ env = Environment(variables = vars,
+ CPPDEFINES={'OUTPUT' : '"$OUTPUT"'})
+ env.Program('foo.c')
+
PackageVariable Build Variable Function9.9.5. Enabled/Disabled Path Names: the
12.2.4.5. Enabled/Disabled Path Names: the
PackageOption
Build OptionPackageOption
PackageVariable
- function to support this:
+ function to support this:
-
opts = Options('custom.py')
- opts.Add(PackageOption('PACKAGE',
- 'Location package',
- '/opt/location'))
- env = Environment(options = opts,
- CPPDEFINES={'PACKAGE' : '"$PACKAGE"'})
- env.Program('foo.c')
-
vars = Variables('custom.py')
+ vars.Add(PackageVariable('PACKAGE',
+ 'Location package',
+ '/opt/location'))
+ env = Environment(variables = vars,
+ CPPDEFINES={'PACKAGE' : '"$PACKAGE"'})
+ env.Program('foo.c')
+ PackageOption
PackageVariable funciton,
- user can now still use the default
- or supply an overriding path name,
- but can now explicitly set the
- specified variable to a value
- that indicates the package should be enabled
- (in which case the default should be used)
- or disabled:
+ user can now still use the default
+ or supply an overriding path name,
+ but can now explicitly set the
+ specified variable to a value
+ that indicates the package should be enabled
+ (in which case the default should be used)
+ or disabled:
+
+
% scons -Q foo.o
+ cc -o foo.o -c -DPACKAGE="/opt/location" foo.c
+ % scons -Q PACKAGE=/usr/local/location foo.o
+ cc -o foo.o -c -DPACKAGE="/usr/local/location" foo.c
+ % scons -Q PACKAGE=yes foo.o
+ cc -o foo.o -c -DPACKAGE="True" foo.c
+ % scons -Q PACKAGE=no foo.o
+ cc -o foo.o -c -DPACKAGE="False" foo.c
+
12.2.5. Adding Multiple Command-Line Build Variables at Once
Variables
object at once.
+ Instead of having to call the Add
method
+ multiple times,
+ you can call the AddVariables
+ method with a list of build variables
+ to be added to the object.
+ Each build variable is specified
+ as either a tuple of arguments,
+ just like you'd pass to the Add
method itself,
+ or as a call to one of the pre-defined
+ functions for pre-packaged command-line build variables.
+ in any order:
+
+
vars = Variables()
+ vars.AddVariables(
+ ('RELEASE', 'Set to 1 to build for release', 0),
+ ('CONFIG', 'Configuration file', '/etc/my_config'),
+ BoolVariable('warnings', 'compilation with -Wall and similiar', 1),
+ EnumVariable('debug', 'debug output and symbols', 'no',
+ allowed_values=('yes', 'no', 'full'),
+ map={}, ignorecase=0), # case sensitive
+ ListVariable('shared',
+ 'libraries to build as shared libraries',
+ 'all',
+ names = list_of_libs),
+ PackageVariable('x11',
+ 'use X11 installed here (yes = search some places)',
+ 'yes'),
+ PathVariable('qtdir', 'where the root of Qt is installed', qtdir),
+ )
+
12.2.6. Handling Unknown Command-Line Build Variables: the
UnknownVariables
FunctionARGUMENTS
dictionary,
+ and therefore SCons can't know in the general case
+ whether a given "misspelled" variable is
+ really unknown and a potential problem,
+ or something that your SConscript file
+ will handle directly with some Python code.)
+
+ Variables
object to
+ define a specific set of command-line build variables
+ that you expect users to be able to set,
+ you may want to provide an error
+ message or warning of your own
+ if the user supplies a variable setting
+ that is not among
+ the defined list of variable names known to the Variables
object.
+ You can do this by calling the UnknownVariables
+ method of the Variables
object:
+
+
vars = Variables(None)
+ vars.Add('RELEASE', 'Set to 1 to build for release', 0)
+ env = Environment(variables = vars,
+ CPPDEFINES={'RELEASE_BUILD' : '${RELEASE}'})
+ unknown = vars.UnknownVariables()
+ if unknown:
+ print "Unknown variables:", unknown.keys()
+ Exit(1)
+ env.Program('foo.c')
+
UnknownVariables
method returns a dictionary
+ containing the keywords and values
+ of any variables the user specified on the command line
+ that are not
+ among the variables known to the Variables
object
+ (from having been specified using
+ the Variables
object'sAdd
method).
+ In the examble above,
+ we check for whether the dictionary
+ returned by the UnknownVariables
is non-empty,
+ and if so print the Python list
+ containing the names of the unknwown variables
+ and then call the Exit
function
+ to terminate SCons:
% scons -Q foo.oscons -Q NOT_KNOWN=foo
- cc -o foo.o -c -DPACKAGE="/opt/location" foo.c
- % scons -Q PACKAGE=/usr/local/location foo.o
- cc -o foo.o -c -DPACKAGE="/usr/local/location" foo.c
- % scons -Q PACKAGE=yes foo.o
- cc -o foo.o -c -DPACKAGE="True" foo.c
- % scons -Q PACKAGE=no foo.o
- cc -o foo.o -c -DPACKAGE="False" foo.c
+ Unknown variables: ['NOT_KNOWN']
UnknownVariables
function
+ in any way appropriate to your bulid configuration,
+ including just printing a warning message
+ but not exiting,
+ logging an error somewhere,
+ etc.
+
+ UnknownVariables
+ until after you have applied the Variables
object
+ to a construction environment
+ with the variables=
+ keyword argument of an Environment
call.
+
+ 9.10. Adding Multiple Command-Line Build Options at Once12.3. Command-Line Targets
Options
object at once.
- Instead of having to call the Add
method
- multiple times,
- you can call the AddOptions
- method with a list of build options
- to be added to the object.
- Each build option is specified
- as either a tuple of arguments,
- just like you'd pass to the Add
method itself,
- or as a call to one of the canned
- functions for pre-packaged command-line build options.
- in any order:
-
-
opts = Options()
- opts.AddOptions(
- ('RELEASE', 'Set to 1 to build for release', 0),
- ('CONFIG', 'Configuration file', '/etc/my_config'),
- BoolOption('warnings', 'compilation with -Wall and similiar', 1),
- EnumOption('debug', 'debug output and symbols', 'no',
- allowed_values=('yes', 'no', 'full'),
- map={}, ignorecase=0), # case sensitive
- ListOption('shared',
- 'libraries to build as shared libraries',
- 'all',
- names = list_of_libs),
- PackageOption('x11',
- 'use X11 installed here (yes = search some places)',
- 'yes'),
- PathOption('qtdir', 'where the root of Qt is installed', qtdir),
- )
-
12.3.1. Fetching Command-Line Targets: the Chapter 10. Providing Build Help: the
Help
FunctionCOMMAND_LINE_TARGETS
VariableHelp
function
- to allow you to specify this help text:
+> supports a COMMAND_LINE_TARGETS
variable
+ that lets you fetch the list of targets that the
+ user specified on the command line.
+ You can use the targets to manipulate the
+ build in any way you wish.
+ As a simple example,
+ suppose that you want to print a reminder
+ to the user whenever a specific program is built.
+ You can do this by checking for the
+ target in the COMMAND_LINE_TARGETS
list:
-
Help("""
- Type: 'scons program' to build the production program,
- 'scons debug' to build the debug version.
- """)
-
if 'bar' in COMMAND_LINE_TARGETS:
+ print "Don't forget to copy `bar' to the archive!"
+ Default(Program('foo.c'))
+ Program('bar.c')
+ Help
function,
- the specified help text will be displayed in response to
- the SCons -h option:
+> with the default target
+ works as it always does,
+ but explicity specifying the bar target
+ on the command line generates the warning message:
-
%
% scons -hscons -Q
- scons: Reading SConscript files ...
- scons: done reading SConscript files.
-
- Type: 'scons program' to build the production program,
- 'scons debug' to build the debug version.
-
- Use scons -H for help about command-line options.
-
scons -Q bar
+ Don't forget to copy `bar' to the archive!
+ cc -o bar.o -c bar.c
+ cc -o bar bar.o
+ Help
function,
- in which case the specified text(s)
- will be concatenated when displayed.
- This allows you to split up the
- help text across multiple SConscript files.
- In this situation, the order in
- which the SConscript files are called
- will determine the order in which the Help
functions are called,
- which will determine the order in which
- the various bits of text will get concatenated.
+>
+ files if a specific target is requested.
- 12.3.2. Controlling the Default Targets: the
Default
FunctionDefault
function:
+
+
env = Environment()
+ hello = env.Program('hello.c')
+ env.Program('goodbye.c')
+ Default(hello)
+
% scons -Q
+ cc -o hello.o -c hello.c
+ cc -o hello hello.o
+ % scons -Q
+ scons: `hello' is up to date.
+ % scons -Q goodbye
+ cc -o goodbye.o -c goodbye.c
+ cc -o goodbye goodbye.o
+
Default
+ function in your SConstruct file,
+ you can still explicitly specify the current directory
+ (.) on the command line
+ to tell SCons to build
+ everything in (or below) the current directory:
+
+
% scons -Q .
+ cc -o goodbye.o -c goodbye.c
+ cc -o goodbye goodbye.o
+ cc -o hello.o -c hello.c
+ cc -o hello hello.o
+
Default
+ function more than once,
+ in which case each call
+ adds to the list of targets to be built by default:
+
+
env = Environment()
+ prog1 = env.Program('prog1.c')
+ Default(prog1)
+ prog2 = env.Program('prog2.c')
+ prog3 = env.Program('prog3.c')
+ Default(prog3)
+
Default
function:
+
+
env = Environment()
+ prog1 = env.Program('prog1.c')
+ prog2 = env.Program('prog2.c')
+ prog3 = env.Program('prog3.c')
+ Default(prog1, prog3)
+
% scons -Q
+ cc -o prog1.o -c prog1.c
+ cc -o prog1 prog1.o
+ cc -o prog3.o -c prog3.c
+ cc -o prog3 prog3.o
+ % scons -Q .
+ cc -o prog2.o -c prog2.c
+ cc -o prog2 prog2.o
+
Default
:
+
+
env = Environment()
+ env.Program(['prog1/main.c', 'prog1/foo.c'])
+ env.Program(['prog2/main.c', 'prog2/bar.c'])
+ Default('prog1')
+
% scons -Q
+ cc -o prog1/foo.o -c prog1/foo.c
+ cc -o prog1/main.o -c prog1/main.c
+ cc -o prog1/main prog1/main.o prog1/foo.o
+ % scons -Q
+ scons: `prog1' is up to date.
+ % scons -Q .
+ cc -o prog2/bar.o -c prog2/bar.c
+ cc -o prog2/main.o -c prog2/main.c
+ cc -o prog2/main prog2/main.o prog2/bar.o
+
env = Environment()
+ prog1 = env.Program('prog1.c')
+ prog2 = env.Program('prog2.c')
+ Default(None)
+
% scons -Q
+ scons: *** No targets specified and no Default() targets found. Stop.
+ % scons -Q .
+ cc -o prog1.o -c prog1.c
+ cc -o prog1 prog1.o
+ cc -o prog2.o -c prog2.c
+ cc -o prog2 prog2.o
+
12.3.2.1. Fetching the List of Default Targets: the
DEFAULT_TARGETS
VariableDEFAULT_TARGETS
variable
+ that lets you get at the current list of default targets.
+ The DEFAULT_TARGETS
variable has
+ two important differences from the COMMAND_LINE_TARGETS
variable.
+ First, the DEFAULT_TARGETS
variable is a list of
+ internal SCons nodes,
+ so you need to convert the list elements to strings
+ if you want to print them or look for a specific target name.
+ Fortunately, you can do this easily
+ by using the Python map
function
+ to run the list through str
:
+
+
prog1 = Program('prog1.c')
+ Default(prog1)
+ print "DEFAULT_TARGETS is", map(str, DEFAULT_TARGETS)
+
DEFAULT_TARGETS
list takes place during the
+ first phase when SCons is reading up the SConscript files,
+ which is obvious if
+ we leave off the -Q flag when we run SCons:)
+
+
% scons
+ scons: Reading SConscript files ...
+ DEFAULT_TARGETS is ['prog1']
+ scons: done reading SConscript files.
+ scons: Building targets ...
+ cc -o prog1.o -c prog1.c
+ cc -o prog1 prog1.o
+ scons: done building targets.
+
DEFAULT_TARGETS
list change
+ in response to calls to the Default
: function,
+ as you can see from the following SConstruct file:
-
env = Environment()
-
- Help("\nType: 'scons program' to build the production program.\n")
-
- if env['PLATFORM'] == 'win32':
- Help("\nType: 'scons windebug' to build the Windows debug version.\n")
-
prog1 = Program('prog1.c')
+ Default(prog1)
+ print "DEFAULT_TARGETS is now", map(str, DEFAULT_TARGETS)
+ prog2 = Program('prog2.c')
+ Default(prog2)
+ print "DEFAULT_TARGETS is now", map(str, DEFAULT_TARGETS)
+
C:\>
% scons -hscons
- scons: Reading SConscript files ...
- scons: done reading SConscript files.
-
- Type: 'scons program' to build the production program.
-
- Type: 'scons windebug' to build the Windows debug version.
-
- Use scons -H for help about command-line options.
-
% scons -h
- scons: Reading SConscript files ...
- scons: done reading SConscript files.
-
- Type: 'scons program' to build the production program.
-
- Use scons -H for help about command-line options.
-
Help
text in the SConstruct or
- SConscript files,
- SCons will revert to displaying its
- standard list that describes the SCons command-line
- options.
- This list is also always displayed whenever
- the -H option is used.
+>Default function
+ and refer to the DEFAULT_TARGETS
list,
+ to make sure that you don't examine the
+ list before you've added the default targets
+ you expect to find in it.
- 12.3.3. Fetching the List of Build Targets, Regardless of Origin: the
BUILD_TARGETS
VariableCOMMAND_LINE_TARGETS
variable,
+ which contains a list of targets specified on the command line,
+ and the DEFAULT_TARGETS
variable,
+ which contains a list of targets specified
+ via calls to the Default
method or function.
+ Sometimes, however,
+ you want a list of whatever targets
+ SCons will try to build,
+ regardless of whether the targets came from the
+ command line or a Default
call.
+ You could code this up by hand, as follows:
+
+
if COMMAND_LINE_TARGETS:
+ targets = COMMAND_LINE_TARGETS
+ else:
+ targets = DEFAULT_TARGETS
+
BUILD_TARGETS
variable
+ that eliminates the need for this by-hand manipulation.
+ Essentially, the BUILD_TARGETS
variable
+ contains a list of the command-line targets,
+ if any were specified,
+ and if no command-line targets were specified,
+ it contains a list of the targets specified
+ via the Default
method or function.
+
+ BUILD_TARGETS
may contain a list of SCons nodes,
+ you must convert the list elements to strings
+ if you want to print them or look for a specific target name,
+ just like the DEFAULT_TARGETS
list:
+
+
prog1 = Program('prog1.c')
+ Program('prog2.c')
+ Default(prog1)
+ print "BUILD_TARGETS is", map(str, BUILD_TARGETS)
+
BUILD_TARGETS
+ changes depending on whether a target is
+ specified on the command line:
+
+
% scons -Q
+ BUILD_TARGETS is ['prog1']
+ cc -o prog1.o -c prog1.c
+ cc -o prog1 prog1.o
+ % scons -Q prog2
+ BUILD_TARGETS is ['prog2']
+ cc -o prog2.o -c prog2.c
+ cc -o prog2 prog2.o
+ % scons -Q -c .
+ BUILD_TARGETS is ['.']
+ Removed prog1.o
+ Removed prog1
+ Removed prog2.o
+ Removed prog2
+
Chapter 13. Installing Files in Other Directories: the
Install
Builder11.1. Installing Multiple Files in a Directory13.1. Installing Multiple Files in a Directory
11.2. Installing a File Under a Different Name13.2. Installing a File Under a Different Name
11.3. Installing Multiple Files Under Different Names13.3. Installing Multiple Files Under Different Names
12.1. Copying Files or Directories: The
14.1. Copying Files or Directories: The
Copy
FactoryInstall
builder isn't appropriate
- because it may make a hard link on POSIX systems.
+ and don't have a suitable pre-existing builder.
+ [4]
One way would be to use the Copy
12.2. Deleting Files or Directories: The
14.2. Deleting Files or Directories: The
Delete
FactoryDelete
deletes its target(s)
for you before executing any action.
+ Delete
factory:
+ it has the same variable expansions available
+ as any other factory, including the $SOURCE
variable.
+ Specifying Delete("$SOURCE")
+ is not something you usually want to do!
+
12.3. Moving (Renaming) Files or Directories: The
14.3. Moving (Renaming) Files or Directories: The
Move
Factory12.4. Updating the Modification Time of a File: The
14.4. Updating the Modification Time of a File: The
Touch
Factory12.5. Creating a Directory: The
14.5. Creating a Directory: The
Mkdir
Factory12.6. Changing File or Directory Permissions: The
14.6. Changing File or Directory Permissions: The
Chmod
Factory12.7. Executing an action immediately: the
14.7. Executing an action immediately: the
SConscript file is read
- by wrapping it up in the Execute
FunctionExecute
function.
For example, if we need to make sure that
a directory exists before we build any targets,
-
is specified.
Execute
function returns the exit status
+ or return value of the underlying action being executed.
+ It will also print an error message if the action
+ fails and returns a non-zero value.
+ SCons will not, however,
+ actually stop the build if the action fails.
+ If you want the build to stop
+ in response to a failure in an action called by Execute
,
+ you must do so by explicitly
+ checking the return value
+ and calling the Exit
function
+ (or a Python equivalent):
+
+
if Execute(Mkdir('/tmp/my_temp_directory')):
+ # A problem occurred while making the temp directory.
+ Exit(1)
+
13.1. Preventing target removal during build: the
15.1. Preventing target removal during build: the
Precious
Function13.2. Preventing target removal during clean: the
15.2. Preventing target removal during clean: the
NoClean
Function13.3. Removing additional files during clean: the
15.3. Removing additional files during clean: the
Chapter 14. Hierarchical BuildsChapter 16. Hierarchical BuildsClean
Function14.1. 16.1. SConscript Files
14.2. Path Names Are Relative to the 16.2. Path Names Are Relative to the SConscript Directory
14.3. Top-Level Path Names in Subsidiary 16.3. Top-Level Path Names in Subsidiary SConscript FilesChapter 15Chapter 17, below,
for information about
how to build the object file in a different subdirectory.)
@@ -12698,8 +17141,8 @@ CLASS="section"
>
14.4. Absolute Path Names16.4. Absolute Path Names
14.5. Sharing Environments (and Other Variables) Between 16.5. Sharing Environments (and Other Variables) Between SConscript Files
14.5.1. Exporting Variables16.5.1. Exporting Variables
14.5.2. Importing Variables16.5.2. Importing Variables
14.5.3. Returning Values From an 16.5.3. Returning Values From an SConscript FileChapter 15. Separating Source and Build DirectoriesChapter 17. Separating Source and Build Directories
15.1. Specifying a Variant Directory Tree as Part of an 17.1. Specifying a Variant Directory Tree as Part of an SConscript Call
15.2. Why 17.2. Why SCons Duplicates Source Files in a Variant Directory Tree
15.3. Telling 17.3. Telling SCons to Not Duplicate Source Files in the Variant Directory Tree
15.4. The
17.4. The
VariantDir
Function15.5. Using
17.5. Using
VariantDir
With an 15.6. Using Glob() with
17.6. Using
Glob
with VariantDir
Glob
file name pattern matching function
works just as usual when using VariantDir
SConstruct file as in the previous section,
- and source files f1.c and f2.c in src, we would see the following
- output:
+ and source files f1.c
+ and f2.c in src,
+ we would see the following output:
Glob
function returns Nodes in the
+ build/ tree, as you'd expect.
Chapter 17. Writing Your Own BuildersChapter 19. Writing Your Own Builders
17.1. Writing Builders That Execute External Commands19.1. Writing Builders That Execute External Commands
17.2. Attaching a Builder to a 19.2. Attaching a Builder to a Construction Environment
17.3. Letting 19.3. Letting SCons Handle The File Suffixes
17.4. Builders That Execute Python Functions19.4. Builders That Execute Python Functions
@@ -14512,8 +18974,8 @@ CLASS="section" >
+ For example, suppose you want to define a Builder + that always calls a foobuild program, + and you want to automatically add + a new target file named + new_target + and a new source file named + new_source + whenever it's called. + The SConstruct file might look like this:
+ And would yield the following output: + +
% foobuild file.foo new_target - file.input new_source+ One very flexible thing that you can is specify + use a construction variable to specify + different emitter functions for different + construction variable. + To do this, specify a string + containing a construction variable + expansion as the emitter when you call + the
Builder
function, + and set that construction variable to + the desired emitter function + in different construction environments: + +bld = Builder(action = 'my_command', - suffix = '.foo', - src_suffix = '.input', - emitter = 'MY_EMITTER') - def modify1(target, source, env): - return target, source - def modify2(target, source, env): - return target, source - env1 = Environment(BUILDERS = {'Foo' : bld}, - MY_EMITTER = modify1) - env2 = Environment(BUILDERS = {'Foo' : bld}, - MY_EMITTER = modify2) - env1.Foo('file1') - env2.Foo('file2') +> bld = Builder(action = 'my_command $SOURCES > $TARGET', + suffix = '.foo', + src_suffix = '.input', + emitter = '$MY_EMITTER') + def modify1(target, source, env): + return target, source + ['modify1.in'] + def modify2(target, source, env): + return target, source + ['modify2.in'] + env1 = Environment(BUILDERS = {'Foo' : bld}, + MY_EMITTER = modify1) + env2 = Environment(BUILDERS = {'Foo' : bld}, + MY_EMITTER = modify2) + env1.Foo('file1') + env2.Foo('file2') + import os + env1['ENV']['PATH'] = env2['ENV']['PATH'] + os.pathsep + os.getcwd() + env2['ENV']['PATH'] = env2['ENV']['PATH'] + os.pathsep + os.getcwd() + +bld = Builder(action = 'my_command $SOURCES > $TARGET', + suffix = '.foo', + src_suffix = '.input', + emitter = '$MY_EMITTER') + def modify1(target, source, env): + return target, source + ['modify1.in'] + def modify2(target, source, env): + return target, source + ['modify2.in'] + env1 = Environment(BUILDERS = {'Foo' : bld}, + MY_EMITTER = modify1) + env2 = Environment(BUILDERS = {'Foo' : bld}, + MY_EMITTER = modify2) + env1.Foo('file1') + env2.Foo('file2') + ++ In this example, the modify1.in + and modify2.in files + get added to the source lists + of the different commands: + +
% scons -Q + my_command file1.input modify1.in > file1.foo + my_command file2.input modify2.in > file2.foo +19.7. Where To Put Your Custom Builders and Tools
+ The site_scons directory gives you a place to + put Python modules you can import into your SConscripts + (site_scons), add-on tools that can integrate into SCons + (site_scons/site_tools), and a site_scons/site_init.py file that + gets read before any SConstruct or SConscript, allowing you to + change SCons's default behavior. + +
+ If you get a tool from somewhere (the SCons wiki or a third party, + for instance) and you'd like to use it in your project, the + site_scons dir is the simplest place to put it. + Tools come in two flavors; either a Python function that operates on + an
Environment
or a Python file containing two functions, exists() + and generate(). + ++ A single-function Tool can just be included in your + site_scons/site_init.py file where it will be + parsed and made available for use. For instance, you could have a + site_scons/site_init.py file like this: + +
def TOOL_ADD_HEADER(env): + """A Tool to add a header from $HEADER to the source file""" + add_header = Builder(action=['echo "$HEADER" > $TARGET', + 'cat $SOURCE >> $TARGET']) + env.Append(BUILDERS = {'AddHeader' : add_header}) + env['HEADER'] = '' # set default value ++ and a SConstruct like this: + +
# Use TOOL_ADD_HEADER from site_scons/site_init.py + env=Environment(tools=['default', TOOL_ADD_HEADER], HEADER="=====") + env.AddHeader('tgt', 'src') ++ The
TOOL_ADD_HEADER
tool method will be + called to add theAddHeader
tool to the + environment. + +Similarly, a more full-fledged tool with +
exists()
andgenerate()
+ methods can be installed in + site_scons/site_tools/toolname.py. Since + site_scons/site_tools is automatically added + to the head of the tool search path, any tool found there will be + available to all environments. Furthermore, a tool found there + will override a built-in tool of the same name, so if you need to + change the behavior of a built-in tool, site_scons gives you the + hook you need. +Many people have a library of utility Python functions they'd like + to include in SConscripts; just put that module in + site_scons/my_utils.py or any valid Python module name of your + choice. For instance you can do something like this in + site_scons/my_utils.py to add a build_id method: +
def build_id(): + """Return a build ID (stub version)""" + return "100" ++ And then in your SConscript or any sub-SConscript anywhere in + your build, you can import my_utils and use it: + +
import my_utils + print "build_id=" + my_utils.build_id() ++ If you have a machine-wide site dir you'd like to use instead of + ./site_scons, use the + --site-dir option to point to your dir. + site_init.py and + site_tools will be located under that dir. + To avoid using a site_scons dir at all, even + if it exists, use the --no-site-dir option. + +
Chapter 18. Not Writing a Builder: theChapter 20. Not Writing a Builder: the
Command
BuilderChapter 19. Pseudo-Builders: the AddMethod functionChapter 21. Pseudo-Builders: the AddMethod function- The env.AddMethod(function, [name]) function is used to add a method - to an environment. It's typically used to add a "pseudo-builder" or - wrap up a call to multiple builders. In the first example, we want - to install the program into the standard bin dir, but also copy it - into a local install/bin dir that might be used to build a package - from. + The
AddMethod
function is used to add a method + to an environment. It's typically used to add a "pseudo-builder," + a function that looks like aBuilder
but + wraps up calls to multiple otherBuilder
s + or otherwise processes its arguments + before calling one or moreBuilder
s. + In the following example, + we want to install the program into the standard + /usr/bin directory hierarchy, + but also copy it into a local install/bin + directory from which a package might be built:% scons -Qscons -Q / cc -o hello.o -c hello.c cc -o hello hello.o + Install file: "hello" as "/usr/bin/hello" Install file: "hello" as "install/bin/hello"- It also gives more flexibility in parsing arguments than you can get - with a builder. The next example shows a pseudo-builder with a + As mentioned, a psuedo-builder also provides more flexibility + in parsing arguments than you can get with a
Builder
. + The next example shows a pseudo-builder with a named argument that modifies the filename, and a separate argument for the resource file (rather than having the builder figure it out - by file extension). Also this example demonstrates using the global - AddMethod function to add a method to the global Environment class, + by file extension). This example also demonstrates using the global +AddMethod
function to add a method to the global Environment class, so it will be used in all subsequently created environments.import sys - def BuildTestProg(env, testfile, resourcefile, testdir="tests"): +> def BuildTestProg(env, testfile, resourcefile, testdir="tests"): """Build the test program; - prepends "test_" to src and target, and puts target into testdir.""" - srcfile="test_%s.c"%testfile - if sys.platform=='win32': - target="%s/test_%s$EXESUFFIX"%(testdir,[testfile, resourcefile]) + prepends "test_" to src and target, + and puts target into testdir.""" + srcfile = "test_%s.c" % testfile + target = "%s/test_%s" % (testdir, testfile) + if env['PLATFORM'] == 'win32': + resfile = env.RES(resourcefile) + p = env.Program(target, [srcfile, resfile]) else: - target="%s/test_%s$EXESUFFIX"%(testdir,testfile) - p = env.Program(target, srcfile) + p = env.Program(target, srcfile) return p AddMethod(Environment, BuildTestProg) - # Now use it - env=Environment() + env = Environment() env.BuildTestProg('stuff', resourcefile='res.rc')This produces the following (on Linux, anyway; Windows would include the - resource file): +> This produces the following on Linux:
And the following on Windows: +
C:\>scons -Q + rc /fores.res res.rc + cl /nologo /c test_stuff.c /Fotest_stuff.obj + link /nologo /OUT:tests\test_stuff.exe test_stuff.obj res.res +Using
AddMethod
is better than just adding an instance method + to a construction environment because it gets called as a proper method, + and becauseAddMethod
provides for copying the method + to any clones of the construction environment instance. +Chapter 20. Writing ScannersChapter 22. Writing Scanners
20.1. A Simple Scanner Example22.1. A Simple Scanner Example
@@ -15231,7 +20057,7 @@ CLASS="chapter" >Chapter 21. Building From Code RepositoriesChapter 23. Building From Code Repositories
Often, a software project will have @@ -15252,8 +20078,8 @@ CLASS="section" >
21.1. The
23.1. The
Repository
Method21.2. Finding source files in repositories23.2. Finding source files in repositories
@@ -15451,8 +20277,8 @@ CLASS="section" >
21.3. Finding 23.3. Finding #include files in repositories
21.3.1. Limitations on 23.3.1. Limitations on #include files in repositories
21.4. Finding the 23.4. Finding the SConstruct file in repositories
21.5. Finding derived files in repositories23.5. Finding derived files in repositories
@@ -16038,8 +20864,8 @@ CLASS="section" >
21.6. Guaranteeing local copies of files23.6. Guaranteeing local copies of files
@@ -16156,7 +20982,7 @@ CLASS="chapter" >Chapter 22. Multi-Platform Configuration (Chapter 24. Multi-Platform Configuration (Autoconf Functionality)
22.1. 24.1. Configure Contexts
22.2. Checking for the Existence of Header Files24.2. Checking for the Existence of Header Files
@@ -16356,8 +21182,8 @@ CLASS="section" >
22.3. Checking for the Availability of a Function24.3. Checking for the Availability of a Function
@@ -16383,8 +21209,8 @@ CLASS="section" >
22.4. Checking for the Availability of a Library24.4. Checking for the Availability of a Library
@@ -16440,7 +21266,7 @@ CLASS="function" CLASS="programlisting" > env = Environment() conf = Configure(env) - if not conf.CheckLibWithHeader('m', 'math.h'): + if not conf.CheckLibWithHeader('m', 'math.h', 'c'): print 'Did not find libm.a or m.lib, exiting!' Exit(1) env = conf.Finish() @@ -16464,8 +21290,8 @@ CLASS="section" >
22.5. Checking for the Availability of a 24.5. Checking for the Availability of a typedef
22.6. Adding Your Own Custom Checks24.6. Adding Your Own Custom Checks
@@ -16716,8 +21542,8 @@ CLASS="section" >
22.7. Not Configuring When Cleaning Targets24.7. Not Configuring When Cleaning Targets
@@ -16786,7 +21612,7 @@ CLASS="chapter" >Chapter 23. Caching Built FilesChapter 25. Caching Built Files
On multi-developer software projects, @@ -16803,8 +21629,8 @@ CLASS="section" >
23.1. Specifying the Shared Cache Directory25.1. Specifying the Shared Cache Directory
@@ -16847,11 +21673,11 @@ CLASS="function" it is stored in the shared cache directory along with its MD5 build signature. [3][5]
On subsequent builds, @@ -16889,14 +21715,42 @@ CLASS="userinput" Retrieved `hello.o' from cache Retrieved `hello' from cache+ Note that the
CacheDir
feature still calculates + MD5 build sigantures for the shared cache file names + even if you configure SCons to use timestamps + to decide if files are up to date. + (See the Chapter 6 + chapter for information about theDecider
function.) + Consequently, usingCacheDir
may reduce or eliminate any + potential performance improvements + from using timestamps for up-to-date decisions. + +23.2. Keeping Build Output Consistent25.2. Keeping Build Output Consistent
@@ -16974,8 +21828,8 @@ CLASS="section" >
23.3. Not Using the Shared Cache for Specific Files25.3. Not Using the Shared Cache for Specific Files
@@ -17041,8 +21895,8 @@ CLASS="section" >
23.4. Disabling the Shared Cache25.4. Disabling the Shared Cache
@@ -17114,8 +21968,8 @@ CLASS="section" >
23.5. Populating a Shared Cache With Already-Built Files25.5. Populating a Shared Cache With Already-Built Files
@@ -17211,8 +22065,8 @@ CLASS="section" >
23.6. Minimizing Cache Contention: the 25.6. Minimizing Cache Contention: the --random OptionChapter 24. Alias TargetsChapter 26. Alias Targets
We've already seen how you can use the
Chapter 25. Java BuildsChapter 27. Java Builds
So far, we've been using examples of @@ -17546,8 +22400,8 @@ CLASS="section" >
25.1. Building Java Class Files: the
27.1. Building Java Class Files: the
Java
Builder25.2. How 27.2. How SCons Handles Java Dependencies
25.3. Building Java Archive (27.3. Building Java Archive (.jar) Files: the
25.4. Building C Header and Stub Files: the
27.4. Building C Header and Stub Files: the
JavaH
Builder25.5. Building RMI Stub and Skeleton Class Files: the
27.5. Building RMI Stub and Skeleton Class Files: the
RMIC
BuilderChapter 28. Miscellaneous Functionality
+ SCons supports a lot of additional functionality + that doesn't readily fit into the other chapters. + +
28.1. Verifying the Python Version: the
EnsurePythonVersion
Function+ Although the SCons code itself will run + on any Python version 1.5.2 or later, + you are perfectly free to make use of + Python syntax and modules from more modern versions + (for example, Python 2.4 or 2.5) + when writing your SConscript files + or your own local modules. + If you do this, it's usually helpful to + configure SCons to exit gracefully with an error message + if it's being run with a version of Python + that simply won't work with your code. + This is especially true if you're going to use SCons + to build source code that you plan to distribute publicly, + where you can't be sure of the Python version + that an anonymous remote user might use + to try to build your software. + +
+ SCons provides an
EnsurePythonVersion
function for this. + You simply pass it the major and minor versions + numbers of the version of Python you require: + +EnsurePythonVersion(2, 5) ++ And then SCons will exit with the following error + message when a user runs it with an unsupported + earlier version of Python: + +
% scons -Q + Python 2.5 or greater required, but you have Python 2.3.6 +28.2. Verifying the SCons Version: the
EnsureSConsVersion
Function+ You may, of course, write your SConscript files + to use features that were only added in + recent versions of SCons. + When you publicly distribute software that is built using SCons, + it's helpful to have SCons + verify the version being used and + exit gracefully with an error message + if the user's version of SCons won't work + with your SConscript files. + SCons provides an
EnsureSConsVersion
function + that verifies the version of SCons + in the same + theEnsurePythonVersion
function + verifies the version of Python, + by passing in the major and minor versions + numbers of the version of SCons you require: + +EnsureSConsVersion(1, 0) ++ And then SCons will exit with the following error + message when a user runs it with an unsupported + earlier version of SCons: + +
% scons -Q + SCons 1.0 or greater required, but you have SCons 0.98.5 +28.3. Explicitly Terminating SCons While Reading SConscript Files: the
Exit
Function+ SCons supports an
Exit
function + which can be used to terminate SCons + while reading the SConscript files, + usually because you've detected a condition + under which it doesn't make sense to proceed: + +if ARGUMENTS.get('FUTURE'): + print "The FUTURE option is not supported yet!" + Exit(2) + env = Environment() + env.Program('hello.c') +% scons -Q FUTURE=1 + The FUTURE option is not supported yet! + % scons -Q + cc -o hello.o -c hello.c + cc -o hello hello.o ++ The
Exit
function takes as an argument + the (numeric) exit status that you want SCons to exit with. + If you don't specify a value, + the default is to exit with 0, + which indicates successful execution. + ++ Note that the
Exit
function + is equivalent to calling the Python +sys.exit
function + (which the it actually calls), + but becauseExit
is a SCons function, + you don't have to import the Python + sys module to use it. + +28.4. Searching for Files: the
FindFile
Function+ The
FindFile
function searches for a file in a list of directories. + If there is only one directory, it can be given as a simple string. + The function returns a File node if a matching file exists, + or None if no file is found. + (See the documentation for theGlob
function for an alternative way + of searching for entries in a directory.) + +# one directory + print FindFile('missing', '.') + t = FindFile('exists', '.') + print t.__class__, t +% scons -Q + None + SCons.Node.FS.File exists + scons: `.' is up to date. +# several directories + includes = [ '.', 'include', 'src/include'] + headers = [ 'nonesuch.h', 'config.h', 'private.h', 'dist.h'] + for hdr in headers: + print '%-12s' % ('%s:' % hdr), FindFile(hdr, includes) +% scons -Q + nonesuch.h: None + config.h: config.h + private.h: src/include/private.h + dist.h: include/dist.h + scons: `.' is up to date. ++ If the file exists in more than one directory, + only the first occurrence is returned. + +
print FindFile('multiple', ['sub1', 'sub2', 'sub3']) + print FindFile('multiple', ['sub2', 'sub3', 'sub1']) + print FindFile('multiple', ['sub3', 'sub1', 'sub2']) +% scons -Q + sub1/multiple + sub2/multiple + sub3/multiple + scons: `.' is up to date. ++ In addition to existing files,
FindFile
will also find derived files + (that is, non-leaf files) that haven't been built yet. + (Leaf files should already exist, or the build will fail!) + +# Neither file exists, so build will fail + Command('derived', 'leaf', 'cat >$TARGET $SOURCE') + print FindFile('leaf', '.') + print FindFile('derived', '.') +% scons -Q + None + derived + scons: *** Source `leaf' not found, needed by target `derived'. Stop. +# Neither file exists, so build will fail + Command('derived', 'leaf', 'cat >$TARGET $SOURCE') + print FindFile('leaf', '.') + print FindFile('derived', '.') + + # Only 'leaf' exists + Command('derived', 'leaf', 'cat >$TARGET $SOURCE') + print FindFile('leaf', '.') + print FindFile('derived', '.') +% scons -Q + leaf + derived + cat > derived leaf ++ If a source file exists,
FindFile
will correctly return the name + in the build directory. + +# Only 'src/leaf' exists + VariantDir('build', 'src') + print FindFile('leaf', 'build') +% scons -Q + build/leaf + scons: `.' is up to date. +28.5. Handling Nested Lists: the
Flatten
Function+ SCons supports a
Flatten
function + which takes an input Python sequence + (list or tuple) + and returns a flattened list + containing just the individual elements of + the sequence. + This can be handy when trying to examine + a list composed of the lists + returned by calls to various Builders. + For example, you might collect + object files built in different ways + into one call to theProgram
Builder + by just enclosing them in a list, as follows: + +objects = [ + Object('prog1.c'), + Object('prog2.c', CCFLAGS='-DFOO'), + ] + Program(objects) ++ Because the Builder calls in SCons + flatten their input lists, + this works just fine to build the program: + +
% scons -Q + cc -o prog1.o -c prog1.c + cc -o prog2.o -c -DFOO prog2.c + cc -o prog1 prog1.o prog2.o ++ But if you were debugging your build + and wanted to print the absolute path + of each object file in the +
objects
list, + you might try the following simple approach, + trying to print each Node's + abspath + attribute: + +objects = [ + Object('prog1.c'), + Object('prog2.c', CCFLAGS='-DFOO'), + ] + Program(objects) + + for object_file in objects: + print object_file.abspath ++ This does not work as expected + because each call to
str
+ is operating an embedded list returned by + eachObject
call, + not on the underlying Nodes within those lists: + +% scons -Q + AttributeError: NodeList instance has no attribute 'abspath': + File "/home/my/project/SConstruct", line 8: + print object_file.abspath ++ The solution is to use the
Flatten
function + so that you can pass each Node to + thestr
separately: + +objects = [ + Object('prog1.c'), + Object('prog2.c', CCFLAGS='-DFOO'), + ] + Program(objects) + + for object_file in Flatten(objects): + print object_file.abspath +% scons -Q + /home/me/project/prog1.o + /home/me/project/prog2.o + cc -o prog1.o -c prog1.c + cc -o prog2.o -c -DFOO prog2.c + cc -o prog1 prog1.o prog2.o +28.6. Finding the Invocation Directory: the
GetLaunchDir
Function+ If you need to find the directory from + which the user invoked the scons command, + you can use the
GetLaunchDir
function: + +env = Environment( + LAUNCHDIR = GetLaunchDir(), + ) + env.Command('directory_build_info', + '$LAUNCHDIR/build_info' + Copy('$TARGET', '$SOURCE')) ++ Because SCons is usually invoked from the top-level + directory in which the SConstruct file lives, + the Python
os.getcwd()
+ is often equivalent. + However, the SCons + -u, + -U + and + -D + command-line options, + when invoked from a subdirectory, + will cause SCons to change to the directory + in which the SConstruct file is found. + When those options are used, +GetLaunchDir
will still return the path to the + user's invoking subdirectory, + allowing the SConscript configuration + to still get at configuration (or other) files + from the originating directory. + +Chapter 26. Troubleshooting
Chapter 29. TroubleshootingThe experience of configuring any @@ -18312,8 +23861,8 @@ CLASS="section" >
26.1. Why is That Target Being Rebuilt? the 29.1. Why is That Target Being Rebuilt? the --debug=explain Option
26.2. What's in That Construction Environment? the
29.2. What's in That Construction Environment? the
Dump
Method26.3. What Dependencies Does 29.3. What Dependencies Does SCons Know About? the
26.4. How is 29.4. How is SCons Constructing the Command Lines It Executes? the
26.5. Where is 29.5. Where is SCons Searching for Libraries? the
26.6. Where is 29.6. Where is SCons Blowing Up? the scons: *** Source `prog.c' not found, needed by target `prog.o'. Stop. scons: internal stack trace: - File "bootstrap/src/engine/SCons/Job.py", line 187, in start + File "bootstrap/src/engine/SCons/Job.py", line 198, in start File "bootstrap/src/engine/SCons/Script/Main.py", line 169, in prepare File "bootstrap/src/engine/SCons/Taskmaster.py", line 184, in prepare File "bootstrap/src/engine/SCons/Executor.py", line 171, in prepare @@ -19678,8 +25227,8 @@ CLASS="section" >
26.7. How is 29.7. How is SCons Making Its Decisions? the Taskmaster: Looking for a node to evaluate - Taskmaster: Considering node <no_state 'prog'> and its children: - Taskmaster: <no_state 'prog.o'> - Taskmaster: Considering node <no_state 'prog.o'> and its children: - Taskmaster: <no_state 'prog.c'> - Taskmaster: <no_state 'inc.h'> - Taskmaster: Considering node <no_state 'prog.c'> and its children: - Taskmaster: Evaluating <pending 'prog.c'> + Taskmaster: Considering node <no_state 0 'prog'> and its children: + Taskmaster: <no_state 0 'prog.o'> + Taskmaster: adjusting ref count: <pending 1 'prog'> + Taskmaster: Considering node <no_state 0 'prog.o'> and its children: + Taskmaster: <no_state 0 'prog.c'> + Taskmaster: <no_state 0 'inc.h'> + Taskmaster: adjusting ref count: <pending 1 'prog.o'> + Taskmaster: adjusting ref count: <pending 2 'prog.o'> + Taskmaster: Considering node <no_state 0 'prog.c'> and its children: + Taskmaster: Evaluating <pending 0 'prog.c'> Taskmaster: Looking for a node to evaluate - Taskmaster: Considering node <no_state 'inc.h'> and its children: - Taskmaster: Evaluating <pending 'inc.h'> + Taskmaster: Considering node <no_state 0 'inc.h'> and its children: + Taskmaster: Evaluating <pending 0 'inc.h'> Taskmaster: Looking for a node to evaluate - Taskmaster: Considering node <pending 'prog.o'> and its children: - Taskmaster: <up_to_date 'prog.c'> - Taskmaster: <up_to_date 'inc.h'> - Taskmaster: Evaluating <pending 'prog.o'> + Taskmaster: Considering node <pending 0 'prog.o'> and its children: + Taskmaster: <up_to_date 0 'prog.c'> + Taskmaster: <up_to_date 0 'inc.h'> + Taskmaster: Evaluating <pending 0 'prog.o'> cc -o prog.o -c -I. prog.c Taskmaster: Looking for a node to evaluate - Taskmaster: Considering node <pending 'prog'> and its children: - Taskmaster: <executed 'prog.o'> - Taskmaster: Evaluating <pending 'prog'> + Taskmaster: Considering node <pending 0 'prog'> and its children: + Taskmaster: <executed 0 'prog.o'> + Taskmaster: Evaluating <pending 0 'prog'> cc -o prog prog.o Taskmaster: Looking for a node to evaluate @@ -20434,8 +25986,7 @@ CLASS="envar"
import SCons.Util -env['CCPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Zi /Fd%s" % File(PDB)) or ""}']) +> env['CCPDBFLAGS'] = ['${(PDB and "/Zi /Fd%s" % File(PDB)) or ""}']An alternative would be to use the
class file.
Example: +>Examples:
Java source files can use the native encoding for the underlying OS. +Since SCons compiles in simple ASCII mode by default, +the compiler will generate warnings about unmappable characters, +which may lead to errors as the file is processed further. +In this case, the user must specify the LANG +environment variable to tell the compiler what encoding is uesd. +For portibility, it's best if the encoding is hard-coded +so that the compile will work if it is done on a system +with a different encoding. +
env = Environment() +env['ENV']['LANG'] = 'en_GB.UTF-8' +Builder (see below). It takes several lists of filenames to be placed into the project -file. +>The
MSVSProject
builder +takes several lists of filenames +to be placed into the project file. These are currently limited to value.Note that because SCons always executes its build commands +from the directory in which the SConstruct file is located, +if you generate a project file in a different directory +than the SConstruct directory, +users will not be able to double-click +on the file name in compilation error messages +displayed in the Visual Studio console output window. +This can be remedied by adding the +Visual C/C++ +.B /FC +compiler option to the
$CCFLAGS
variable +so that the compiler will print +the full path name of any +files that cause compilation errors.Example usage:
Builds software distribution packages. Packages consist of files -to install and packaging information. The former may be specified -with the
is not specified +it will be deduced from additional information given to this Builder.Builds software distribution packages. +Packages consist of files to install and packaging information. +The former may be specified with the
source
parameter and may be left out, in which case the -parameter and may be left out, +in which case the
FindInstalledFiles
function will collect all files that have an -function will collect +all files that have an
Install
orInstallAs
Builder attached. If theBuilder attached. +If the
target
, is -not specified it will be deduced from additional information given to -this Builder.The packaging information is specified with the help of construction -variables documented below. This information is called a tag to stress -that some of them can also be attached to files with the
The packaging information is specified +with the help of construction variables documented below. +This information is called a tag to stress that +some of them can also be attached to files with the
Tag
function. -The mandatory ones will complain if they were not specified. They vary -depending on chosen target packager.The target packager may be selected with the "PACKAGETYPE" command line option or with the
[2][3]
The
AddOption
function is, + in fact, implemented using a subclass + of theoptparse.OptionParser
. +[4] Unfortunately, in the early days of SCons design, + we used the name
Copy
for the function that + returns a copy of the environment, + otherwise that would be the logical choice for + a Builder that copies a file or directory tree + to a target location. +[5] Actually, the MD5 signature is used as the name of the file in the shared cache directory in which the contents are stored.