c++linuxcmake

CMake link external shared lib on linux?


I try to link an external library on Linux in CMake. The compile and make are fine. But when I run it, it says:

./test/calculator_test: error while loading shared libraries: ../../../third_party/add/lib/add.so: cannot open shared object file: No such file or directory

File tree (I removed some unnecessary part):

├── CMakeLists.txt
├── build
├── src
├── test
│   ├── CMakeLists.txt
│   └── calculator
│       ├── CMakeLists.txt
│       └── calculator_test.cpp
└── third_party
    ├── add
    │   ├── include
    │   │   └── add.h
    │   └── lib
    │       └── add.so
    └── googletest
        ...

test/calculator/CMakeLists.txt:

add_library(lib-add SHARED IMPORTED)

set_target_properties(lib-add
                    PROPERTIES
                    IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/third_party/add/lib/add.so"
                    INTERFACE_INCLUDE_DIRECTORIES "${PROJECT_SOURCE_DIR}/third_party/add/include"
                    )


add_executable(calculator_test calculator_test.cpp)

target_link_libraries(calculator_test PRIVATE lib-add lib-sub)

set_target_properties(calculator_test 
                     PROPERTIES
                     RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/test"
                     COMMAND calculator_test
                     )

So why and how to make it correct?


Solution

  • I think it is a bug of cmake.

    I see the problem when using 3.22.1 (Ubuntu 22.04). After upgrading to cmake 3.27 it works. It seems it was fixed in cmake 3.24.