How To Selectively Static Link Some of The Libraries Using GCC
Usually, we just use “gcc -o output obj1.o obj2.o ... -Llibdir -llib1 -llib2 ...” when linking via GCC, and let ld’s default library searching mechanism that prefers shared libraries to static libraries to help us make the selections. Under such a shelter, many of us don’t care the static-V.S.-dynamic competition or even have no sense of it.
If you are an Linux developer with more than 2 years’ experience, you probably know the difference between static and shared libary and that between static and dynamic linking, and you even possibly know how to link againt static libraries instead of the default prefered shared libraries with gcc’s -static option.
Sometimes however, we want to static link against just some of the libraries but not all, but gcc’ -static option does not give you such a grained control. Now, we must see through gcc to discover ld which is actual workhorse in the linking phase.
There is an option for ld just like -static for gcc but with a more grained control:
-Bstatic
-dn
-non_shared
-static
Do not link against shared libraries. This is only meaningful on platforms for which
shared libraries are supported. The different variants of this option are for com‐
patibility with various systems. You may use this option multiple times on the com‐
mand line: it affects library searching for -l options which follow it. This option
also implies --unresolved-symbols=report-all. This option can be used with -shared.
Doing so means that a shared library is being created but that all of the library's
external references must be resolved by pulling in entries from static libraries.
And another option that is complement:
-Bdynamic
-dy
-call_shared
Link against dynamic libraries. This is only meaningful on platforms for which
shared libraries are supported. This option is normally the default on such
platforms. The different variants of this option are for compatibility with various
systems. You may use this option multiple times on the command line: it affects
library searching for -l options which follow it.
With the two ld options above and the option passing mechanism of gcc(-Wl,option1,option2,…), we can static link against two libraries and dynamic link against the left by:
gcc -o output main.o -Llibdir -Wl,-Bstatic -llib1 -llib2 -Wl,-Bdynamic ...
Loading...