问题
I've look for a solutions to my trouble and just get some clues, but I could not find any consistent solution: I have the code of a dynamic library (libdyna.so), that uses the functions of 3 statics libraries (libone.a, libtwo.a, libthree.a) and the log4cpp library. And when I built it the first time everything looked fine, I could make the 'libdyna.so', but when y tested it with my java test program though a wrapper (the jni wrapper works fine) I got lots of undefined references.
Then I put the "-z defs" flag to the make file and a lot of undefined references appear and I could not compile the dynamic library again.
I've made the 'nm' command with the three statics libraries and it exports all the functions that I use in the dyna lib correctly. But when I made nm over the 'libdyna.so', the one which includes the 3 statics libs, I found Undefined symbols (functions).
I think that the solutions must be something like adding some flag to the linker when I want to made the dynamic one, but i really don't know. Could anyone help me, or tell me some ideas?. if some code is needed please let me know and I'll paste it here. Thanks a lot.
P/D: Sorry for my bad english.
回答1:
You could use linker option --whole-archive
, it will include whole static libraries and will probably solve your problem, although the library could become quite big.
g++ -shared -o libdyna.so dyna.o -Wl,-whole-archive -la -lb -lc -Wl,-no-whole-archive
man ld:
For each archive mentioned on the command line after the --whole-archive option, include every object file in the archive in the link, rather than searching the archive for the required object files. This is normally used to turn an archive file into a shared library, forcing every object to be included in the resulting shared library.
Don't forget closing -Wl,-no-whole-archive
.
Check also the order of appearing of the libraries in gcc command line, make sure they are after the object files of the dynamic library, otherwise the linker will not load them. If libone uses libtwo for example, it's also important for libone to appear before libtwo. It could be alternative solution for your problem.
来源:https://stackoverflow.com/questions/5860818/dynamic-library-uses-statics-libraries-undefined-symbols-appears