Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force linking with a static library when a shared library of same name is present

Tags:

linux

gcc

g++

ld

Suppose I have a file main.cpp which uses sin() function which is defined in libmath. Also suppose that we have both libmath.a and libmath.so available in the same directory. Now if I issue the command g++ -o main main.cpp -lmath the default behaviour of Linux is to link to the shared library libmath.so. I want to know is there a way to force the program to link with the static library libmath.a without deleting or moving the shared library?

like image 528
user550009 Avatar asked Dec 21 '10 14:12

user550009


People also ask

Can shared library be statically linked?

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

Can a static library depend on another static library?

Static Library Chains This is because static libraries don't link to other static libraries: All of the executable code only gets embedded in the executable. Technically, then, no static library depends on any other static library.


2 Answers

You'll need to pass the -static to the linker, but only for particular libraries you want. e.g.:

g++ -o main main.cpp -Wl,-Bstatic -lmath -Wl,-Bdynamic 
like image 90
nos Avatar answered Oct 08 '22 20:10

nos


If your linker supports -l:<filename> you may use:

g++ -o main main.cpp -l:libmath.a 
like image 38
Dmitry Yudakov Avatar answered Oct 08 '22 19:10

Dmitry Yudakov