Chapter 8. Automatically Putting Command-line Options into their Construction Variables

This chapter describes the MergeFlags, ParseFlags, and ParseConfig methods of a construction environment.

8.1. Merging Options into the Environment: the MergeFlags Function

SCons construction environments have a MergeFlags method that merges a dictionary of values into the construction environment. MergeFlags treats each value in the dictionary as a list of options such as one might pass to a command (such as a compiler or linker). MergeFlags will not duplicate an option if it already exists in the construction environment variable.

MergeFlags tries to be intelligent about merging options. When merging options to any variable whose name ends in PATH, MergeFlags keeps the leftmost occurrence of the option, because in typical lists of directory paths, the first occurrence "wins." When merging options to any other variable name, MergeFlags keeps the rightmost occurrence of the option, because in a list of typical command-line options, the last occurrence "wins."

env = Environment()
env.Append(CCFLAGS = '-option -O3 -O1')
flags = { 'CCFLAGS' : '-whatever -O3' }
env.MergeFlags(flags)
print(env['CCFLAGS'])
   
% scons -Q
['-option', '-O1', '-whatever', '-O3']
scons: `.' is up to date.

Note that the default value for $CCFLAGS is an internal SCons object which automatically converts the options we specified as a string into a list.

env = Environment()
env.Append(CPPPATH = ['/include', '/usr/local/include', '/usr/include'])
flags = { 'CPPPATH' : ['/usr/opt/include', '/usr/local/include'] }
env.MergeFlags(flags)
print(env['CPPPATH'])
   
% scons -Q
['/include', '/usr/local/include', '/usr/include', '/usr/opt/include']
scons: `.' is up to date.

Note that the default value for $CPPPATH is a normal Python list, so we must specify its values as a list in the dictionary we pass to the MergeFlags function.

If MergeFlags is passed anything other than a dictionary, it calls the ParseFlags method to convert it into a dictionary.

env = Environment()
env.Append(CCFLAGS = '-option -O3 -O1')
env.Append(CPPPATH = ['/include', '/usr/local/include', '/usr/include'])
env.MergeFlags('-whatever -I/usr/opt/include -O3 -I/usr/local/include')
print(env['CCFLAGS'])
print(env['CPPPATH'])
   
% scons -Q
['-option', '-O1', '-whatever', '-O3']
['/include', '/usr/local/include', '/usr/include', '/usr/opt/include']
scons: `.' is up to date.

In the combined example above, ParseFlags has sorted the options into their corresponding variables and returned a dictionary for MergeFlags to apply to the construction variables in the specified construction environment.