Hello.
I have a situation like this.
add_library(lib INTERFACE)
target_sources(lib INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/lib.cpp")
target_include_directories(lib INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}")
Next, I want to create a shared library, which links to this library, so that all things from lib.cpp get compiled into it:
add_library(lib_shared SHARED)
target_link_libraries(lib_shared PUBLIC lib)
And finally, I link it to my main executable:
add_executable(main "main.cpp")
target_link_libraries(main PRIVATE lib_shared)
However, when I link to it, I don’t get a shared library linked into “main”, I don’t get a dependency on lib_shared.so. Instead, I get lib.cpp being compiled as a part of main target (due to “lib” target being INTERFACE), so I don’t get a dynamic linking to shared lib produced by lib_shared target.
The only way I’ve found to prevent this is to do this:
target_link_libraries(lib_shared PRIVATE lib)
This way, “main” links to “lib_shared” dynamically. However, I lose the include directories which were declared by “target_include_directories” in “lib” target and I have to manually declare them once again, so in the end I have to do this:
add_library(lib_shared)
target_link_libraries(lib_shared PUBLIC lib)
add_executable(main "main.cpp")
target_include_directories(main PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/lib")
target_link_libraries(main PUBLIC lib_shared)
Is there a way to avoid this? How can shared libraries link to interface libraries but still be “true” shared libraries when other targets link to said shared libraries?