36

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?

user550009
  • 361
  • 1
  • 3
  • 3
  • 2
    Possible duplicate of [g++ linker: force static linking if static library exists?](http://stackoverflow.com/questions/3698321/g-linker-force-static-linking-if-static-library-exists) – John_West Apr 05 '16 at 13:08

3 Answers3

31

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
Leandros
  • 16,612
  • 9
  • 69
  • 105
nos
  • 215,098
  • 54
  • 400
  • 488
  • Surely it shouldn't matter for gcc/binutils, -static and -Bstatic are synonyms in the GNU linker. – nos Aug 31 '11 at 20:26
13

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

g++ -o main main.cpp -l:libmath.a
Dmitry Yudakov
  • 14,839
  • 4
  • 48
  • 51
5

Use this function:

g++ -o main main.cpp /path_to/libmath.a
Somnath Muluk
  • 51,453
  • 32
  • 215
  • 222
karlphillip
  • 89,883
  • 35
  • 240
  • 408