简体   繁体   中英

Building shared library from static libraries

I've written some code that works as a wrapper around boost::asio and I am looking for a way to pack it as a shared object (.so), to be used by some applications I'm working on, however I would like to remove all dependencies from the boost libraries (mainly because they were custom compiled, and may cause conflict with default pre-built boost libraries). I'm linking my code to the static versions of these special boost libraries, however, the linker provides the following error:

g++ -D_GLIBCXX_USE_CXX11_ABI=0 -I/path_to_boost_headers -Wall -fPIC -o build/obj.o -c include/source.cpp 
g++ -D_GLIBCXX_USE_CXX11_ABI=0 -shared -Wl,-soname,libobj.so.1 -o lib/libobj.so.1 build/obj.o -lc /project_path/lib/libboost_serialization.a /project_path/lib/libboost_wserialization.a /project_path/lib/libboost_system.a
/usr/bin/ld: /home/joao/Work/ASBG/code/cpp/extra/socket/lib/libboost_system.a(error_code.o): relocation R_X86_64_PC32 against symbol `_ZN5boost6system16generic_categoryEv' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Bad value
collect2: error: ld returned 1 exit status

If I'm not mistaken, boost libraries are compiled with -fPIC by default. Even so, I added the flag when compiling boostand replaced the libraries: same output.

Try to put -Wl,--whole-archive and -Wl,--no-whole-archive around the static libraries.

Untested, but something like this could work:

g++ -D_GLIBCXX_USE_CXX11_ABI=0 -shared -Wl,-soname,libobj.so.1 \
  -o lib/libobj.so.1 build/obj.o -lc \
  -Wl,--whole-archive \
  /project_path/lib/libboost_serialization.a \
  /project_path/lib/libboost_wserialization.a \
  /project_path/lib/libboost_system.a \
  -Wl,--no-whole-archive

Notes:

  • The --whole-archive option forces the linker to look at all symbols and not just at unresolved ones. On Linux, there is the concept of weak and strong symbols. I have written an explanation in this answer .
  • I think Link a static lib into a shared lib? is very similar to your problem.

(Also be aware that mixing dynamically and shared libraries is probably not a good idea. You may end up with the combined disadvantages, which goes against your idea of simplification. However, I do not know the whole picture. Just an opinion.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM