Telling gcc directly to link a library statically
It feels strange to me to use -Wl,-Bstatic
in order to tell gcc
which libraries I want to link with statically. After all I'm telling gcc
directly all other information about linking with libraries (-Ldir
, -llibname
).
Is it possible to tell the gcc driver directly which libraries should be linked statically?
Clarification: I know that if a certain library exists only in static versions it'll use it without -Wl,-Bstatic
, but I want to imply gcc
to prefer the static library. I also know that specifying the library file directly would link with it, but I prefer to keep the semantic for including static and dynamic libraries the same.
Solution 1:
Use -l:
instead of -l
. For example -l:libXYZ.a
to link with libXYZ.a
. Notice the lib
and .a
are written out, as opposed to -lXYZ
which would auto-expand to libXYZ.so
/libXYZ.a
.
It is an option of the GNU ld
linker:
-l namespec
... If namespec is of the form:filename
,ld
will search the library path for a file called filename, otherwise it will search the library path for a file calledlibnamespec.a
. ... on ELF ... systems,ld
will search a directory for a library calledlibnamespec.so
before searching for one calledlibnamespec.a
. ... Note that this behavior does not apply to:filename
, which always specifies a file called filename."
(Since binutils 2.18)
Note that this only works with the GNU linker. If your ld
isn't the GNU one you're out of luck.
Solution 2:
You can add .a file in the linking command:
gcc yourfiles /path/to/library/libLIBRARY.a
But this is not talking with gcc driver, but with ld
linker as options like -Wl,anything
are.
When you tell gcc or ld -Ldir -lLIBRARY
, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose
). To change order of library types checked you can use -Wl,-Bstatic
and -Wl,-Bdynamic
. Here is a man page of gnu LD: http://linux.die.net/man/1/ld
To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:
gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3
Assuming that default setting of ld is to use dynamic libraries (it is on Linux).