1

I'd like to create a liboo.so from a libfoo.a using CMake.

So far I have

include_directories(third-party/includes)
find_library(${thirdparty_LIBRARIES} foo PATHS third-party/lib)
add_library(boo SHARED empty.cpp)
target_link_libraries(boo ${thirdparty_LIBRARIES})
add_executable(runBoo main.cpp)
target_link_libraries(runBoo boo)

where main calls functions from libfoo.so. But provokes the error:

main.cpp:(.text+0x26): undefined reference to `Foo::Foo()'
main.cpp:(.text+0x50): undefined reference to `Foo::sayHello(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'

I'm guessing the symbols aren't added since empty.cpp doesn't use them, but I'm not sure that's the issue and how to overcome it.

I've seen CMake: how create a single shared library from all static libraries of subprojects? , but I'd prefer to stick to lower versions of cmake for now.

I've also seen how to link static library into dynamic library in gcc but I can't get it to work and I'm using CMake anyway.

Community
  • 1
  • 1
quimnuss
  • 1,503
  • 2
  • 17
  • 37

2 Answers2

0

There was just a silly mistake. The corrected code is:

   include_directories(third-party/includes)

   find_library(thirdparty_LIBRARIES foo PATHS third-party/lib) //remove the ${}!

   add_library(boo SHARED empty.cpp)
   target_link_libraries(boo ${thirdparty_LIBRARIES})
   add_executable(runBoo main.cpp)
   target_link_libraries(runBoo boo)
quimnuss
  • 1,503
  • 2
  • 17
  • 37
0

The selected answer is not correct. You are compiling an empty source file into a shared library. You then try to link a static library to this shared library. Since the static library is not used in the code which is compiled, it will not be linked and will be ignored. You must therefore add the -whole-archive linker flag to force the static library to be linked, so something like the following.

add_library(my_shared_lib SHARED src/empty.cpp)
SET(MY_LIB_LINK_LIBRARIES -Wl,--whole-archive my_static_library.a -Wl,--no-whole-archive)
target_link_libraries(my_shared_lib ${MY_LIB_LINK_LIBRARIES})
cyrusbehr
  • 1,100
  • 1
  • 12
  • 32