GCC link option: Static and Dynamic Linking

Posted: December 3, 2012 in Programming
Tags: , , , ,

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.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s