Fix XML in documentation, and in the bin/scons-doc.py script that generates
[scons.git] / doc / user / environments.in
1 <!--
2
3      __COPYRIGHT__
4
5      Permission is hereby granted, free of charge, to any person obtaining
6      a copy of this software and associated documentation files (the
7      "Software"), to deal in the Software without restriction, including
8      without limitation the rights to use, copy, modify, merge, publish,
9      distribute, sublicense, and/or sell copies of the Software, and to
10      permit persons to whom the Software is furnished to do so, subject to
11      the following conditions:
12
13      The above copyright notice and this permission notice shall be included
14      in all copies or substantial portions of the Software.
15
16      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
17      KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
18      WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19      NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20      LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21      OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22      WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
24 -->
25
26 <!--
27
28 =head1 More on construction environments
29
30 As previously mentioned, a B<construction environment> is an object that
31 has a set of keyword/value pairs and a set of methods, and which is used
32 to tell Cons how target files should be built.  This section describes
33 how Cons uses and expands construction environment values to control its
34 build behavior.
35
36 =head2 Construction variable expansion
37
38 Construction variables from a construction environment are expanded
39 by preceding the keyword with a C<%> (percent sign):
40
41      Construction variables:
42         XYZZY => 'abracadabra',
43
44      The string:  "The magic word is:  %XYZZY!"
45      expands to:  "The magic word is:  abracadabra!"
46
47 A construction variable name may be surrounded by C<{> and C<}> (curly
48 braces), which are stripped as part of the expansion.  This can
49 sometimes be necessary to separate a variable expansion from trailing
50 alphanumeric characters:
51
52      Construction variables:
53         OPT    => 'value1',
54         OPTION => 'value2',
55
56      The string:  "%OPT %{OPT}ION %OPTION %{OPTION}"
57      expands to:  "value1 value1ION value2 value2"
58
59 Construction variable expansion is recursive, that is, a string
60 containing C<%->expansions after substitution will be re-expanded until
61 no further substitutions can be made:
62
63      Construction variables:
64         STRING => 'The result is:  %FOO',
65         FOO    => '%BAR',
66         BAR    => 'final value',
67
68      The string:  "The string says:  %STRING"
69      expands to:  "The string says:  The result is:  final value"
70
71 If a construction variable is not defined in an environment, then the
72 null string is substituted:
73
74      Construction variables:
75         FOO => 'value1',
76         BAR => 'value2',
77
78      The string:  "%FOO <%NO_VARIABLE> %BAR"
79      expands to:  "value1 <> value2"
80
81 A doubled C<%%> will be replaced by a single C<%>:
82
83      The string:  "Here is a percent sign:  %%"
84      expands to:  "Here is a percent sign: %"
85
86 =head2 Default construction variables
87
88 When you specify no arguments when creating a new construction
89 environment:
90
91      $env = new cons();
92
93 Cons creates a reference to a new, default construction
94 environment. This contains a number of construction variables and some
95 methods. At the present writing, the default construction variables on a
96 UNIX system are:
97
98      CC            => 'cc',
99      CFLAGS        => '',
100      CCCOM         => '%CC %CFLAGS %_IFLAGS -c %< -o %>',
101      CXX           => '%CC',
102      CXXFLAGS      => '%CFLAGS',
103      CXXCOM        => '%CXX %CXXFLAGS %_IFLAGS -c %< -o %>',
104      INCDIRPREFIX  => '-I',
105      INCDIRSUFFIX  => '',
106      LINK          => '%CXX',
107      LINKCOM       => '%LINK %LDFLAGS -o %> %< %_LDIRS %LIBS',
108      LINKMODULECOM => '%LD -r -o %> %<',
109      LIBDIRPREFIX  => '-L',
110      LIBDIRSUFFIX  => '',
111      AR         => 'ar',
112      ARFLAGS    => 'r',
113      ARCOM              => ['%AR %ARFLAGS %> %<', '%RANLIB %>'],
114      RANLIB     => 'ranlib',
115      AS         => 'as',
116      ASFLAGS    => '',
117      ASCOM              => '%AS %ASFLAGS %< -o %>',
118      LD         => 'ld',
119      LDFLAGS    => '',
120      PREFLIB    => 'lib',
121      SUFLIB     => '.a',
122      SUFLIBS    => '.so:.a',
123      SUFOBJ     => '.o',
124      SIGNATURE     => [ '*' => 'build' ],
125      ENV                => { 'PATH' => '/bin:/usr/bin' },
126
127
128 And on a Windows system (Windows NT), the default construction variables
129 are (unless the default rule style is set using the B<DefaultRules>
130 method):
131
132      CC         => 'cl',
133      CFLAGS     => '/nologo',
134      CCCOM              => '%CC %CFLAGS %_IFLAGS /c %< /Fo%>',
135      CXXCOM        => '%CXX %CXXFLAGS %_IFLAGS /c %< /Fo%>',
136      INCDIRPREFIX  => '/I',
137      INCDIRSUFFIX  => '',
138      LINK          => 'link',
139      LINKCOM       => '%LINK %LDFLAGS /out:%> %< %_LDIRS %LIBS',
140      LINKMODULECOM => '%LD /r /o %> %<',
141      LIBDIRPREFIX  => '/LIBPATH:',
142      LIBDIRSUFFIX  => '',
143      AR            => 'lib',
144      ARFLAGS       => '/nologo ',
145      ARCOM         => "%AR %ARFLAGS /out:%> %<",
146      RANLIB        => '',
147      LD            => 'link',
148      LDFLAGS       => '/nologo ',
149      PREFLIB       => '',
150      SUFEXE     => '.exe',
151      SUFLIB     => '.lib',
152      SUFLIBS    => '.dll:.lib',
153      SUFOBJ     => '.obj',
154      SIGNATURE     => [ '*' => 'build' ],
155
156 These variables are used by the various methods associated with the
157 environment. In particular, any method that ultimately invokes an external
158 command will substitute these variables into the final command, as
159 appropriate. For example, the C<Objects> method takes a number of source
160 files and arranges to derive, if necessary, the corresponding object
161 files:
162
163      Objects $env 'foo.c', 'bar.c';
164
165 This will arrange to produce, if necessary, F<foo.o> and F<bar.o>. The
166 command invoked is simply C<%CCCOM>, which expands, through substitution,
167 to the appropriate external command required to build each object. The
168 substitution rules will be discussed in detail in the next section.
169
170 The construction variables are also used for other purposes. For example,
171 C<CPPPATH> is used to specify a colon-separated path of include
172 directories. These are intended to be passed to the C preprocessor and are
173 also used by the C-file scanning machinery to determine the dependencies
174 involved in a C Compilation.
175
176 Variables beginning with underscore are created by various methods,
177 and should normally be considered ``internal'' variables. For example,
178 when a method is called which calls for the creation of an object from
179 a C source, the variable C<_IFLAGS> is created: this corresponds to the
180 C<-I> switches required by the C compiler to represent the directories
181 specified by C<CPPPATH>.
182
183 Note that, for any particular environment, the value of a variable is set
184 once, and then never reset (to change a variable, you must create a new
185 environment. Methods are provided for copying existing environments for this
186 purpose). Some internal variables, such as C<_IFLAGS> are created on demand,
187 but once set, they remain fixed for the life of the environment.
188
189 The C<CFLAGS>, C<LDFLAGS>, and C<ARFLAGS> variables all supply a place
190 for passing options to the compiler, loader, and archiver, respectively.
191
192 The C<INCDIRPREFIX> and C<INCDIRSUFFIX> variables specify option
193 strings to be appended to the beginning and end, respectively, of each
194 include directory so that the compiler knows where to find F<.h> files.
195 Similarly, the C<LIBDIRPREFIX> and C<LIBDIRSUFFIX> variables specify the
196 option string to be appended to the beginning of and end, respectively,
197 of each directory that the linker should search for libraries.
198
199 Another variable, C<ENV>, is used to determine the system environment during
200 the execution of an external command. By default, the only environment
201 variable that is set is C<PATH>, which is the execution path for a UNIX
202 command. For the utmost reproducibility, you should really arrange to set
203 your own execution path, in your top-level F<Construct> file (or perhaps by
204 importing an appropriate construction package with the Perl C<use>
205 command). The default variables are intended to get you off the ground.
206
207 =head2 Expanding variables in construction commands
208
209 Within a construction command, construction variables will be expanded
210 according to the rules described above.  In addition to normal variable
211 expansion from the construction environment, construction commands also
212 expand the following pseudo-variables to insert the specific input and
213 output files in the command line that will be executed:
214
215 =over 10
216
217 =item %>
218
219 The target file name.  In a multi-target command, this expands to the
220 first target mentioned.)
221
222 =item %0
223
224 Same as C<%E<gt>>.
225
226 =item %1, %2, ..., %9
227
228 These refer to the first through ninth input file, respectively.
229
230 =item %E<lt>
231
232 The full set of input file names. If any of these have been used
233 anywhere else in the current command line (via C<%1>, C<%2>, etc.), then
234 those will be deleted from the list provided by C<%E<lt>>. Consider the
235 following command found in a F<Conscript> file in the F<test> directory:
236
237      Command $env 'tgt', qw(foo bar baz), qq(
238         echo %< -i %1 > %>
239         echo %< -i %2 >> %>
240         echo %< -i %3 >> %>
241      );
242
243 If F<tgt> needed to be updated, then this would result in the execution of
244 the following commands, assuming that no remapping has been established for
245 the F<test> directory:
246
247      echo test/bar test/baz -i test/foo > test/tgt
248      echo test/foo test/baz -i test/bar >> test/tgt
249      echo test/foo test/bar -i test/baz >> test/tgt
250
251 =back
252
253 Any of the above pseudo-variables may be followed immediately by one of
254 the following suffixes to select a portion of the expanded path name:
255
256      :a    the absolute path to the file name
257      :b    the directory plus the file name stripped of any suffix
258      :d    the directory
259      :f    the file name
260      :s    the file name suffix
261      :F    the file name stripped of any suffix
262      :S    the absolute path path to a Linked source file
263
264 Continuing with the above example, C<%E<lt>:f> would expand to C<foo bar baz>,
265 and C<%E<gt>:d> would expand to C<test>.
266
267 There are additional C<%> elements which affect the command line(s):
268
269 =over 10
270
271 =item %[ %]
272
273 It is possible to programmatically rewrite part of the command by
274 enclosing part of it between C<%[> and C<%]>.  This will call the
275 construction variable named as the first word enclosed in the brackets
276 as a Perl code reference; the results of this call will be used to
277 replace the contents of the brackets in the command line.  For example,
278 given an existing input file named F<tgt.in>:
279
280      @keywords = qw(foo bar baz);
281      $env = new cons(X_COMMA => sub { join(",", @_) });
282      Command $env 'tgt', 'tgt.in', qq(
283         echo '# Keywords: %[X_COMMA @keywords %]' > %>
284         cat %< >> %>
285      );
286
287 This will execute:
288
289      echo '# Keywords: foo,bar,baz' > tgt
290      cat tgt.in >> tgt
291
292 =item %( %)
293
294 Cons includes the text of the command line in the MD5 signature for a
295 build, so that targets get rebuilt if you change the command line (to
296 add or remove an option, for example).  Command-line text in between
297 C<%(> and C<%)>, however, will be ignored for MD5 signature calculation.
298
299 Internally, Cons uses C<%(> and C<%)> around include and library
300 directory options (C<-I> and C<-L> on UNIX systems, C</I> and
301 C</LIBPATH> on Windows NT) to avoid rebuilds just because the directory
302 list changes.  Rebuilds occur only if the changed directory list causes
303 any included I<files> to change, and a changed include file is detected
304 by the MD5 signature calculation on the actual file contents.
305
306 =back
307
308 XXX DESCRIBE THE Literal() FUNCTION, TOO XXX
309
310 =head2 Expanding construction variables in file names
311
312 Cons expands construction variables in the source and target file names
313 passed to the various construction methods according to the expansion
314 rules described above:
315
316      $env = new cons(
317         DESTDIR =>      'programs',
318         SRCDIR  =>      'src',
319      );
320      Program $env '%DESTDIR/hello', '%SRCDIR/hello.c';
321
322 This allows for flexible configuration, through the construction
323 environment, of directory names, suffixes, etc.
324
325 -->
326
327   <para>
328
329   An <literal>environment</literal>
330   is a collection of values that
331   can affect how a program executes.
332   &SCons; distinguishes between three
333   different types of environments
334   that can affect the behavior of &SCons; itself
335   (subject to the configuration in the &SConscript; files),
336   as well as the compilers and other tools it executes:
337
338   </para>
339
340   <variablelist>
341
342     <varlistentry>
343     <term>External Environment</term>
344
345     <listitem>
346     <para>
347
348     The <literal>external environment</literal>
349     is the set of variables in the user's environment
350     at the time the user runs &SCons.
351     These variables are available within the &SConscript; files
352     through the Python <literal>os.environ</literal> dictionary.
353     See <xref linkend="sect-external-environments"></xref>, below.
354
355     </para>
356     </listitem>
357     </varlistentry>
358
359     <varlistentry>
360     <term>&ConsEnv;</term>
361
362     <listitem>
363     <para>
364
365     A &consenv;
366     is a distinct object creating within
367     a &SConscript; file and
368     and which contains values that
369     affect how &SCons; decides
370     what action to use to build a target,
371     and even to define which targets
372     should be built from which sources.
373     One of the most powerful features of &SCons;
374     is the ability to create multiple &consenvs;,
375     including the ability to clone a new, customized
376     &consenv; from an existing &consenv;.
377     See <xref linkend="sect-construction-environments"></xref>, below.
378
379     </para>
380     </listitem>
381     </varlistentry>
382
383     <varlistentry>
384     <term>Execution Environment</term>
385
386     <listitem>
387     <para>
388
389     An <literal>execution environment</literal>
390     is the values that &SCons; sets
391     when executing an external
392     command (such as a compiler or linker)
393     to build one or more targets.
394     Note that this is not the same as
395     the <literal>external environment</literal>
396     (see above).
397     See <xref linkend="sect-execution-environments"></xref>, below.
398
399     </para>
400     </listitem>
401     </varlistentry>
402
403   </variablelist>
404
405   <para>
406
407   Unlike &Make;,  &SCons; does not automatically
408   copy or import values between different environments
409   (with the exception of explicit clones of &consenvs,
410   which inherit values from their parent).
411   This is a deliberate design choice
412   to make sure that builds are,
413   by default, repeatable regardless of
414   the values in the user's external environment.
415   This avoids a whole class of problems with builds
416   where a developer's local build works
417   because a custom variable setting
418   causes a different compiler or build option to be used,
419   but the checked-in change breaks the official build
420   because it uses different environment variable settings.
421
422   </para>
423
424   <para>
425
426   Note that the &SConscript; writer can
427   easily arrange for variables to be
428   copied or imported between environments,
429   and this is often very useful
430   (or even downright necessary)
431   to make it easy for developers
432   to customize the build in appropriate ways.
433   The point is <emphasis>not</emphasis>
434   that copying variables between different environments
435   is evil and must always be avoided.
436   Instead, it should be up to the
437   implementer of the build system
438   to make conscious choices
439   about how and when to import
440   a variable from one environment to another,
441   making informed decisions about
442   striking the right balance
443   between making the build
444   repeatable on the one hand
445   and convenient to use on the other.
446
447   </para>
448
449   <section id="sect-external-environments">
450   <title>Using Values From the External Environment</title>
451
452   <para>
453
454   The <literal>external environment</literal>
455   variable settings that
456   the user has in force
457   when executing &SCons;
458   are available through the normal Python
459   <envar>os.environ</envar>
460   dictionary.
461   This means that you must add an
462   <literal>import os</literal> statement
463   to any &SConscript; file
464   in which you want to use
465   values from the user's external environment.
466
467   </para>
468
469    <scons_example name="ex1">
470      <file name="SConstruct" printme="1">
471      import os
472      </file>
473      <file name="foo.c">
474     int main() { }
475      </file>
476    </scons_example>
477
478   <para>
479
480   More usefully, you can use the
481   <envar>os.environ</envar>
482   dictionary in your &SConscript;
483   files to initialize &consenvs;
484   with values from the user's external environment.
485   See the next section,
486   <xref linkend="sect-construction-environments"></xref>,
487   for information on how to do this.
488
489   </para>
490
491   </section>
492
493   <section id="sect-construction-environments">
494   <title>Construction Environments</title>
495
496     <para>
497
498       It is rare that all of the software in a large,
499       complicated system needs to be built the same way.
500       For example, different source files may need different options
501       enabled on the command line,
502       or different executable programs need to be linked
503       with different libraries.
504       &SCons; accommodates these different build
505       requirements by allowing you to create and
506       configure multiple &consenvs;
507       that control how the software is built.
508       A &consenv; is an object
509       that has a number of associated
510       &consvars;, each with a name and a value.
511       (A construction environment also has an attached
512       set of &Builder; methods,
513       about which we'll learn more later.)
514
515     </para>
516
517     <section>
518     <title>Creating a &ConsEnv;:  the &Environment; Function</title>
519
520       <para>
521
522         A &consenv; is created by the &Environment; method:
523
524       </para>
525
526        <sconstruct>
527          env = Environment()
528        </sconstruct>
529
530       <para>
531
532         By default, &SCons; initializes every
533         new construction environment
534         with a set of &consvars;
535         based on the tools that it finds on your system,
536         plus the default set of builder methods
537         necessary for using those tools.
538         The construction variables
539         are initialized with values describing
540         the C compiler,
541         the Fortran compiler,
542         the linker,
543         etc.,
544         as well as the command lines to invoke them.
545
546       </para>
547
548       <para>
549
550         When you initialize a construction environment
551         you can set the values of the
552         environment's &consvars;
553         to control how a program is built.
554         For example:
555
556       </para>
557
558        <scons_example name="ex1">
559          <file name="SConstruct" printme="1">
560          env = Environment(CC = 'gcc',
561                            CCFLAGS = '-O2')
562
563          env.Program('foo.c')
564          </file>
565          <file name="foo.c">
566         int main() { }
567          </file>
568        </scons_example>
569
570       <para>
571
572         The construction environment in this example
573         is still initialized with the same default
574         construction variable values,
575         except that the user has explicitly specified use of the
576         GNU C compiler &gcc;,
577         and further specifies that the <literal>-O2</literal>
578         (optimization level two)
579         flag should be used when compiling the object file.
580         In other words, the explicit initializations of
581         &cv-link-CC; and &cv-link-CCFLAGS;
582         override the default values in the newly-created
583         construction environment.
584         So a run from this example would look like:
585
586       </para>
587
588       <scons_output example="ex1">
589          <scons_output_command>scons -Q</scons_output_command>
590       </scons_output>
591
592     </section>
593
594     <section>
595     <title>Fetching Values From a &ConsEnv;</title>
596
597       <para>
598
599       You can fetch individual construction variables
600       using the normal syntax
601       for accessing individual named items in a Python dictionary:
602
603       </para>
604
605       <scons_example name="ex6">
606         <file name="SConstruct" printme="1">
607          env = Environment()
608          print "CC is:", env['CC']
609         </file>
610       </scons_example>
611
612       <para>
613
614       This example &SConstruct; file doesn't build anything,
615       but because it's actually a Python script,
616       it will print the value of &cv-link-CC; for us:
617
618       </para>
619
620       <scons_output example="ex6">
621          <scons_output_command>scons -Q</scons_output_command>
622       </scons_output>
623
624       <para>
625
626       A construction environment, however,
627       is actually an object with associated methods, etc.
628       If you want to have direct access to only the
629       dictionary of construction variables,
630       you can fetch this using the &Dictionary; method:
631
632       </para>
633
634       <scons_example name="ex6b">
635          <file name="SConstruct" printme="1">
636          env = Environment(FOO = 'foo', BAR = 'bar')
637          dict = env.Dictionary()
638          for key in ['OBJSUFFIX', 'LIBSUFFIX', 'PROGSUFFIX']:
639              print "key = %s, value = %s" % (key, dict[key])
640          </file>
641       </scons_Example>
642
643       <para>
644
645       This &SConstruct; file
646       will print the specified dictionary items for us on POSIX
647       systems as follows:
648
649       </para>
650
651       <scons_output example="ex6b" os="posix">
652          <scons_output_command>scons -Q</scons_output_command>
653       </scons_output>
654
655       <para>
656
657       And on Windows:
658
659       </para>
660
661       <scons_output example="ex6b" os="win32">
662          <scons_output_command>scons -Q</scons_output_command>
663       </scons_output>
664
665       <para>
666
667       If you want to loop and print the values of
668       all of the construction variables in a construction environment,
669       the Python code to do that in sorted order might look something like:
670
671       </para>
672
673       <sconstruct>
674          env = Environment()
675          for item in sorted(env.Dictionary().items()):
676              print "construction variable = '%s', value = '%s'" % item
677       </sconstruct>
678
679     </section>
680
681     <section>
682     <title>Expanding Values From a &ConsEnv;:  the &subst; Method</title>
683
684       <para>
685
686       Another way to get information from
687       a construction environment.
688       is to use the &subst; method
689       on a string containing <literal>$</literal> expansions
690       of construction variable names.
691       As a simple example,
692       the example from the previous
693       section that used
694       <literal>env['CC']</literal>
695       to fetch the value of &cv-link-CC;
696       could also be written as:
697
698       </para>
699
700       <sconstruct>
701         env = Environment()
702         print "CC is:", env.subst('$CC')
703       </sconstruct>
704
705       <para>
706
707       One advantage of using
708       &subst; to expand strings is
709       that construction variables
710       in the result get re-expanded until
711       there are no expansions left in the string.
712       So a simple fetch of a value like
713       &cv-link-CCCOM;:
714
715       </para>
716
717       <sconstruct>
718         env = Environment(CCFLAGS = '-DFOO')
719         print "CCCOM is:", env['CCCOM']
720       </sconstruct>
721
722       <para>
723
724       Will print the unexpanded value of &cv-CCCOM;,
725       showing us the construction
726       variables that still need to be expanded:
727
728       </para>
729
730       <screen>
731         % <userinput>scons -Q</userinput>
732         CCCOM is: $CC $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES
733         scons: `.' is up to date.
734       </screen>
735
736       <para>
737
738       Calling the &subst; method on <varname>$CCOM</varname>,
739       however:
740
741       </para>
742
743       <sconstruct>
744         env = Environment(CCFLAGS = '-DFOO')
745         print "CCCOM is:", env.subst('$CCCOM')
746       </sconstruct>
747
748       <para>
749
750       Will recursively expand all of
751       the construction variables prefixed
752       with <literal>$</literal> (dollar signs),
753       showing us the final output:
754
755       </para>
756
757       <screen>
758         % <userinput>scons -Q</userinput>
759         CCCOM is: gcc -DFOO -c -o
760         scons: `.' is up to date.
761       </screen>
762
763       <para>
764
765       Note that because we're not expanding this
766       in the context of building something
767       there are no target or source files
768       for &cv-link-TARGET; and &cv-link-SOURCES; to expand.
769
770       </para>
771
772     </section>
773
774     <section>
775     <title>Controlling the Default &ConsEnv;:  the &DefaultEnvironment; Function</title>
776
777       <para>
778
779       All of the &Builder; functions that we've introduced so far,
780       like &Program; and &Library;,
781       actually use a default &consenv;
782       that contains settings
783       for the various compilers
784       and other tools that
785       &SCons; configures by default,
786       or otherwise knows about
787       and has discovered on your system.
788       The goal of the default construction environment
789       is to make many configurations to "just work"
790       to build software using
791       readily available tools
792       with a minimum of configuration changes.
793
794       </para>
795
796       <para>
797
798       You can, however, control the settings
799       in the default contstruction environment
800       by using the &DefaultEnvironment; function
801       to initialize various settings:
802
803       </para>
804
805       <sconstruct>
806
807       DefaultEnvironment(CC = '/usr/local/bin/gcc')
808
809       </sconstruct>
810
811       <para>
812
813       When configured as above,
814       all calls to the &Program;
815       or &Object; Builder
816       will build object files with the
817       <filename>/usr/local/bin/gcc</filename>
818       compiler.
819
820       </para>
821
822       <para>
823
824       Note that the &DefaultEnvironment; function
825       returns the initialized
826       default construction environment object,
827       which can then be manipulated like any
828       other construction environment.
829       So the following
830       would be equivalent to the
831       previous example,
832       setting the &cv-CC;
833       variable to <filename>/usr/local/bin/gcc</filename>
834       but as a separate step after
835       the default construction environment has been initialized:
836
837       </para>
838
839       <sconstruct>
840
841       env = DefaultEnvironment()
842       env['CC'] = '/usr/local/bin/gcc'
843
844       </sconstruct>
845
846       <para>
847
848       One very common use of the &DefaultEnvironment; function
849       is to speed up &SCons; initialization.
850       As part of trying to make most default
851       configurations "just work,"
852       &SCons; will actually
853       search the local system for installed
854       compilers and other utilities.
855       This search can take time,
856       especially on systems with
857       slow or networked file systems.
858       If you know which compiler(s) and/or
859       other utilities you want to configure,
860       you can control the search
861       that &SCons; performs
862       by specifying some specific
863       tool modules with which to
864       initialize the default construction environment:
865
866       </para>
867
868       <sconstruct>
869
870       env = DefaultEnvironment(tools = ['gcc', 'gnulink'],
871                                CC = '/usr/local/bin/gcc')
872
873       </sconstruct>
874
875       <para>
876
877       So the above example would tell &SCons;
878       to explicitly configure the default environment
879       to use its normal GNU Compiler and GNU Linker settings
880       (without having to search for them,
881       or any other utilities for that matter),
882       and specifically to use the compiler found at
883       <filename>/usr/local/bin/gcc</filename>.
884
885       </para>
886
887     </section>
888
889     <section>
890     <title>Multiple &ConsEnvs;</title>
891
892       <para>
893
894       The real advantage of construction environments
895       is that you can create as many different construction
896       environments as you need,
897       each tailored to a different way to build
898       some piece of software or other file.
899       If, for example, we need to build
900       one program with the <literal>-O2</literal> flag
901       and another with the <literal>-g</literal> (debug) flag,
902       we would do this like so:
903
904       </para>
905
906       <scons_example name="ex2">
907         <file name="SConstruct" printme="1">
908          opt = Environment(CCFLAGS = '-O2')
909          dbg = Environment(CCFLAGS = '-g')
910
911          opt.Program('foo', 'foo.c')
912
913          dbg.Program('bar', 'bar.c')
914         </file>
915         <file name="foo.c">
916         int main() { }
917         </file>
918         <file name="bar.c">
919         int main() { }
920         </file>
921       </scons_example>
922
923       <scons_output example="ex2">
924          <scons_output_command>scons -Q</scons_output_command>
925       </scons_output>
926
927       <para>
928
929       We can even use multiple construction environments to build
930       multiple versions of a single program.
931       If you do this by simply trying to use the
932       &b-link-Program; builder with both environments, though,
933       like this:
934
935       </para>
936
937       <scons_example name="ex3">
938         <file name="SConstruct" printme="1">
939          opt = Environment(CCFLAGS = '-O2')
940          dbg = Environment(CCFLAGS = '-g')
941
942          opt.Program('foo', 'foo.c')
943
944          dbg.Program('foo', 'foo.c')
945         </file>
946         <file name="foo.c">
947         int main() { }
948         </file>
949       </scons_example>
950
951       <para>
952
953       Then &SCons; generates the following error:
954
955       </para>
956
957       <scons_output example="ex3">
958          <scons_output_command>scons -Q</scons_output_command>
959       </scons_output>
960
961       <para>
962
963       This is because the two &b-Program; calls have
964       each implicitly told &SCons; to generate an object file named
965       <filename>foo.o</filename>,
966       one with a &cv-link-CCFLAGS; value of
967       <literal>-O2</literal>
968       and one with a &cv-link-CCFLAGS; value of
969       <literal>-g</literal>.
970       &SCons; can't just decide that one of them
971       should take precedence over the other,
972       so it generates the error.
973       To avoid this problem,
974       we must explicitly specify
975       that each environment compile
976       <filename>foo.c</filename>
977       to a separately-named object file
978       using the &b-link-Object; builder, like so:
979
980       </para>
981
982       <scons_example name="ex4">
983         <file name="SConstruct" printme="1">
984          opt = Environment(CCFLAGS = '-O2')
985          dbg = Environment(CCFLAGS = '-g')
986
987          o = opt.Object('foo-opt', 'foo.c')
988          opt.Program(o)
989
990          d = dbg.Object('foo-dbg', 'foo.c')
991          dbg.Program(d)
992         </file>
993         <file name="foo.c">
994         int main() { }
995         </file>
996       </scons_example>
997
998       <para>
999
1000       Notice that each call to the &b-Object; builder
1001       returns a value,
1002       an internal &SCons; object that
1003       represents the object file that will be built.
1004       We then use that object
1005       as input to the &b-Program; builder.
1006       This avoids having to specify explicitly
1007       the object file name in multiple places,
1008       and makes for a compact, readable
1009       &SConstruct; file.
1010       Our &SCons; output then looks like:
1011
1012       </para>
1013
1014       <scons_output example="ex4">
1015          <scons_output_command>scons -Q</scons_output_command>
1016       </scons_output>
1017
1018     </section>
1019
1020     <section>
1021     <title>Making Copies of &ConsEnvs;:  the &Clone; Method</title>
1022
1023       <para>
1024
1025       Sometimes you want more than one construction environment
1026       to share the same values for one or more variables.
1027       Rather than always having to repeat all of the common
1028       variables when you create each construction environment,
1029       you can use the &Clone; method
1030       to create a copy of a construction environment.
1031
1032       </para>
1033
1034       <para>
1035
1036       Like the &Environment; call that creates a construction environment,
1037       the &Clone; method takes &consvar; assignments,
1038       which will override the values in the copied construction environment.
1039       For example, suppose we want to use &gcc;
1040       to create three versions of a program,
1041       one optimized, one debug, and one with neither.
1042       We could do this by creating a "base" construction environment
1043       that sets &cv-link-CC; to &gcc;,
1044       and then creating two copies,
1045       one which sets &cv-link-CCFLAGS; for optimization
1046       and the other which sets &cv-CCFLAGS; for debugging:
1047
1048       </para>
1049
1050       <scons_example name="ex5">
1051         <file name="SConstruct" printme="1">
1052          env = Environment(CC = 'gcc')
1053          opt = env.Clone(CCFLAGS = '-O2')
1054          dbg = env.Clone(CCFLAGS = '-g')
1055
1056          env.Program('foo', 'foo.c')
1057
1058          o = opt.Object('foo-opt', 'foo.c')
1059          opt.Program(o)
1060
1061          d = dbg.Object('foo-dbg', 'foo.c')
1062          dbg.Program(d)
1063         </file>
1064         <file name="foo.c">
1065         int main() { }
1066         </file>
1067       </scons_example>
1068
1069       <para>
1070
1071       Then our output would look like:
1072
1073       </para>
1074
1075       <scons_output example="ex5">
1076          <scons_output_command>scons -Q</scons_output_command>
1077       </scons_output>
1078
1079     </section>
1080
1081     <section>
1082     <title>Replacing Values:  the &Replace; Method</title>
1083
1084       <para>
1085
1086       You can replace existing construction variable values
1087       using the &Replace; method:
1088
1089       </para>
1090
1091       <scons_example name="Replace1">
1092         <file name="SConstruct" printme="1">
1093          env = Environment(CCFLAGS = '-DDEFINE1')
1094          env.Replace(CCFLAGS = '-DDEFINE2')
1095          env.Program('foo.c')
1096         </file>
1097         <file name="foo.c">
1098         int main() { }
1099         </file>
1100       </scons_example>
1101
1102       <para>
1103
1104       The replacing value
1105       (<literal>-DDEFINE2</literal> in the above example)
1106       completely replaces the value in the
1107       construction environment:
1108
1109       </para>
1110
1111       <scons_output example="Replace1">
1112          <scons_output_command>scons -Q</scons_output_command>
1113       </scons_output>
1114
1115       <para>
1116
1117       You can safely call &Replace;
1118       for construction variables that
1119       don't exist in the construction environment:
1120
1121       </para>
1122
1123       <scons_example name="Replace-nonexistent">
1124         <file name="SConstruct" printme="1">
1125          env = Environment()
1126          env.Replace(NEW_VARIABLE = 'xyzzy')
1127          print "NEW_VARIABLE =", env['NEW_VARIABLE']
1128         </file>
1129       </scons_example>
1130
1131       <para>
1132
1133       In this case,
1134       the construction variable simply
1135       gets added to the construction environment:
1136
1137       </para>
1138
1139       <scons_output example="Replace-nonexistent">
1140          <scons_output_command>scons -Q</scons_output_command>
1141       </scons_output>
1142
1143       <para>
1144
1145       Because the variables
1146       aren't expanded until the construction environment
1147       is actually used to build the targets,
1148       and because &SCons; function and method calls
1149       are order-independent,
1150       the last replacement "wins"
1151       and is used to build all targets,
1152       regardless of the order in which
1153       the calls to Replace() are
1154       interspersed with calls to
1155       builder methods:
1156
1157       </para>
1158
1159       <scons_example name="Replace2">
1160         <file name="SConstruct" printme="1">
1161          env = Environment(CCFLAGS = '-DDEFINE1')
1162          print "CCFLAGS =", env['CCFLAGS']
1163          env.Program('foo.c')
1164
1165          env.Replace(CCFLAGS = '-DDEFINE2')
1166          print "CCFLAGS =", env['CCFLAGS']
1167          env.Program('bar.c')
1168         </file>
1169         <file name="foo.c">
1170         int main() { }
1171         </file>
1172         <file name="bar.c">
1173         int main() { }
1174         </file>
1175       </scons_example>
1176
1177       <para>
1178
1179       The timing of when the replacement
1180       actually occurs relative
1181       to when the targets get built
1182       becomes apparent
1183       if we run &scons; without the <literal>-Q</literal>
1184       option:
1185
1186       </para>
1187
1188       <scons_output example="Replace2">
1189          <scons_output_command>scons</scons_output_command>
1190       </scons_output>
1191
1192       <para>
1193
1194       Because the replacement occurs while
1195       the &SConscript; files are being read,
1196       the &cv-link-CCFLAGS;
1197       variable has already been set to
1198       <literal>-DDEFINE2</literal>
1199       by the time the &foo_o; target is built,
1200       even though the call to the &Replace;
1201       method does not occur until later in
1202       the &SConscript; file.
1203
1204       </para>
1205
1206     </section>
1207
1208     <section>
1209     <title>Setting Values Only If They're Not Already Defined:  the &SetDefault; Method</title>
1210
1211       <para>
1212
1213       Sometimes it's useful to be able to specify
1214       that a construction variable should be
1215       set to a value only if the construction environment
1216       does not already have that variable defined
1217       You can do this with the &SetDefault; method,
1218       which behaves similarly to the <function>set_default</function>
1219       method of Python dictionary objects:
1220
1221       </para>
1222
1223       <sconstruct>
1224       env.SetDefault(SPECIAL_FLAG = '-extra-option')
1225       </sconstruct>
1226
1227       <para>
1228
1229       This is especially useful
1230       when writing your own <literal>Tool</literal> modules
1231       to apply variables to construction environments.
1232       <!--
1233       See <xref linkend="chap-tool-modules"></xref>
1234       for more information about writing
1235       Tool modules.
1236       -->
1237
1238       </para>
1239
1240     </section>
1241
1242     <section>
1243     <title>Appending to the End of Values:  the &Append; Method</title>
1244
1245       <para>
1246
1247       You can append a value to
1248       an existing construction variable
1249       using the &Append; method:
1250
1251       </para>
1252
1253       <scons_example name="ex8">
1254         <file name="SConstruct" printme="1">
1255          env = Environment(CCFLAGS = ['-DMY_VALUE'])
1256          env.Append(CCFLAGS = ['-DLAST'])
1257          env.Program('foo.c')
1258         </file>
1259         <file name="foo.c">
1260         int main() { }
1261         </file>
1262       </scons_example>
1263
1264       <para>
1265
1266       &SCons; then supplies both the <literal>-DMY_VALUE</literal> and
1267       <literal>-DLAST</literal> flags when compiling the object file:
1268
1269       </para>
1270
1271       <scons_output example="ex8">
1272          <scons_output_command>scons -Q</scons_output_command>
1273       </scons_output>
1274
1275       <para>
1276
1277       If the construction variable doesn't already exist,
1278       the &Append; method will create it:
1279
1280       </para>
1281
1282       <scons_example name="Append-nonexistent">
1283         <file name="SConstruct" printme="1">
1284          env = Environment()
1285          env.Append(NEW_VARIABLE = 'added')
1286          print "NEW_VARIABLE =", env['NEW_VARIABLE']
1287         </file>
1288       </scons_example>
1289
1290       <para>
1291
1292       Which yields:
1293
1294       </para>
1295
1296       <scons_output example="Append-nonexistent">
1297          <scons_output_command>scons -Q</scons_output_command>
1298       </scons_output>
1299
1300       <para>
1301
1302       Note that the &Append; function tries to be "smart"
1303       about how the new value is appended to the old value.
1304       If both are strings, the previous and new strings
1305       are simply concatenated.
1306       Similarly, if both are lists,
1307       the lists are concatenated.
1308       If, however, one is a string and the other is a list,
1309       the string is added as a new element to the list.
1310
1311       </para>
1312
1313     </section>
1314
1315     <section>
1316     <title>Appending Unique Values:  the &AppendUnique; Method</title>
1317
1318       <para>
1319
1320       Some times it's useful to add a new value
1321       only if the existing construction variable
1322       doesn't already contain the value.
1323       This can be done using the &AppendUnique; method:
1324
1325       </para>
1326
1327       <sconstruct>
1328       env.AppendUnique(CCFLAGS=['-g'])
1329       </sconstruct>
1330
1331       <para>
1332
1333       In the above example,
1334       the <literal>-g</literal> would be added
1335       only if the &cv-CCFLAGS; variable
1336       does not already contain a <literal>-g</literal> value.
1337
1338       </para>
1339
1340     </section>
1341
1342     <section>
1343     <title>Appending to the Beginning of Values:  the &Prepend; Method</title>
1344
1345       <para>
1346
1347       You can append a value to the beginning of
1348       an existing construction variable
1349       using the &Prepend; method:
1350
1351       </para>
1352
1353       <scons_example name="ex9">
1354         <file name="SConstruct" printme="1">
1355          env = Environment(CCFLAGS = ['-DMY_VALUE'])
1356          env.Prepend(CCFLAGS = ['-DFIRST'])
1357          env.Program('foo.c')
1358         </file>
1359         <file name="foo.c">
1360         int main() { }
1361         </file>
1362       </scons_example>
1363
1364       <para>
1365
1366       &SCons; then supplies both the <literal>-DFIRST</literal> and
1367       <literal>-DMY_VALUE</literal> flags when compiling the object file:
1368
1369       </para>
1370
1371       <scons_output example="ex9">
1372          <scons_output_command>scons -Q</scons_output_command>
1373       </scons_output>
1374
1375       <para>
1376
1377       If the construction variable doesn't already exist,
1378       the &Prepend; method will create it:
1379
1380       </para>
1381
1382       <scons_example name="Prepend-nonexistent">
1383         <file name="SConstruct" printme="1">
1384          env = Environment()
1385          env.Prepend(NEW_VARIABLE = 'added')
1386          print "NEW_VARIABLE =", env['NEW_VARIABLE']
1387         </file>
1388       </scons_example>
1389
1390       <para>
1391
1392       Which yields:
1393
1394       </para>
1395
1396       <scons_output example="Prepend-nonexistent">
1397          <scons_output_command>scons -Q</scons_output_command>
1398       </scons_output>
1399
1400       <para>
1401
1402       Like the &Append; function,
1403       the &Prepend; function tries to be "smart"
1404       about how the new value is appended to the old value.
1405       If both are strings, the previous and new strings
1406       are simply concatenated.
1407       Similarly, if both are lists,
1408       the lists are concatenated.
1409       If, however, one is a string and the other is a list,
1410       the string is added as a new element to the list.
1411
1412       </para>
1413
1414     </section>
1415
1416     <section>
1417     <title>Prepending Unique Values:  the &PrependUnique; Method</title>
1418
1419       <para>
1420
1421       Some times it's useful to add a new value
1422       to the beginning of a construction variable
1423       only if the existing value
1424       doesn't already contain the to-be-added value.
1425       This can be done using the &PrependUnique; method:
1426
1427       </para>
1428
1429       <sconstruct>
1430       env.PrependUnique(CCFLAGS=['-g'])
1431       </sconstruct>
1432
1433       <para>
1434
1435       In the above example,
1436       the <literal>-g</literal> would be added
1437       only if the &cv-CCFLAGS; variable
1438       does not already contain a <literal>-g</literal> value.
1439
1440       </para>
1441
1442     </section>
1443
1444   </section>
1445
1446   <section id="sect-execution-environments">
1447   <title>Controlling the Execution Environment for Issued Commands</title>
1448
1449     <para>
1450
1451       When &SCons; builds a target file,
1452       it does not execute the commands with
1453       the same external environment
1454       that you used to execute &SCons;.
1455       Instead, it uses the dictionary
1456       stored in the &cv-link-ENV; construction variable
1457       as the external environment
1458       for executing commands.
1459
1460     </para>
1461
1462     <para>
1463
1464       The most important ramification of this behavior
1465       is that the &PATH; environment variable,
1466       which controls where the operating system
1467       will look for commands and utilities,
1468       is not the same as in the external environment
1469       from which you called &SCons;.
1470       This means that &SCons; will not, by default,
1471       necessarily find all of the tools
1472       that you can execute from the command line.
1473
1474     </para>
1475
1476     <para>
1477
1478       The default value of the &PATH; environment variable
1479       on a POSIX system
1480       is <literal>/usr/local/bin:/bin:/usr/bin</literal>.
1481       The default value of the &PATH; environment variable
1482       on a Windows system comes from the Windows registry
1483       value for the command interpreter.
1484       If you want to execute any commands--compilers, linkers, etc.--that
1485       are not in these default locations,
1486       you need to set the &PATH; value
1487       in the &cv-ENV; dictionary
1488       in your construction environment.
1489
1490     </para>
1491
1492     <para>
1493
1494       The simplest way to do this is to initialize explicitly
1495       the value when you create the construction environment;
1496       this is one way to do that:
1497
1498     </para>
1499
1500     <sconstruct>
1501       path = ['/usr/local/bin', '/bin', '/usr/bin']
1502       env = Environment(ENV = {'PATH' : path})
1503     </sconstruct>
1504
1505     <para>
1506
1507     Assign a dictionary to the &cv-ENV;
1508     construction variable in this way
1509     completely resets the external environment
1510     so that the only variable that will be
1511     set when external commands are executed
1512     will be the &PATH; value.
1513     If you want to use the rest of
1514     the values in &cv-ENV; and only
1515     set the value of &PATH;,
1516     the most straightforward way is probably:
1517
1518     </para>
1519
1520     <sconstruct>
1521       env['ENV']['PATH'] = ['/usr/local/bin', '/bin', '/usr/bin']
1522     </sconstruct>
1523
1524     <para>
1525
1526     Note that &SCons; does allow you to define
1527     the directories in the &PATH; in a string,
1528     separated by the pathname-separator character
1529     for your system (':' on POSIX systems, ';' on Windows):
1530
1531     </para>
1532
1533     <sconstruct>
1534       env['ENV']['PATH'] = '/usr/local/bin:/bin:/usr/bin'
1535     </sconstruct>
1536
1537     <para>
1538
1539     But doing so makes your &SConscript; file less portable,
1540     (although in this case that may not be a huge concern
1541     since the directories you list are likley system-specific, anyway).
1542
1543     </para>
1544
1545     <!--
1546
1547     <scons_example name="ex1">
1548       <file name="SConstruct" printme="1">
1549       env = Environment()
1550       env.Command('foo', [], '__ROOT__/usr/bin/printenv.py')
1551       </file>
1552       <file name="__ROOT__/usr/bin/printenv.py" chmod="0755">
1553       #!/usr/bin/env python
1554       import os
1555       import sys
1556       if len(sys.argv) &gt; 1:
1557           keys = sys.argv[1:]
1558       else:
1559           keys = sorted(os.environ.keys())
1560       for key in keys:
1561           print "    " + key + "=" + os.environ[key]
1562       </file>
1563     </scons_example>
1564
1565     <para>
1566
1567     </para>
1568
1569     <scons_output example="ex1">
1570       <scons_output_command>scons -Q</scons_output_command>
1571     </scons_output>
1572
1573     -->
1574
1575     <section>
1576     <title>Propagating &PATH; From the External Environment</title>
1577
1578       <para>
1579
1580       You may want to propagate the external &PATH;
1581       to the execution environment for commands.
1582       You do this by initializing the &PATH;
1583       variable with the &PATH; value from
1584       the <literal>os.environ</literal>
1585       dictionary,
1586       which is Python's way of letting you
1587       get at the external environment:
1588
1589       </para>
1590
1591       <sconstruct>
1592         import os
1593         env = Environment(ENV = {'PATH' : os.environ['PATH']})
1594       </sconstruct>
1595
1596       <para>
1597
1598       Alternatively, you may find it easier
1599       to just propagate the entire external
1600       environment to the execution environment
1601       for commands.
1602       This is simpler to code than explicity
1603       selecting the &PATH; value:
1604
1605       </para>
1606
1607       <sconstruct>
1608         import os
1609         env = Environment(ENV = os.environ)
1610       </sconstruct>
1611
1612       <para>
1613
1614       Either of these will guarantee that
1615       &SCons; will be able to execute
1616       any command that you can execute from the command line.
1617       The drawback is that the build can behave
1618       differently if it's run by people with
1619       different &PATH; values in their environment--for example,
1620       if both the <literal>/bin</literal> and
1621       <literal>/usr/local/bin</literal> directories
1622       have different &cc; commands,
1623       then which one will be used to compile programs
1624       will depend on which directory is listed
1625       first in the user's &PATH; variable.
1626
1627       </para>
1628
1629     </section>
1630
1631     <section>
1632     <title>Adding to <varname>PATH</varname> Values in the Execution Environment</title>
1633
1634       <para>
1635
1636       One of the most common requirements
1637       for manipulating a variable in the execution environment
1638       is to add one or more custom directories to a search
1639       like the <envar>$PATH</envar> variable on Linux or POSIX systems,
1640       or the <envar>%PATH%</envar> variable on Windows,
1641       so that a locally-installed compiler or other utility
1642       can be found when &SCons; tries to execute it to update a target.
1643       &SCons; provides &PrependENVPath; and &AppendENVPath; functions
1644       to make adding things to execution variables convenient.
1645       You call these functions by specifying the variable
1646       to which you want the value added,
1647       and then value itself.
1648       So to add some <filename>/usr/local</filename> directories
1649       to the <envar>$PATH</envar> and <envar>$LIB</envar> variables,
1650       you might:
1651
1652       </para>
1653
1654       <sconstruct>
1655         env = Environment(ENV = os.environ)
1656         env.PrependENVPath('PATH', '/usr/local/bin')
1657         env.AppendENVPath('LIB', '/usr/local/lib')
1658       </sconstruct>
1659
1660       <para>
1661
1662       Note that the added values are strings,
1663       and if you want to add multiple directories to
1664       a variable like <envar>$PATH</envar>,
1665       you must include the path separate character
1666       (<literal>:</literal> on Linux or POSIX,
1667       <literal>;</literal> on Windows)
1668       in the string.
1669
1670       </para>
1671
1672     </section>
1673
1674   </section>