Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing static libraries and shared libraries

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!

like image 951
Anin Teger Avatar asked Mar 25 '11 22:03

Anin Teger


People also ask

Why do we need shared libraries in addition to static ones?

The most significant advantage of shared libraries is that there is only one copy of code loaded in memory, no matter how many processes are using the library. For static libraries each process gets its own copy of the code. This can lead to significant memory wastage.

When use static library vs shared library?

Shared libraries are added during linking process when executable file and libraries are added to the memory. Static libraries are much bigger in size, because external programs are built in the executable file.

Can a static library use a dynamic library?

Yes for instance when you call windows functions from within your static lib they are normally from some dynamic library so there should be no difference.

What is the disadvantage of static linking in OS?

The major disadvantages of static linking are increases in the memory required to run an executable, network bandwidth to transfer it, and disk space to store it.


1 Answers

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.

like image 60
Employed Russian Avatar answered Sep 28 '22 08:09

Employed Russian