Merged revisions 2136-2200,2202-2290,2292-2301 via svnmerge from
[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 =head1 Default construction methods
326
327 The list of default construction methods includes the following:
328
329
330 =head2 The C<new> constructor
331
332 The C<new> method is a Perl object constructor. That is, it is not invoked
333 via a reference to an existing construction environment B<reference>, but,
334 rather statically, using the name of the Perl B<package> where the
335 constructor is defined. The method is invoked like this:
336
337   $env = new cons(<overrides>);
338
339 The environment you get back is blessed into the package C<cons>, which
340 means that it will have associated with it the default methods described
341 below. Individual construction variables can be overridden by providing
342 name/value pairs in an override list. Note that to override any command
343 environment variable (i.e. anything under C<ENV>), you will have to override
344 all of them. You can get around this difficulty by using the C<copy> method
345 on an existing construction environment.
346
347
348 =head2 The C<clone> method
349
350 The C<clone> method creates a clone of an existing construction environment,
351 and can be called as in the following example:
352
353   $env2 = $env1->clone(<overrides>);
354
355 You can provide overrides in the usual manner to create a different
356 environment from the original. If you just want a new name for the same
357 environment (which may be helpful when exporting environments to existing
358 components), you can just use simple assignment.
359
360
361 =head2 The C<copy> method
362
363 The C<copy> method extracts the externally defined construction variables
364 from an environment and returns them as a list of name/value
365 pairs. Overrides can also be provided, in which case, the overridden values
366 will be returned, as appropriate. The returned list can be assigned to a
367 hash, as shown in the prototype, below, but it can also be manipulated in
368 other ways:
369
370   %env = $env1->copy(<overrides>);
371
372 The value of C<ENV>, which is itself a hash, is also copied to a new hash,
373 so this may be changed without fear of affecting the original
374 environment. So, for example, if you really want to override just the
375 C<PATH> variable in the default environment, you could do the following:
376
377   %cons = new cons()->copy();
378   $cons{ENV}{PATH} = "<your path here>";
379   $cons = new cons(%cons);
380
381 This will leave anything else that might be in the default execution
382 environment undisturbed.
383
384 -->
385
386  <para>
387
388    It is rare that all of the software in a large,
389    complicated system needs to be built the same way.
390    For example, different source files may need different options
391    enabled on the command line,
392    or different executable programs need to be linked
393    with different libraries.
394    &SCons; accomodates these different build
395    requirements by allowing you to create and
396    configure multiple &consenvs;
397    that control how the software is built.
398    Technically, a &consenv; is an object
399    that has a number of associated
400    &consvars;, each with a name and a value.
401    (A construction environment also has an attached
402    set of &Builder; methods,
403    about which we'll learn more later.)
404
405  </para>
406
407  <para>
408
409    A &consenv; is created by the &Environment; method:
410
411  </para>
412
413   <programlisting>
414     env = Environment()
415   </programlisting>
416
417  <para>
418
419    By default, &SCons; intializes every
420    new construction environment
421    with a set of &consvars;
422    based on the tools that it finds on your system,
423    plus the default set of builder methods
424    necessary for using those tools.
425    The construction variables
426    are initialized with values describing
427    the C compiler,
428    the Fortran compiler,
429    the linker,
430    etc.,
431    as well as the command lines to invoke them.
432
433  </para>
434
435  <para>
436
437    When you initialize a construction environment
438    you can set the values of the
439    environment's &consvars;
440    to control how a program is built.
441    For example:
442
443  </para>
444
445   <programlisting>
446     env = Environment(CC = 'gcc',
447                       CCFLAGS = '-O2')
448
449     env.Program('foo.c')
450   </programlisting>
451
452  <para>
453
454    The construction environment in this example
455    is still initialized with the same default
456    construction variable values,
457    except that the user has explicitly specified use of the
458    GNU C compiler &gcc;,
459    and further specifies that the <literal>-O2</literal>
460    (optimization level two)
461    flag should be used when compiling the object file.
462    In other words, the explicit initializations of
463    &cv-link-CC; and &cv-link-CCFLAGS;
464    override the default values in the newly-created
465    construction environment.
466    So a run from this example would look like:
467
468  </para>
469
470  <screen>
471     % <userinput>scons -Q</userinput>
472     gcc -o foo.o -c -O2 foo.c
473     gcc -o foo foo.o
474  </screen>
475
476  <section>
477  <title>Multiple &ConsEnvs;</title>
478
479    <para>
480
481    The real advantage of construction environments
482    is that you can create as many different construction
483    environments as you need,
484    each tailored to a different way to build
485    some piece of software or other file.
486    If, for example, we need to build
487    one program with the <literal>-O2</literal> flag
488    and another with the <literal>-g</literal> (debug) flag,
489    we would do this like so:
490
491    </para>
492
493    <programlisting>
494       opt = Environment(CCFLAGS = '-O2')
495       dbg = Environment(CCFLAGS = '-g')
496
497       opt.Program('foo', 'foo.c')
498
499       dbg.Program('bar', 'bar.c')
500    </programlisting>
501
502    <screen>
503       % <userinput>scons -Q</userinput>
504       cc -o bar.o -c -g bar.c
505       cc -o bar bar.o
506       cc -o foo.o -c -O2 foo.c
507       cc -o foo foo.o
508    </screen>
509
510    <para>
511
512    We can even use multiple construction environments to build
513    multiple versions of a single program.
514    If you do this by simply trying to use the
515    &b-link-Program; builder with both environments, though,
516    like this:
517
518    </para>
519
520    <programlisting>
521       opt = Environment(CCFLAGS = '-O2')
522       dbg = Environment(CCFLAGS = '-g')
523
524       opt.Program('foo', 'foo.c')
525
526       dbg.Program('foo', 'foo.c')
527    </programlisting>
528
529    <para>
530
531    Then &SCons; generates the following error:
532
533    </para>
534
535    <screen>
536       % <userinput>scons -Q</userinput>
537       
538       scons: *** Two environments with different actions were specified for the same target: foo.o
539       File "/home/my/project/SConstruct", line 6, in &lt;module&gt;
540    </screen>
541
542    <para>
543
544    This is because the two &b-Program; calls have
545    each implicitly told &SCons; to generate an object file named
546    <filename>foo.o</filename>,
547    one with a &cv-link-CCFLAGS; value of
548    <literal>-O2</literal>
549    and one with a &cv-link-CCFLAGS; value of
550    <literal>-g</literal>.
551    &SCons; can't just decide that one of them
552    should take precedence over the other,
553    so it generates the error.
554    To avoid this problem,
555    we must explicitly specify
556    that each environment compile
557    <filename>foo.c</filename>
558    to a separately-named object file
559    using the &b-link-Object; builder, like so:
560
561    </para>
562
563    <programlisting>
564       opt = Environment(CCFLAGS = '-O2')
565       dbg = Environment(CCFLAGS = '-g')
566
567       o = opt.Object('foo-opt', 'foo.c')
568       opt.Program(o)
569
570       d = dbg.Object('foo-dbg', 'foo.c')
571       dbg.Program(d)
572    </programlisting>
573
574    <para>
575
576    Notice that each call to the &b-Object; builder
577    returns a value,
578    an internal &SCons; object that
579    represents the object file that will be built.
580    We then use that object
581    as input to the &b-Program; builder.
582    This avoids having to specify explicitly
583    the object file name in multiple places,
584    and makes for a compact, readable
585    &SConstruct; file.
586    Our &SCons; output then looks like:
587
588    </para>
589
590    <screen>
591       % <userinput>scons -Q</userinput>
592       cc -o foo-dbg.o -c -g foo.c
593       cc -o foo-dbg foo-dbg.o
594       cc -o foo-opt.o -c -O2 foo.c
595       cc -o foo-opt foo-opt.o
596    </screen>
597
598  </section>
599
600  <section>
601  <title>Copying &ConsEnvs;</title>
602
603    <para>
604
605    Sometimes you want more than one construction environment
606    to share the same values for one or more variables.
607    Rather than always having to repeat all of the common
608    variables when you create each construction environment,
609    you can use the &Clone; method
610    to create a copy of a construction environment.
611
612    </para>
613
614    <para>
615
616    Like the &Environment; call that creates a construction environment,
617    the &Clone; method takes &consvar; assignments,
618    which will override the values in the copied construction environment.
619    For example, suppose we want to use &gcc;
620    to create three versions of a program,
621    one optimized, one debug, and one with neither.
622    We could do this by creating a "base" construction environment
623    that sets &cv-link-CC; to &gcc;,
624    and then creating two copies,
625    one which sets &cv-link-CCFLAGS; for optimization
626    and the other which sets &cv-CCFLAGS; for debugging:
627
628    </para>
629
630    <programlisting>
631       env = Environment(CC = 'gcc')
632       opt = env.Clone(CCFLAGS = '-O2')
633       dbg = env.Clone(CCFLAGS = '-g')
634
635       env.Program('foo', 'foo.c')
636
637       o = opt.Object('foo-opt', 'foo.c')
638       opt.Program(o)
639
640       d = dbg.Object('foo-dbg', 'foo.c')
641       dbg.Program(d)
642    </programlisting>
643
644    <para>
645
646    Then our output would look like:
647
648    </para>
649
650    <screen>
651       % <userinput>scons -Q</userinput>
652       gcc -o foo.o -c foo.c
653       gcc -o foo foo.o
654       gcc -o foo-dbg.o -c -g foo.c
655       gcc -o foo-dbg foo-dbg.o
656       gcc -o foo-opt.o -c -O2 foo.c
657       gcc -o foo-opt foo-opt.o
658    </screen>
659
660  </section>
661
662  <section>
663  <title>Fetching Values From a &ConsEnv;</title>
664
665    <para>
666
667    You can fetch individual construction variables
668    using the normal syntax
669    for accessing individual named items in a Python dictionary:
670
671    </para>
672
673    <programlisting>
674       env = Environment()
675       print "CC is:", env['CC']
676    </programlisting>
677
678    <para>
679
680    This example &SConstruct; file doesn't build anything,
681    but because it's actually a Python script,
682    it will print the value of &cv-link-CC; for us:
683
684    </para>
685
686    <screen>
687       % <userinput>scons -Q</userinput>
688       CC is: cc
689       scons: `.' is up to date.
690    </screen>
691
692    <para>
693
694    A construction environment, however,
695    is actually an object with associated methods, etc.
696    If you want to have direct access to only the
697    dictionary of construction variables,
698    you can fetch this using the &Dictionary; method:
699
700    </para>
701
702    <programlisting>
703       env = Environment(FOO = 'foo', BAR = 'bar')
704       dict = env.Dictionary()
705       for key in ['OBJSUFFIX', 'LIBSUFFIX', 'PROGSUFFIX']:
706           print "key = %s, value = %s" % (key, dict[key])
707    </programlisting>
708
709    <para>
710
711    This &SConstruct; file
712    will print the specified dictionary items for us on POSIX
713    systems as follows:
714
715    </para>
716
717    <screen>
718       % <userinput>scons -Q</userinput>
719       key = OBJSUFFIX, value = .o
720       key = LIBSUFFIX, value = .a
721       key = PROGSUFFIX, value = 
722       scons: `.' is up to date.
723    </screen>
724
725    <para>
726
727    And on Windows:
728
729    </para>
730
731    <screen>
732       C:\><userinput>scons -Q</userinput>
733       key = OBJSUFFIX, value = .obj
734       key = LIBSUFFIX, value = .lib
735       key = PROGSUFFIX, value = .exe
736       scons: `.' is up to date.
737    </screen>
738
739    <para>
740
741    If you want to loop through and print the values of
742    all of the construction variables in a construction environment,
743    the Python code to do that in sorted order might look something like:
744
745    </para>
746
747    <programlisting>
748       env = Environment()
749       dict = env.Dictionary()
750       keys = dict.keys()
751       keys.sort()
752       for key in keys:
753           print "construction variable = '%s', value = '%s'" % (key, dict[key])
754    </programlisting>
755
756  </section>
757
758  <section>
759  <title>Expanding Values From a &ConsEnv;</title>
760
761    <para>
762
763    Another way to get information from
764    a construction environment.
765    is to use the &subst; method
766    on a string containing $-expansions
767    of construction variable names.
768    As a simple example,
769    the example from the previous
770    section that used
771    <literal>env['CC']</literal>
772    to fetch the value of &cv-link-CC;
773    could also be written as:
774
775    </para>
776
777    <programlisting>
778      env = Environment()
779      print "CC is:", env.subst('$CC')
780    </programlisting>
781
782    <para>
783
784    The real advantage of using
785    &subst; to expand strings is
786    that construction variables
787    in the result get
788    re-expanded until
789    there are no expansions left in the string.
790    So a simple fetch of a value like
791    &cv-link-CCCOM;:
792
793    </para>
794
795    <programlisting>
796      env = Environment(CCFLAGS = '-DFOO')
797      print "CCCOM is:", env['CCCOM']
798    </programlisting>
799
800    <para>
801
802    Will print the unexpanded value of &cv-CCCOM;,
803    showing us the construction
804    variables that still need to be expanded:
805
806    </para>
807
808    <screen>
809      % <userinput>scons -Q</userinput>
810      CCCOM is: $CC $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES
811      scons: `.' is up to date.
812    </screen>
813
814    <para>
815
816    Calling the &subst; method on <varname>$CCOM</varname>,
817    however:
818
819    </para>
820
821    <programlisting>
822      env = Environment(CCFLAGS = '-DFOO')
823      print "CCCOM is:", env.subst('$CCCOM')
824    </programlisting>
825
826    <para>
827
828    Will recursively expand all of
829    the $-prefixed construction variables,
830    showing us the final output:
831
832    </para>
833
834    <screen>
835      % <userinput>scons -Q</userinput>
836      CCCOM is: gcc -DFOO -c -o
837      scons: `.' is up to date.
838    </screen>
839
840    <para>
841
842    (Note that because we're not expanding this
843    in the context of building something
844    there are no target or source files
845    for &cv-link-TARGET; and &cv-link-SOURCES; to expand.
846
847    </para>
848
849  </section>
850
851  <section>
852  <title>Modifying a &ConsEnv;</title>
853
854    <para>
855
856    &SCons; provides various methods that
857    support modifying existing values in a construction environment.
858
859    </para>
860
861    <section>
862    <title>Replacing Values in a &ConsEnv;</title>
863
864      <para>
865
866      You can replace existing construction variable values
867      using the &Replace; method:
868
869      </para>
870
871      <programlisting>
872         env = Environment(CCFLAGS = '-DDEFINE1')
873         env.Replace(CCFLAGS = '-DDEFINE2')
874         env.Program('foo.c')
875      </programlisting>
876
877      <para>
878
879      The replacing value
880      (<literal>-DDEFINE2</literal> in the above example)
881      completely replaces the value in the
882      construction environment:
883
884      </para>
885
886      <screen>
887         % <userinput>scons -Q</userinput>
888         cc -o foo.o -c -DDEFINE2 foo.c
889         cc -o foo foo.o
890      </screen>
891
892      <para>
893
894      You can safely call &Replace;
895      for construction variables that
896      don't exist in the construction environment:
897
898      </para>
899
900      <programlisting>
901         env = Environment()
902         env.Replace(NEW_VARIABLE = 'xyzzy')
903         print "NEW_VARIABLE =", env['NEW_VARIABLE']
904      </programlisting>
905
906      <para>
907
908      In this case,
909      the construction variable simply
910      gets added to the construction environment:
911
912      </para>
913
914      <screen>
915         % <userinput>scons -Q</userinput>
916         NEW_VARIABLE = xyzzy
917         scons: `.' is up to date.
918      </screen>
919
920      <para>
921
922      Because the variables
923      aren't expanded until the construction environment
924      is actually used to build the targets,
925      and because &SCons; function and method calls
926      are order-independent,
927      the last replacement "wins"
928      and is used to build all targets,
929      regardless of the order in which
930      the calls to Replace() are
931      interspersed with calls to
932      builder methods:
933
934      </para>
935
936      <programlisting>
937         env = Environment(CCFLAGS = '-DDEFINE1')
938         print "CCFLAGS =", env['CCFLAGS']
939         env.Program('foo.c')
940
941         env.Replace(CCFLAGS = '-DDEFINE2')
942         print "CCFLAGS =", env['CCFLAGS']
943         env.Program('bar.c')
944      </programlisting>
945
946      <para>
947
948      The timing of when the replacement
949      actually occurs relative
950      to when the targets get built
951      becomes apparent
952      if we run &scons; without the <literal>-Q</literal>
953      option:
954
955      </para>
956
957      <screen>
958         % <userinput>scons</userinput>
959         scons: Reading SConscript files ...
960         CCFLAGS = -DDEFINE1
961         CCFLAGS = -DDEFINE2
962         scons: done reading SConscript files.
963         scons: Building targets ...
964         cc -o bar.o -c -DDEFINE2 bar.c
965         cc -o bar bar.o
966         cc -o foo.o -c -DDEFINE2 foo.c
967         cc -o foo foo.o
968         scons: done building targets.
969      </screen>
970
971      <para>
972
973      Because the replacement occurs while
974      the &SConscript; files are being read,
975      the &cv-link-CCFLAGS;
976      variable has already been set to
977      <literal>-DDEFINE2</literal>
978      by the time the &foo_o; target is built,
979      even though the call to the &Replace;
980      method does not occur until later in
981      the &SConscript; file.
982
983      </para>
984
985    </section>
986
987    <!--
988
989    <section>
990    <title>Setting Values Only If They're Not Already Defined</title>
991
992      <para>
993
994      XXX SetDefault()
995
996      </para>
997
998    </section>
999
1000    -->
1001
1002    <section>
1003    <title>Appending to the End of Values in a &ConsEnv;</title>
1004
1005      <para>
1006
1007      You can append a value to
1008      an existing construction variable
1009      using the &Append; method:
1010
1011      </para>
1012
1013      <programlisting>
1014         env = Environment(CCFLAGS = '-DMY_VALUE')
1015         env.Append(CCFLAGS = ' -DLAST')
1016         env.Program('foo.c')
1017      </programlisting>
1018
1019      <para>
1020
1021      &SCons; then supplies both the <literal>-DMY_VALUE</literal> and
1022      <literal>-DLAST</literal> flags when compiling the object file:
1023
1024      </para>
1025
1026      <screen>
1027         % <userinput>scons -Q</userinput>
1028         cc -o foo.o -c -DMY_VALUE -DLAST foo.c
1029         cc -o foo foo.o
1030      </screen>
1031
1032      <para>
1033
1034      If the construction variable doesn't already exist,
1035      the &Append; method will create it:
1036
1037      </para>
1038
1039      <programlisting>
1040         env = Environment()
1041         env.Append(NEW_VARIABLE = 'added')
1042         print "NEW_VARIABLE =", env['NEW_VARIABLE']
1043      </programlisting>
1044
1045      <para>
1046
1047      Which yields:
1048
1049      </para>
1050
1051      <screen>
1052         % <userinput>scons -Q</userinput>
1053         NEW_VARIABLE = added
1054         scons: `.' is up to date.
1055      </screen>
1056
1057      <!--
1058
1059      XXX AppendUnique()
1060
1061      -->
1062
1063    </section>
1064
1065    <section>
1066    <title>Appending to the Beginning of Values in a &ConsEnv;</title>
1067
1068      <para>
1069
1070      You can append a value to the beginning of
1071      an existing construction variable
1072      using the &Prepend; method:
1073
1074      </para>
1075
1076      <programlisting>
1077         env = Environment(CCFLAGS = '-DMY_VALUE')
1078         env.Prepend(CCFLAGS = '-DFIRST ')
1079         env.Program('foo.c')
1080      </programlisting>
1081
1082      <para>
1083
1084      &SCons; then supplies both the <literal>-DFIRST</literal> and
1085      <literal>-DMY_VALUE</literal> flags when compiling the object file:
1086
1087      </para>
1088
1089      <screen>
1090         % <userinput>scons -Q</userinput>
1091         cc -o foo.o -c -DFIRST -DMY_VALUE foo.c
1092         cc -o foo foo.o
1093      </screen>
1094
1095      <para>
1096
1097      If the construction variable doesn't already exist,
1098      the &Prepend; method will create it:
1099
1100      </para>
1101
1102      <programlisting>
1103         env = Environment()
1104         env.Prepend(NEW_VARIABLE = 'added')
1105         print "NEW_VARIABLE =", env['NEW_VARIABLE']
1106      </programlisting>
1107
1108      <para>
1109
1110      Which yields:
1111
1112      </para>
1113
1114      <screen>
1115         % <userinput>scons -Q</userinput>
1116         NEW_VARIABLE = added
1117         scons: `.' is up to date.
1118      </screen>
1119
1120      <!--
1121
1122      XXX PrependUnique()
1123
1124      -->
1125
1126    </section>
1127
1128    <!--
1129
1130    <section>
1131    <title>Adding to Values in the Execution Environment</title>
1132
1133      <para>
1134
1135      XXX AppendENVPath()
1136
1137      XXX PrependENVPath()
1138
1139      </para>
1140
1141    </section>
1142
1143    -->
1144
1145  </section>