Suppose there's a shared library file called foo.so in ${CMAKE_SOURCE_DIR}, which is created without soname specified. (In this case I created this library file by writing a simple C source file foo.c and then build it with g++ -shared -o foo.so -std=c++17 -O2 -fPIC foo.c)
Also there's an executable target called bar in ${CMAKE_SOURCE_DIR}/CMakeLists.txt that wants to link with this shared library. It also has its install command written as follows:
install(TARGETS bar
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
RUNTIME DESTINATION bin
)
I am going to build this project under ${CMAKE_SOURCE_DIR}/build and installed it in somewhere outside ${CMAKE_SOURCE_DIR}. My question is, how should I create the imported library called foo so that after I call target_link_libraries(bar foo) and install the whole project, the generated executable for target bar would correctly find and link foo.so?
Approaches I've tried yet failed
Create target
foousing the following code:add_library(foo SHARED IMPORTED) set_target_properties(foo PROPERTIES IMPORTED_LOCATION ${CMAKE_SOURCE_DIR}/foo.so)- Though it would work if I build the project out of
${CMAKE_SOURCE_DIR}, CMake would convert path offoo.soto path relative to build directory if I put build directory inside${CMAKE_SOURCE_DIR}. When I tried to invoke executablebar, GNU ld would report that../foo.so(or similar) cannot be found.
- Though it would work if I build the project out of
Create target
foousing the following code:add_library(foo SHARED IMPORTED) set_target_properties(foo PROPERTIES IMPORTED_LOCATION ${CMAKE_SOURCE_DIR}/foo.so IMPORTED_NO_SONAME ON)- This would cause cmake to link
foo.sowith arguments like-lfoo, which in turn requires the shared library name belibfoo.soinstead offoo.so, causing build failure.
- This would cause cmake to link
Create target foo using the following code:
add_library(foo SHARED IMPORTED) set_target_properties(foo PROPERTIES IMPORTED_LOCATION ${CMAKE_SOURCE_DIR}/foo.so IMPORTED_SONAME "foo.so")- The result is exactly the same with 1, and I cannot observe any differences during build and install process.
I am facing this problem under Linux and I'm using GCC/G++ 11.0, GNU ld 2.36.1, GNU libc 2.33 and CMake 3.21.3, but of course, solutions for any other versions (if any) would be welcomed too.