0746793bbdc2f7749a6d3873791d7dc4df3f18e7
[scons.git] / doc / user / environments.xml
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    <programlisting>
470      import os
471    </programlisting>
472
473   <para>
474
475   More usefully, you can use the
476   <envar>os.environ</envar>
477   dictionary in your &SConscript;
478   files to initialize &consenvs;
479   with values from the user's external environment.
480   See the next section,
481   <xref linkend="sect-construction-environments"></xref>,
482   for information on how to do this.
483
484   </para>
485
486   </section>
487
488   <section id="sect-construction-environments">
489   <title>Construction Environments</title>
490
491     <para>
492
493       It is rare that all of the software in a large,
494       complicated system needs to be built the same way.
495       For example, different source files may need different options
496       enabled on the command line,
497       or different executable programs need to be linked
498       with different libraries.
499       &SCons; accommodates these different build
500       requirements by allowing you to create and
501       configure multiple &consenvs;
502       that control how the software is built.
503       A &consenv; is an object
504       that has a number of associated
505       &consvars;, each with a name and a value.
506       (A construction environment also has an attached
507       set of &Builder; methods,
508       about which we'll learn more later.)
509
510     </para>
511
512     <section>
513     <title>Creating a &ConsEnv;:  the &Environment; Function</title>
514
515       <para>
516
517         A &consenv; is created by the &Environment; method:
518
519       </para>
520
521        <programlisting>
522          env = Environment()
523        </programlisting>
524
525       <para>
526
527         By default, &SCons; initializes every
528         new construction environment
529         with a set of &consvars;
530         based on the tools that it finds on your system,
531         plus the default set of builder methods
532         necessary for using those tools.
533         The construction variables
534         are initialized with values describing
535         the C compiler,
536         the Fortran compiler,
537         the linker,
538         etc.,
539         as well as the command lines to invoke them.
540
541       </para>
542
543       <para>
544
545         When you initialize a construction environment
546         you can set the values of the
547         environment's &consvars;
548         to control how a program is built.
549         For example:
550
551       </para>
552
553        <programlisting>
554      import os
555
556          env = Environment(CC = 'gcc',
557                            CCFLAGS = '-O2')
558
559          env.Program('foo.c')
560        </programlisting>
561
562       <para>
563
564         The construction environment in this example
565         is still initialized with the same default
566         construction variable values,
567         except that the user has explicitly specified use of the
568         GNU C compiler &gcc;,
569         and further specifies that the <literal>-O2</literal>
570         (optimization level two)
571         flag should be used when compiling the object file.
572         In other words, the explicit initializations of
573         &cv-link-CC; and &cv-link-CCFLAGS;
574         override the default values in the newly-created
575         construction environment.
576         So a run from this example would look like:
577
578       </para>
579
580       <screen>
581          % <userinput>scons -Q</userinput>
582          gcc -o foo.o -c -O2 foo.c
583          gcc -o foo foo.o
584       </screen>
585
586     </section>
587
588     <section>
589     <title>Fetching Values From a &ConsEnv;</title>
590
591       <para>
592
593       You can fetch individual construction variables
594       using the normal syntax
595       for accessing individual named items in a Python dictionary:
596
597       </para>
598
599       <programlisting>
600          env = Environment()
601          print "CC is:", env['CC']
602       </programlisting>
603
604       <para>
605
606       This example &SConstruct; file doesn't build anything,
607       but because it's actually a Python script,
608       it will print the value of &cv-link-CC; for us:
609
610       </para>
611
612       <screen>
613          % <userinput>scons -Q</userinput>
614          CC is: cc
615          scons: `.' is up to date.
616       </screen>
617
618       <para>
619
620       A construction environment, however,
621       is actually an object with associated methods, etc.
622       If you want to have direct access to only the
623       dictionary of construction variables,
624       you can fetch this using the &Dictionary; method:
625
626       </para>
627
628       <programlisting>
629          env = Environment(FOO = 'foo', BAR = 'bar')
630          dict = env.Dictionary()
631          for key in ['OBJSUFFIX', 'LIBSUFFIX', 'PROGSUFFIX']:
632              print "key = %s, value = %s" % (key, dict[key])
633       </programlisting>
634
635       <para>
636
637       This &SConstruct; file
638       will print the specified dictionary items for us on POSIX
639       systems as follows:
640
641       </para>
642
643       <screen>
644          % <userinput>scons -Q</userinput>
645          key = OBJSUFFIX, value = .o
646          key = LIBSUFFIX, value = .a
647          key = PROGSUFFIX, value = 
648          scons: `.' is up to date.
649       </screen>
650
651       <para>
652
653       And on Windows:
654
655       </para>
656
657       <screen>
658          C:\><userinput>scons -Q</userinput>
659          key = OBJSUFFIX, value = .obj
660          key = LIBSUFFIX, value = .lib
661          key = PROGSUFFIX, value = .exe
662          scons: `.' is up to date.
663       </screen>
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       <programlisting>
674          env = Environment()
675          dict = env.Dictionary()
676          keys = dict.keys()
677          keys.sort()
678          for key in keys:
679              print "construction variable = '%s', value = '%s'" % (key, dict[key])
680       </programlisting>
681
682     </section>
683
684     <section>
685     <title>Expanding Values From a &ConsEnv;:  the &subst; Method</title>
686
687       <para>
688
689       Another way to get information from
690       a construction environment.
691       is to use the &subst; method
692       on a string containing <literal>$</literal> expansions
693       of construction variable names.
694       As a simple example,
695       the example from the previous
696       section that used
697       <literal>env['CC']</literal>
698       to fetch the value of &cv-link-CC;
699       could also be written as:
700
701       </para>
702
703       <programlisting>
704         env = Environment()
705         print "CC is:", env.subst('$CC')
706       </programlisting>
707
708       <para>
709
710       One advantage of using
711       &subst; to expand strings is
712       that construction variables
713       in the result get re-expanded until
714       there are no expansions left in the string.
715       So a simple fetch of a value like
716       &cv-link-CCCOM;:
717
718       </para>
719
720       <programlisting>
721         env = Environment(CCFLAGS = '-DFOO')
722         print "CCCOM is:", env['CCCOM']
723       </programlisting>
724
725       <para>
726
727       Will print the unexpanded value of &cv-CCCOM;,
728       showing us the construction
729       variables that still need to be expanded:
730
731       </para>
732
733       <screen>
734         % <userinput>scons -Q</userinput>
735         CCCOM is: $CC $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES
736         scons: `.' is up to date.
737       </screen>
738
739       <para>
740
741       Calling the &subst; method on <varname>$CCOM</varname>,
742       however:
743
744       </para>
745
746       <programlisting>
747         env = Environment(CCFLAGS = '-DFOO')
748         print "CCCOM is:", env.subst('$CCCOM')
749       </programlisting>
750
751       <para>
752
753       Will recursively expand all of
754       the construction variables prefixed
755       with <literal>$</literal> (dollar signs),
756       showing us the final output:
757
758       </para>
759
760       <screen>
761         % <userinput>scons -Q</userinput>
762         CCCOM is: gcc -DFOO -c -o
763         scons: `.' is up to date.
764       </screen>
765
766       <para>
767
768       Note that because we're not expanding this
769       in the context of building something
770       there are no target or source files
771       for &cv-link-TARGET; and &cv-link-SOURCES; to expand.
772
773       </para>
774
775     </section>
776
777     <section>
778     <title>Controlling the Default &ConsEnv;:  the &DefaultEnvironment; Function</title>
779
780       <para>
781
782       All of the &Builder; functions that we've introduced so far,
783       like &Program; and &Library;,
784       actually use a default &consenv;
785       that contains settings
786       for the various compilers
787       and other tools that
788       &SCons; configures by default,
789       or otherwise knows about
790       and has discovered on your system.
791       The goal of the default construction environment
792       is to make many configurations to "just work"
793       to build software using
794       readily available tools
795       with a minimum of configuration changes.
796
797       </para>
798
799       <para>
800
801       You can, however, control the settings
802       in the default contstruction environment
803       by using the &DefaultEnvironment; function
804       to initialize various settings:
805
806       </para>
807
808       <programlisting>
809
810       DefaultEnvironment(CC = '/usr/local/bin/gcc')
811
812       </programlisting>
813
814       <para>
815
816       When configured as above,
817       all calls to the &Program;
818       or &Object; Builder
819       will build object files with the
820       <filename>/usr/local/bin/gcc</filename>
821       compiler.
822
823       </para>
824
825       <para>
826
827       Note that the &DefaultEnvironment; function
828       returns the initialized
829       default construction environment object,
830       which can then be manipulated like any
831       other construction environment.
832       So the following
833       would be equivalent to the
834       previous example,
835       setting the &cv-CC;
836       variable to <filename>/usr/local/bin/gcc</filename>
837       but as a separate step after
838       the default construction environment has been initialized:
839
840       </para>
841
842       <programlisting>
843
844       env = DefaultEnvironment()
845       env['CC'] = '/usr/local/bin/gcc'
846
847       </programlisting>
848
849       <para>
850
851       One very common use of the &DefaultEnvironment; function
852       is to speed up &SCons; initialization.
853       As part of trying to make most default
854       configurations "just work,"
855       &SCons; will actually
856       search the local system for installed
857       compilers and other utilities.
858       This search can take time,
859       especially on systems with
860       slow or networked file systems.
861       If you know which compiler(s) and/or
862       other utilities you want to configure,
863       you can control the search
864       that &SCons; performs
865       by specifying some specific
866       tool modules with which to
867       initialize the default construction environment:
868
869       </para>
870
871       <programlisting>
872
873       env = DefaultEnvironment(tools = ['gcc', 'gnulink'],
874                                CC = '/usr/local/bin/gcc')
875
876       </programlisting>
877
878       <para>
879
880       So the above example would tell &SCons;
881       to explicitly configure the default environment
882       to use its normal GNU Compiler and GNU Linker settings
883       (without having to search for them,
884       or any other utilities for that matter),
885       and specifically to use the compiler found at
886       <filename>/usr/local/bin/gcc</filename>.
887
888       </para>
889
890     </section>
891
892     <section>
893     <title>Multiple &ConsEnvs;</title>
894
895       <para>
896
897       The real advantage of construction environments
898       is that you can create as many different construction
899       environments as you need,
900       each tailored to a different way to build
901       some piece of software or other file.
902       If, for example, we need to build
903       one program with the <literal>-O2</literal> flag
904       and another with the <literal>-g</literal> (debug) flag,
905       we would do this like so:
906
907       </para>
908
909       <programlisting>
910          opt = Environment(CCFLAGS = '-O2')
911          dbg = Environment(CCFLAGS = '-g')
912
913          opt.Program('foo', 'foo.c')
914
915          dbg.Program('bar', 'bar.c')
916       </programlisting>
917
918       <screen>
919          % <userinput>scons -Q</userinput>
920          cc -o bar.o -c -g bar.c
921          cc -o bar bar.o
922          cc -o foo.o -c -O2 foo.c
923          cc -o foo foo.o
924       </screen>
925
926       <para>
927
928       We can even use multiple construction environments to build
929       multiple versions of a single program.
930       If you do this by simply trying to use the
931       &b-link-Program; builder with both environments, though,
932       like this:
933
934       </para>
935
936       <programlisting>
937          opt = Environment(CCFLAGS = '-O2')
938          dbg = Environment(CCFLAGS = '-g')
939
940          opt.Program('foo', 'foo.c')
941
942          dbg.Program('foo', 'foo.c')
943       </programlisting>
944
945       <para>
946
947       Then &SCons; generates the following error:
948
949       </para>
950
951       <screen>
952          % <userinput>scons -Q</userinput>
953          
954          scons: *** Two environments with different actions were specified for the same target: foo.o
955          File "/home/my/project/SConstruct", line 6, in &lt;module&gt;
956       </screen>
957
958       <para>
959
960       This is because the two &b-Program; calls have
961       each implicitly told &SCons; to generate an object file named
962       <filename>foo.o</filename>,
963       one with a &cv-link-CCFLAGS; value of
964       <literal>-O2</literal>
965       and one with a &cv-link-CCFLAGS; value of
966       <literal>-g</literal>.
967       &SCons; can't just decide that one of them
968       should take precedence over the other,
969       so it generates the error.
970       To avoid this problem,
971       we must explicitly specify
972       that each environment compile
973       <filename>foo.c</filename>
974       to a separately-named object file
975       using the &b-link-Object; builder, like so:
976
977       </para>
978
979       <programlisting>
980          opt = Environment(CCFLAGS = '-O2')
981          dbg = Environment(CCFLAGS = '-g')
982
983          o = opt.Object('foo-opt', 'foo.c')
984          opt.Program(o)
985
986          d = dbg.Object('foo-dbg', 'foo.c')
987          dbg.Program(d)
988       </programlisting>
989
990       <para>
991
992       Notice that each call to the &b-Object; builder
993       returns a value,
994       an internal &SCons; object that
995       represents the object file that will be built.
996       We then use that object
997       as input to the &b-Program; builder.
998       This avoids having to specify explicitly
999       the object file name in multiple places,
1000       and makes for a compact, readable
1001       &SConstruct; file.
1002       Our &SCons; output then looks like:
1003
1004       </para>
1005
1006       <screen>
1007          % <userinput>scons -Q</userinput>
1008          cc -o foo-dbg.o -c -g foo.c
1009          cc -o foo-dbg foo-dbg.o
1010          cc -o foo-opt.o -c -O2 foo.c
1011          cc -o foo-opt foo-opt.o
1012       </screen>
1013
1014     </section>
1015
1016     <section>
1017     <title>Making Copies of &ConsEnvs;:  the &Clone; Method</title>
1018
1019       <para>
1020
1021       Sometimes you want more than one construction environment
1022       to share the same values for one or more variables.
1023       Rather than always having to repeat all of the common
1024       variables when you create each construction environment,
1025       you can use the &Clone; method
1026       to create a copy of a construction environment.
1027
1028       </para>
1029
1030       <para>
1031
1032       Like the &Environment; call that creates a construction environment,
1033       the &Clone; method takes &consvar; assignments,
1034       which will override the values in the copied construction environment.
1035       For example, suppose we want to use &gcc;
1036       to create three versions of a program,
1037       one optimized, one debug, and one with neither.
1038       We could do this by creating a "base" construction environment
1039       that sets &cv-link-CC; to &gcc;,
1040       and then creating two copies,
1041       one which sets &cv-link-CCFLAGS; for optimization
1042       and the other which sets &cv-CCFLAGS; for debugging:
1043
1044       </para>
1045
1046       <programlisting>
1047          env = Environment(CC = 'gcc')
1048          opt = env.Clone(CCFLAGS = '-O2')
1049          dbg = env.Clone(CCFLAGS = '-g')
1050
1051          env.Program('foo', 'foo.c')
1052
1053          o = opt.Object('foo-opt', 'foo.c')
1054          opt.Program(o)
1055
1056          d = dbg.Object('foo-dbg', 'foo.c')
1057          dbg.Program(d)
1058       </programlisting>
1059
1060       <para>
1061
1062       Then our output would look like:
1063
1064       </para>
1065
1066       <screen>
1067          % <userinput>scons -Q</userinput>
1068          gcc -o foo.o -c foo.c
1069          gcc -o foo foo.o
1070          gcc -o foo-dbg.o -c -g foo.c
1071          gcc -o foo-dbg foo-dbg.o
1072          gcc -o foo-opt.o -c -O2 foo.c
1073          gcc -o foo-opt foo-opt.o
1074       </screen>
1075
1076     </section>
1077
1078     <section>
1079     <title>Replacing Values:  the &Replace; Method</title>
1080
1081       <para>
1082
1083       You can replace existing construction variable values
1084       using the &Replace; method:
1085
1086       </para>
1087
1088       <programlisting>
1089          env = Environment(CCFLAGS = '-DDEFINE1')
1090          env.Replace(CCFLAGS = '-DDEFINE2')
1091          env.Program('foo.c')
1092       </programlisting>
1093
1094       <para>
1095
1096       The replacing value
1097       (<literal>-DDEFINE2</literal> in the above example)
1098       completely replaces the value in the
1099       construction environment:
1100
1101       </para>
1102
1103       <screen>
1104          % <userinput>scons -Q</userinput>
1105          cc -o foo.o -c -DDEFINE2 foo.c
1106          cc -o foo foo.o
1107       </screen>
1108
1109       <para>
1110
1111       You can safely call &Replace;
1112       for construction variables that
1113       don't exist in the construction environment:
1114
1115       </para>
1116
1117       <programlisting>
1118          env = Environment()
1119          env.Replace(NEW_VARIABLE = 'xyzzy')
1120          print "NEW_VARIABLE =", env['NEW_VARIABLE']
1121       </programlisting>
1122
1123       <para>
1124
1125       In this case,
1126       the construction variable simply
1127       gets added to the construction environment:
1128
1129       </para>
1130
1131       <screen>
1132          % <userinput>scons -Q</userinput>
1133          NEW_VARIABLE = xyzzy
1134          scons: `.' is up to date.
1135       </screen>
1136
1137       <para>
1138
1139       Because the variables
1140       aren't expanded until the construction environment
1141       is actually used to build the targets,
1142       and because &SCons; function and method calls
1143       are order-independent,
1144       the last replacement "wins"
1145       and is used to build all targets,
1146       regardless of the order in which
1147       the calls to Replace() are
1148       interspersed with calls to
1149       builder methods:
1150
1151       </para>
1152
1153       <programlisting>
1154          env = Environment(CCFLAGS = '-DDEFINE1')
1155          print "CCFLAGS =", env['CCFLAGS']
1156          env.Program('foo.c')
1157
1158          env.Replace(CCFLAGS = '-DDEFINE2')
1159          print "CCFLAGS =", env['CCFLAGS']
1160          env.Program('bar.c')
1161       </programlisting>
1162
1163       <para>
1164
1165       The timing of when the replacement
1166       actually occurs relative
1167       to when the targets get built
1168       becomes apparent
1169       if we run &scons; without the <literal>-Q</literal>
1170       option:
1171
1172       </para>
1173
1174       <screen>
1175          % <userinput>scons</userinput>
1176          scons: Reading SConscript files ...
1177          CCFLAGS = -DDEFINE1
1178          CCFLAGS = -DDEFINE2
1179          scons: done reading SConscript files.
1180          scons: Building targets ...
1181          cc -o bar.o -c -DDEFINE2 bar.c
1182          cc -o bar bar.o
1183          cc -o foo.o -c -DDEFINE2 foo.c
1184          cc -o foo foo.o
1185          scons: done building targets.
1186       </screen>
1187
1188       <para>
1189
1190       Because the replacement occurs while
1191       the &SConscript; files are being read,
1192       the &cv-link-CCFLAGS;
1193       variable has already been set to
1194       <literal>-DDEFINE2</literal>
1195       by the time the &foo_o; target is built,
1196       even though the call to the &Replace;
1197       method does not occur until later in
1198       the &SConscript; file.
1199
1200       </para>
1201
1202     </section>
1203
1204     <section>
1205     <title>Setting Values Only If They're Not Already Defined:  the &SetDefault; Method</title>
1206
1207       <para>
1208
1209       Sometimes it's useful to be able to specify
1210       that a construction variable should be
1211       set to a value only if the construction environment
1212       does not already have that variable defined
1213       You can do this with the &SetDefault; method,
1214       which behaves similarly to the <function>set_default</function>
1215       method of Python dictionary objects:
1216
1217       </para>
1218
1219       <programlisting>
1220       env.SetDefault(SPECIAL_FLAG = '-extra-option')
1221       </programlisting>
1222
1223       <para>
1224
1225       This is especially useful
1226       when writing your own <literal>Tool</literal> modules
1227       to apply variables to construction environments.
1228       <!--
1229       See <xref linkend="chap-tool-modules"></xref>
1230       for more information about writing
1231       Tool modules.
1232       -->
1233
1234       </para>
1235
1236     </section>
1237
1238     <section>
1239     <title>Appending to the End of Values:  the &Append; Method</title>
1240
1241       <para>
1242
1243       You can append a value to
1244       an existing construction variable
1245       using the &Append; method:
1246
1247       </para>
1248
1249       <programlisting>
1250          env = Environment(CCFLAGS = ['-DMY_VALUE'])
1251          env.Append(CCFLAGS = ['-DLAST'])
1252          env.Program('foo.c')
1253       </programlisting>
1254
1255       <para>
1256
1257       &SCons; then supplies both the <literal>-DMY_VALUE</literal> and
1258       <literal>-DLAST</literal> flags when compiling the object file:
1259
1260       </para>
1261
1262       <screen>
1263          % <userinput>scons -Q</userinput>
1264          cc -o foo.o -c -DMY_VALUE -DLAST foo.c
1265          cc -o foo foo.o
1266       </screen>
1267
1268       <para>
1269
1270       If the construction variable doesn't already exist,
1271       the &Append; method will create it:
1272
1273       </para>
1274
1275       <programlisting>
1276          env = Environment()
1277          env.Append(NEW_VARIABLE = 'added')
1278          print "NEW_VARIABLE =", env['NEW_VARIABLE']
1279       </programlisting>
1280
1281       <para>
1282
1283       Which yields:
1284
1285       </para>
1286
1287       <screen>
1288          % <userinput>scons -Q</userinput>
1289          NEW_VARIABLE = added
1290          scons: `.' is up to date.
1291       </screen>
1292
1293       <para>
1294
1295       Note that the &Append; function tries to be "smart"
1296       about how the new value is appended to the old value.
1297       If both are strings, the previous and new strings
1298       are simply concatenated.
1299       Similarly, if both are lists,
1300       the lists are concatenated.
1301       If, however, one is a string and the other is a list,
1302       the string is added as a new element to the list.
1303
1304       </para>
1305
1306     </section>
1307
1308     <section>
1309     <title>Appending Unique Values:  the &AppendUnique; Method</title>
1310
1311       <para>
1312
1313       Some times it's useful to add a new value
1314       only if the existing construction variable
1315       doesn't already contain the value.
1316       This can be done using the &AppendUnique; method:
1317
1318       </para>
1319
1320       <programlisting>
1321       env.AppendUnique(CCFLAGS=['-g'])
1322       </programlisting>
1323
1324       <para>
1325
1326       In the above example,
1327       the <literal>-g</literal> would be added
1328       only if the &cv-CCFLAGS; variable
1329       does not already contain a <literal>-g</literal> value.
1330
1331       </para>
1332
1333     </section>
1334
1335     <section>
1336     <title>Appending to the Beginning of Values:  the &Prepend; Method</title>
1337
1338       <para>
1339
1340       You can append a value to the beginning of
1341       an existing construction variable
1342       using the &Prepend; method:
1343
1344       </para>
1345
1346       <programlisting>
1347          env = Environment(CCFLAGS = ['-DMY_VALUE'])
1348          env.Prepend(CCFLAGS = ['-DFIRST'])
1349          env.Program('foo.c')
1350       </programlisting>
1351
1352       <para>
1353
1354       &SCons; then supplies both the <literal>-DFIRST</literal> and
1355       <literal>-DMY_VALUE</literal> flags when compiling the object file:
1356
1357       </para>
1358
1359       <screen>
1360          % <userinput>scons -Q</userinput>
1361          cc -o foo.o -c -DFIRST -DMY_VALUE foo.c
1362          cc -o foo foo.o
1363       </screen>
1364
1365       <para>
1366
1367       If the construction variable doesn't already exist,
1368       the &Prepend; method will create it:
1369
1370       </para>
1371
1372       <programlisting>
1373          env = Environment()
1374          env.Prepend(NEW_VARIABLE = 'added')
1375          print "NEW_VARIABLE =", env['NEW_VARIABLE']
1376       </programlisting>
1377
1378       <para>
1379
1380       Which yields:
1381
1382       </para>
1383
1384       <screen>
1385          % <userinput>scons -Q</userinput>
1386          NEW_VARIABLE = added
1387          scons: `.' is up to date.
1388       </screen>
1389
1390       <para>
1391
1392       Like the &Append; function,
1393       the &Prepend; function tries to be "smart"
1394       about how the new value is appended to the old value.
1395       If both are strings, the previous and new strings
1396       are simply concatenated.
1397       Similarly, if both are lists,
1398       the lists are concatenated.
1399       If, however, one is a string and the other is a list,
1400       the string is added as a new element to the list.
1401
1402       </para>
1403
1404     </section>
1405
1406     <section>
1407     <title>Prepending Unique Values:  the &PrependUnique; Method</title>
1408
1409       <para>
1410
1411       Some times it's useful to add a new value
1412       to the beginning of a construction variable
1413       only if the existing value
1414       doesn't already contain the to-be-added value.
1415       This can be done using the &PrependUnique; method:
1416
1417       </para>
1418
1419       <programlisting>
1420       env.PrependUnique(CCFLAGS=['-g'])
1421       </programlisting>
1422
1423       <para>
1424
1425       In the above example,
1426       the <literal>-g</literal> would be added
1427       only if the &cv-CCFLAGS; variable
1428       does not already contain a <literal>-g</literal> value.
1429
1430       </para>
1431
1432     </section>
1433
1434   </section>
1435
1436   <section id="sect-execution-environments">
1437   <title>Controlling the Execution Environment for Issued Commands</title>
1438
1439     <para>
1440
1441       When &SCons; builds a target file,
1442       it does not execute the commands with
1443       the same external environment
1444       that you used to execute &SCons;.
1445       Instead, it uses the dictionary
1446       stored in the &cv-link-ENV; construction variable
1447       as the external environment
1448       for executing commands.
1449
1450     </para>
1451
1452     <para>
1453
1454       The most important ramification of this behavior
1455       is that the &PATH; environment variable,
1456       which controls where the operating system
1457       will look for commands and utilities,
1458       is not the same as in the external environment
1459       from which you called &SCons;.
1460       This means that &SCons; will not, by default,
1461       necessarily find all of the tools
1462       that you can execute from the command line.
1463
1464     </para>
1465
1466     <para>
1467
1468       The default value of the &PATH; environment variable
1469       on a POSIX system
1470       is <literal>/usr/local/bin:/bin:/usr/bin</literal>.
1471       The default value of the &PATH; environment variable
1472       on a Windows system comes from the Windows registry
1473       value for the command interpreter.
1474       If you want to execute any commands--compilers, linkers, etc.--that
1475       are not in these default locations,
1476       you need to set the &PATH; value
1477       in the &cv-ENV; dictionary
1478       in your construction environment.
1479
1480     </para>
1481
1482     <para>
1483
1484       The simplest way to do this is to initialize explicitly
1485       the value when you create the construction environment;
1486       this is one way to do that:
1487
1488     </para>
1489
1490     <programlisting>
1491       path = ['/usr/local/bin', '/bin', '/usr/bin']
1492       env = Environment(ENV = {'PATH' : path})
1493     </programlisting>
1494
1495     <para>
1496
1497     Assign a dictionary to the &cv-ENV;
1498     construction variable in this way
1499     completely resets the external environment
1500     so that the only variable that will be
1501     set when external commands are executed
1502     will be the &PATH; value.
1503     If you want to use the rest of
1504     the values in &cv-ENV; and only
1505     set the value of &PATH;,
1506     the most straightforward way is probably:
1507
1508     </para>
1509
1510     <programlisting>
1511       env['ENV']['PATH'] = ['/usr/local/bin', '/bin', '/usr/bin']
1512     </programlisting>
1513
1514     <para>
1515
1516     Note that &SCons; does allow you to define
1517     the directories in the &PATH; in a string,
1518     separated by the pathname-separator character
1519     for your system (':' on POSIX systems, ';' on Windows):
1520
1521     </para>
1522
1523     <programlisting>
1524       env['ENV']['PATH'] = '/usr/local/bin:/bin:/usr/bin'
1525     </programlisting>
1526
1527     <para>
1528
1529     But doing so makes your &SConscript; file less portable,
1530     (although in this case that may not be a huge concern
1531     since the directories you list are likley system-specific, anyway).
1532
1533     </para>
1534
1535     <!--
1536
1537     <scons_example name="ex1">
1538       <file name="SConstruct" printme="1">
1539       env = Environment()
1540       env.Command('foo', [], '__ROOT__/usr/bin/printenv.py')
1541       </file>
1542       <file name="__ROOT__/usr/bin/printenv.py" chmod="0755">
1543       #!/usr/bin/env python
1544       import os
1545       import sys
1546       if len(sys.argv) > 1:
1547           keys = sys.argv[1:]
1548       else:
1549           keys = os.environ.keys()
1550           keys.sort()
1551       for key in keys:
1552           print "    " + key + "=" + os.environ[key]
1553       </file>
1554     </scons_example>
1555
1556     <para>
1557
1558     </para>
1559
1560     <scons_output example="ex1">
1561       <scons_output_command>scons -Q</scons_output_command>
1562     </scons_output>
1563
1564     -->
1565
1566     <section>
1567     <title>Propagating &PATH; From the External Environment</title>
1568
1569       <para>
1570
1571       You may want to propagate the external &PATH;
1572       to the execution environment for commands.
1573       You do this by initializing the &PATH;
1574       variable with the &PATH; value from
1575       the <literal>os.environ</literal>
1576       dictionary,
1577       which is Python's way of letting you
1578       get at the external environment:
1579
1580       </para>
1581
1582       <programlisting>
1583         import os
1584         env = Environment(ENV = {'PATH' : os.environ['PATH']})
1585       </programlisting>
1586
1587       <para>
1588
1589       Alternatively, you may find it easier
1590       to just propagate the entire external
1591       environment to the execution environment
1592       for commands.
1593       This is simpler to code than explicity
1594       selecting the &PATH; value:
1595
1596       </para>
1597
1598       <programlisting>
1599         import os
1600         env = Environment(ENV = os.environ)
1601       </programlisting>
1602
1603       <para>
1604
1605       Either of these will guarantee that
1606       &SCons; will be able to execute
1607       any command that you can execute from the command line.
1608       The drawback is that the build can behave
1609       differently if it's run by people with
1610       different &PATH; values in their environment--for example,
1611       if both the <literal>/bin</literal> and
1612       <literal>/usr/local/bin</literal> directories
1613       have different &cc; commands,
1614       then which one will be used to compile programs
1615       will depend on which directory is listed
1616       first in the user's &PATH; variable.
1617
1618       </para>
1619
1620     </section>
1621
1622     <section>
1623     <title>Adding to <varname>PATH</varname> Values in the Execution Environment</title>
1624
1625       <para>
1626
1627       One of the most common requirements
1628       for manipulating a variable in the execution environment
1629       is to add one or more custom directories to a search
1630       like the <envar>$PATH</envar> variable on Linux or POSIX systems,
1631       or the <envar>%PATH%</envar> variable on Windows,
1632       so that a locally-installed compiler or other utility
1633       can be found when &SCons; tries to execute it to update a target.
1634       &SCons; provides &PrependENVPath; and &AppendENVPath; functions
1635       to make adding things to execution variables convenient.
1636       You call these functions by specifying the variable
1637       to which you want the value added,
1638       and then value itself.
1639       So to add some <filename>/usr/local</filename> directories
1640       to the <envar>$PATH</envar> and <envar>$LIB</envar> variables,
1641       you might:
1642
1643       </para>
1644
1645       <programlisting>
1646         env = Environment(ENV = os.environ)
1647         env.PrependENVPath('PATH', '/usr/local/bin')
1648         env.AppendENVPath('LIB', '/usr/local/lib')
1649       </programlisting>
1650
1651       <para>
1652
1653       Note that the added values are strings,
1654       and if you want to add multiple directories to
1655       a variable like <envar>$PATH</envar>,
1656       you must include the path separate character
1657       (<literal>:</literal> on Linux or POSIX,
1658       <literal>;</literal> on Windows)
1659       in the string.
1660
1661       </para>
1662
1663     </section>
1664
1665   </section>