Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to force linker to use shared library instead of static library?

This is a quote from Linux programming book:


% gcc -o app app.o -L. –ltest

Suppose that both libtest.a and libtest.so are available.Then the linker must choose one of the libraries and not the other.The linker searches each directory (first those specified with -L options, and then those in the standard directories).When the linker finds a directory that contains either libtest.a or libtest.so, the linker stops search directories. If only one of the two variants is present in the directory, the linker chooses that variant. Otherwise, the linker chooses the shared library version, unless you explicitly instruct it otherwise.You can use the -static option to demand static archives. For example, the following line will use the libtest.a archive, even if the libtest.so shared library is also available:

% gcc -static -o app app.o -L. –ltest


Since if the linker encounters the directory that contains libtest.a it stops search and uses that static library, how to force the linker to search only for shared library, and not for static?

% gcc -o app app.o -L. libtest.so ?

like image 352
dragan.stepanovic Avatar asked Dec 12 '10 15:12

dragan.stepanovic


People also ask

Can I statically link a shared library?

You can't statically link a shared library (or dynamically link a static one). The flag -static will force the linker to use static libraries (. a) instead of shared (.

Can you mix static and dynamic linking?

If you want to link some modules statically and others dynamically, you need to: Specify the Linker directive CALL when you build the executable program; to do this, check Resolve external calls at link time on the Assembler tab on your project properties Assembler page.

Why shared libraries are preferred over static libraries?

While Shared libraries are faster because shared library code is already in the memory. In Static library no compatibility issue has been observed. On other hand in case of Shared library has compatibility issue as target program will not work if library gets removed from the system .

What are two disadvantages of static linking of shared libraries?

Disadvantages: Constant load time every time a file is compiled and recompiled. Larger in size because the file has to be recompiled every time when adding new code to the executable.


1 Answers

You could use -l option in its form -l:filename if your linker supports it (older versions of ld didn't)

gcc -o app app.o -L. -l:libtest.so

Other option is to use the filename directly without -l and -L

gcc -o app app.o /path/to/library/libtest.so
like image 122
Dmitry Yudakov Avatar answered Sep 17 '22 17:09

Dmitry Yudakov