Archive for December, 2012

This post will describe on how to enable static and dynamic linking on gcc (GNU Compiler Collection).

By default, a library is dynamically linked, if the -l option is used to include the library.

For example, the code below will dynamically link somelib as well as libc, libstdc++, etc.

g++ file.cpp -o a.out -l somelib

Meanwhile, if the -static specifier is used, all libraries will be linked statically.

g++ file.cpp -o a.out -l somelib -static

Mixing between linking static and dynamic libraries is also possible; and there are two ways.

  1. Specify the full name of the static lib.
    • For example:

       g++ file.cpp -o a.out libsome.a -lsomelib2

    • By this way, the library libsome.a will be linked statically along with other object files. Meanwhile, somelib2 and the standard c libraries will remain dynamic.
  2. Pass additional options on to the linker.
    • The -Wl,<options> switch is used to pass on the options to the linker.
    • For example:

       g++ file.cpp -o a.out -Wl,-Bstatic -lsome -Wl,-Bdynamic -lsomelib2

    • The command above performs the same linking as method 1, as the -Wl,-Bstatic switch sets the linker in static-linking mode, and the -Wl,-Bdynamic switch sets the linker back to dynamic-linking mode.

Linking between static and shared library is just as simple as this. Hope this tutorial might help anyone encountering this problem.