Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ linker: force static linking if static library exists?

I've a program which links to many libraries. g++, by default, prefers to link to shared libraries, even if the corresponding archive exists.

How can I change this preference to prefer static archives over dynamic libraries, if a static archive exists?

Note, I used -static option, but it tries to find static archive for all libraries which is not what I want.

like image 976
kumar Avatar asked Sep 13 '10 06:09

kumar


People also ask

What happens when you link a static library?

Static Linking and Static Libraries is the result of the linker making copy of all used library functions to the executable file. Static Linking creates larger binary files, and need more space on disk and main memory.

How static library is linked?

Static libraries are either merged with other static libraries and object files during building/linking to form a single executable or loaded at run-time into the address space of their corresponding executable at a static memory offset determined at compile-time/link-time.

Can you statically link a dynamic library?

You can't statically link a shared library (or dynamically link a static one).

What is static and dynamic linking How does a compiler know if a function belongs to a statically linked source or a dynamically linked source?

The main difference between static and dynamic linking is that static linking copies all library modules used in the program into the final executable file at the final step of the compilation while, in dynamic linking, the linking occurs at run time when both executable files and libraries are placed in the memory.


1 Answers

g++ -Wl,-Bstatic -lz -lfoo -Wl,-Bdynamic -lbar -Wl,--as-needed 

Will link zlib and libfoo as static, and libbar as dynamic . --as-needed will drop any unused dynamic library.

like image 184
naideflan Avatar answered Sep 20 '22 13:09

naideflan