3.8. Sharing Source Files Between Multiple Programs

It's common to re-use code by sharing source files between multiple programs. One way to do this is to create a library from the common source files, which can then be linked into resulting programs. (Creating libraries is discussed in Chapter 4, below.)

A more straightforward, but perhaps less convenient, way to share source files between multiple programs is simply to include the common files in the lists of source files for each program:


       Program(Split('foo.c common1.c common2.c'))
       Program('bar', Split('bar1.c bar2.c common1.c common2.c'))
    

SCons recognizes that the object files for the common1.c and common2.c source files each only need to be built once, even though the resulting object files are each linked in to both of the resulting executable programs:


       % scons -Q
       cc -o bar1.o -c bar1.c
       cc -o bar2.o -c bar2.c
       cc -o common1.o -c common1.c
       cc -o common2.o -c common2.c
       cc -o bar bar1.o bar2.o common1.o common2.o
       cc -o foo.o -c foo.c
       cc -o foo foo.o common1.o common2.o
    

If two or more programs share a lot of common source files, repeating the common files in the list for each program can be a maintenance problem when you need to change the list of common files. You can simplify this by creating a separate Python list to hold the common file names, and concatenating it with other lists using the Python + operator:


       common = ['common1.c', 'common2.c']
       foo_files = ['foo.c'] + common
       bar_files = ['bar1.c', 'bar2.c'] + common
       Program('foo', foo_files)
       Program('bar', bar_files)
    

This is functionally equivalent to the previous example.