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

3

39

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?

Diocletian answered 21/12, 2010 at 14:13 Comment(1)
Possible duplicate of g++ linker: force static linking if static library exists?Aeriell
T
32

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
Terriss answered 21/12, 2010 at 14:17 Comment(1)
Surely it shouldn't matter for gcc/binutils, -static and -Bstatic are synonyms in the GNU linker.Terriss
C
15

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

g++ -o main main.cpp -l:libmath.a
Coheman answered 21/12, 2010 at 14:39 Comment(0)
E
5

Use this function:

g++ -o main main.cpp /path_to/libmath.a
Europeanize answered 21/12, 2010 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.