Linking a shared library with another shared lib in linux
I am trying to build a shared library. Let us say libabc.so .It uses another .so file , say lib123.so (a lib in /usr/local/lib) .Now i am using my shared lib libabc.so in my application. say my-app.I want to know how i should link these binaries??i don't want to link my-app with lib123.so directly. my-app should be linked with only libabc.so. How can i do this?
Thanks in advance. I am using g++ compiler
Solution 1:
Suppose that libabc.so
is obtained from posiition independent object code files abc1.pic.o
and abc2.pic.o
; then you have built them with e.g.
gcc -Wall -fPIC -O -g abc1.c -c -o abc1.pic.o
gcc -Wall -fPIC -O -g abc2.c -c -o abc2.pic.o
and you build libabc.so
with
gcc -shared abc1.pic.o abc2.pic.o -L/usr/local/lib -l123 -o libabc.so
I added -L/usr/local/lib
before -l123
because I am assuming you have a /usr/local/lib/lib123.so
shared library.
Read also the Program Library HowTo.
As you see, you may link a shared library lib123.so
into your own shared library libabc.so
Then check with ldd libabc.so
You may want to set up some rpath in your libabc.so
by adding -Wl,-rpath
and -Wl,$RPATHDIR
to the linking command.
For much more details, read Drepper's paper How to write shared libraries
PS. Don't use a static library for lib123.a
(it should be PIC). If you link non-PIC code into a shared object, you lose most of the advantages of shared objects, and the dynamic linker ld.so has to do zillions of relocations.
Solution 2:
Following the same procedure pointed out by Basile Starynkevitch, for example, I have a library which depends on libm.so
, so the compilation for the library objects are:
gcc -fPIC -Wall -g -I include -I src -c src/wavegen.c -o build/arm/wavegen.o
gcc -fPIC -Wall -g -I include -I src -c src/serial.c -o build/arm/serial.o
To compile the library, however, in some versions of gcc the order where library references are placed, is important, so I suggest, to ensure compatibility, placing those references at the end of the command:
gcc -shared -Wl,-soname,libserial.so.1 -o lib/libserial.so.1.0 build/arm/wavegen.o build/arm/serial.o -lm
I have tested in PC (gcc v.8.3.0) and in ARM (gcc v.4.6.3).