4.2. Linking with Libraries
Prev | Chapter 4. Building and Linking with Libraries | Next

## 4.2. Linking with Libraries

Usually, you build a library because you want to link it with one or more programs. You link libraries with a program by specifying the libraries in the `$LIBS` construction variable, and by specifying the directory in which the library will be found in the `$LIBPATH` construction variable:

    Library('foo', ['f1.c', 'f2.c', 'f3.c'])
    Program('prog.c', LIBS=['foo', 'bar'], LIBPATH='.')

Notice, of course, that you don't need to specify a library prefix (like `lib`) or suffix (like `.a` or `.lib`). SCons uses the correct prefix or suffix for the current system.

On a POSIX or Linux system, a build of the above example would look like:

    % scons -Q
    cc -o f1.o -c f1.c
    cc -o f2.o -c f2.c
    cc -o f3.o -c f3.c
    ar rc libfoo.a f1.o f2.o f3.o
    ranlib libfoo.a
    cc -o prog.o -c prog.c
    cc -o prog prog.o -L. -lfoo -lbar

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

    C:\>scons -Q
    cl /Fof1.obj /c f1.c /nologo
    cl /Fof2.obj /c f2.c /nologo
    cl /Fof3.obj /c f3.c /nologo
    lib /nologo /OUT:foo.lib f1.obj f2.obj f3.obj
    cl /Foprog.obj /c prog.c /nologo
    link /nologo /OUT:prog.exe /LIBPATH:. foo.lib bar.lib prog.obj
    embedManifestExeCheck(target, source, env)

As usual, notice that SCons has taken care of constructing the correct command lines to link with the specified library on each system.

Note also that, if you only have a single library to link with, you can specify the library name in single string, instead of a Python list, so that:

    Program('prog.c', LIBS='foo', LIBPATH='.')

is equivalent to:

    Program('prog.c', LIBS=['foo'], LIBPATH='.')

This is similar to the way that SCons handles either a string or a list to specify a single source file.

Prev | Up | Next
Chapter 4. Building and Linking with Libraries | Home | 4.3. Finding Libraries: the `$LIBPATH` Construction Variable