Search code examples
scons

scons: changing compilation flags for a single source file


I have a fairly complex scons system with several subdirectories, with many libraries and executables. Currently, every SConscript gets its own cloned environment, so I can easily change CFLAGS (or any other wariable) on a per-SConscript basis, but I'd like to change it per-target, and even per-object-file within a target.

I created a simple example SConscript and SConstruct to explain the problem, as follows.

SConstruct:

env = Environment()
env['CFLAGS'] = '-O2'
env.SConscript('SConscript', 'env')

SConscript:

Import('env')
env=env.Clone()
env.Program('foo', ['foo.c', 'bar.c'])

If I run scons, both foo.c and bar.c compile with -O2 flags. I could easily change flags SConscript-wide by just adding env['CFLAGS'] = '...' within the SConscript, but let's say that I want to compile foo.c with -O2, but bar.c with full debugging, -O0 -g. How do I do that (in the simplest possible way)?

The example uses gcc, but I'd like something that can be used with any compiler.

This happens frequently with performance-sensitive projects where compiling everything without optimization would result in unacceptable performance, but there is a need to debug one single file (or a subset of them).


Solution

  • The simplest one-liner answer is probably just to replace your Program line with this:

    env.Program('foo', ['foo.c', env.Object('bar.c', CFLAGS='-g')])
    

    because Program can take Object nodes as well as source files, and you can override any construction variable(s) in any builder (here, we override CFLAGS in the Object builder call). If you want to break out the Object into its own line for clarity:

    debug_objs = env.Object('bar.c', CFLAGS='-g')
    env.Program('foo', ['foo.c', debug_objs])
    

    and of course taking that to the limit you get a system like Avatar33 showed above.