G ++ linker: forced static linking if there is a static library?

I have a program that links to many libraries. g++ , by default, prefers to reference shared libraries, even if the corresponding archive exists.

How can I change this preference by preferring static archives through dynamic libraries if a static archive exists?

Note. I used the -static option, but it is trying to find a static archive for all libraries that are not what I want.

+54
c ++ c linker g ++ static-libraries
Sep 13 '10 at 6:52
source share
3 answers
 g++ -Wl,-Bstatic -lz -lfoo -Wl,-Bdynamic -lbar -Wl,--as-needed 

Binds zlib and libfoo as static, and libbar as dynamic. --as-needed will remove any unused dynamic library.

+67
Sep 13 '10 at 2:00
source share

If you want to statically link one or two libraries to the rest, including system libraries, being dynamic, it is often easier to just reference the static library by its full name. Those. instead of using -l and -l to get g ++ to resolve the library from what it finds, just add the full path to the library as input. By taking the g ++ command above to bind the main program of the main.o application with static libz, libfoo, dynamic libbar, libglib, etc .:

  g++ main.o /usr/lib/libz.a /usr/lib/libfoo.a -lbar 

Edit August 3, 17: I just read this answer, which is more than -l: and offers an alternative way ( -l: to specify the library directly.

+5
Oct 03 '16 at 22:53 on
source share

g ++ binds dynamic libraries by default. therefore , we have to install some kind of pkg.

gcc -o main main.cpp file main

main: executable 64-bit LSB ELF, x86-64, version 1 (SYSV), dynamically linked (uses shared libraries)

yum install gcc-c ++ glibc -static libstdc ++ -static

And gcc

g ++ -static -o main main.cpp

main file

main: 64-bit LSF ELF executable, x86-64 version 1 (GNU / Linux), statically linked

So this is statically connected.

0
Jun 12 '19 at 2:34
source share



All Articles