Search code examples
c++scons

Scons, building C++ executable from only static libraries


I am attempting to build an executable from three static libraries using scons. However, even though the source files have the .cc suffix, gcc is selected to link the final executable instead of g++. The following SConstruct demonstrates this issue.

lib_a = Library('a.cc')
lib_b = Library('b.cc')
lib_c = Library('c.cc')
Program('prog',[lib_a,lib_b,lib_c])

This then output the following commands to be run.

g++ -o a.o -c a.cc
g++ -o b.o -c b.cc
g++ -o c.o -c c.cc
ar rc liba.a a.o
ranlib liba.a
ar rc libb.a b.o
ranlib libb.a
ar rc libc.a c.o
ranlib libc.a
gcc -o prog liba.a libb.a libc.a

As far as I understand, the Program builder cannot determine from suffix alone whether these libraries came from C or C++ source files, and then chooses C. I know that I could work around this by specifying that C code should be linked using g++ instead of gcc, but that feels dirty. Is there some way to tell scons that it should link this program as C++ code instead of C?


Solution

  • SCons tries to pick a linker, based on the suffixes of the given source files. Since you're sticking the libraries right into the Program Builder, SCons is not able to see that they stem from C++ files (they have the "*.a" extension now). That's why the "smartlink" functionality of SCons switches to its default, which is "$CC" = "gcc" in your case above.

    Against this, you could restructure your build a little, and make it look more like this:

    lib_a = Library('a.cc')
    
    Program('prog', 'main.cc', LIBS=['a'], LIBPATH=['.'])
    

    Now, SCons is able to derive the linker from the file type of "main.cc"...and correctly calls the "g++" executable (if it can be found in the current path).

    I'm not advocating this (the above method should be preferred), but another option would be to simply overwrite the linker that gets used with:

    Program('prog', ..., LINK='g++')