Mixing static libraries and shared libraries
Asked Answered
K

1

6

I have a project where I have one static library libhelper.a and another with my actual shared object library, libtestlib.so. My goal is to link libhelper.a into libtestlib.so. Is that possible on Linux/BSD? When I tried and created a test program I got the following errors:

./prog1:/usr/local/lib/libtestlib.so.1.0: undefined symbol ''

My guess is that this is occurring because libhelper.a was not compiled with -fPIC while libtestlib.so was. What is the proper way to build programs that use shared libraries that also have dependancies on static libraries?

Thanks!

Kiushu answered 25/3, 2011 at 22:44 Comment(2)
"link libhelper.a into libtestlib.so" What?Ruckus
What did you try so far? In any case, I don't know of any way to link non-PIC code into a shared library. Static libraries are usually only linked into executables, that's why they are rarely compiled with PIC. Can't you link both libraries into the executable, or build both with PIC right from the start?Biogen
D
12

My goal is to link libhelper.a into libtestlib.so. Is that possible on Linux?

Sure. This should do:

gcc -shared -fPIC -o libtestlib.so $(OBJS) \
  -Wl,--whole-archive -lhelper -Wl,--no-whole-archive

libhelper.a was not compiled with -fPIC

It's best to rebuild libhelper.a with -fPIC. If that's not possible, above command will still work on Linux/ix86, but not on e.g. Linux/x86_64.

What is the proper way to build programs that use shared libraries that also have dependancies on static libraries?

If you include libhelper.a into libtestlib.so as above, then simple:

gcc main.c -ltestlib

is all you need. If you insist on linking with libhelper.a, then you must tell the end-user that he must link with e.g.

gcc main.c -ltestlib -lhelper

There is no way to specify that libtestlib.so depends on libhelper.a.

Diondione answered 26/3, 2011 at 20:18 Comment(1)
Thanks, I am able to rebuild libhelper.a with -fPIC so i'll continue to do that.Kiushu

© 2022 - 2024 — McMap. All rights reserved.