Linking a shared library with another shared lib in linux

前提是你 提交于 2019-11-26 07:34:22

问题


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


回答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

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.




回答2:


When trying to create my own shared library that uses Berkeley DB, I found that I have to put the -ldb at the end of the gcc command or else it blew up saying the symbol 'db_create' was not found. This was under Cygwin.

Specifically, this worked:

gcc -shared -o $b/$libfile nt_*.o -ldb

This did not work:

gcc -ldb -shared -o $b/$libfile nt_*.o




回答3:


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).



来源:https://stackoverflow.com/questions/19424494/linking-a-shared-library-with-another-shared-lib-in-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!