Building and Linking with Libraries

It's often useful to organize large software projects by collecting parts of the software into one or more libraries. SCons makes it easy to create libraries and to use them in the programs.

Building Libraries

You build your own libraries by specifying Library instead of Program:

      Library('foo', ['f1.c', 'f2.c', 'f3.c'])
    

SCons uses the appropriate library prefix and suffix for your system. So on POSIX or Linux systems, the above example would build as follows (although ranlib may not be called on all systems):

      % scons -Q
      cc -c -o f1.o f1.c
      cc -c -o f2.o f2.c
      cc -c -o f3.o f3.c
      ar r libfoo.a f1.o f2.o f3.o
      ranlib libfoo.a
    

On a Windows system, a build of the above example would look like:

      C:\>scons -Q
      cl /nologo /c f1.c /Fof1.obj
      cl /nologo /c f2.c /Fof2.obj
      cl /nologo /c f3.c /Fof3.obj
      lib /nologo /OUT:foo.lib f1.obj f2.obj f3.obj
    

The rules for the target name of the library are similar to those for programs: if you don't explicitly specify a target library name, SCons will deduce one from the name of the first source file specified, and SCons will add an appropriate file prefix and suffix if you leave them off.

Building Static Libraries Explicitly: the StaticLibrary Builder

The Library function builds a traditional static library. If you want to be explicit about the type of library being built, you can use the synonym StaticLibrary function instead of Library:

        StaticLibrary('foo', ['f1.c', 'f2.c', 'f3.c'])
      

There is no functional difference between the StaticLibrary and Library functions.

Building Shared (DLL) Libraries: the SharedLibrary Builder

If you want to build a shared library (on POSIX systems) or a DLL file (on Windows systems), you use the SharedLibrary function:

        SharedLibrary('foo', ['f1.c', 'f2.c', 'f3.c'])
      

The output on POSIX:

        % scons -Q
        cc -c -o f1.os f1.c
        cc -c -o f2.os f2.c
        cc -c -o f3.os f3.c
        cc -shared -o libfoo.so f1.os f2.os f3.os
      

And the output on Windows:

        C:\>scons -Q
        cl /nologo /c f1.c /Fof1.obj
        cl /nologo /c f2.c /Fof2.obj
        cl /nologo /c f3.c /Fof3.obj
        link /nologo /dll /out:foo.dll /implib:foo.lib f1.obj f2.obj f3.obj
      

Notice again that SCons takes care of building the output file correctly, adding the -shared option for a POSIX compilation, and the /dll option on Windows.