How to add a imported library target for a shared library without soname inside project dir in cmake under Linux?

Viewed 514

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

  1. Create target foo using 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 of foo.so to path relative to build directory if I put build directory inside ${CMAKE_SOURCE_DIR}. When I tried to invoke executable bar, GNU ld would report that ../foo.so(or similar) cannot be found.
  2. 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_NO_SONAME ON)
    
    • This would cause cmake to link foo.so with arguments like -lfoo, which in turn requires the shared library name be libfoo.so instead of foo.so, causing build failure.
  3. 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.

0 Answers
Related