Search code examples
c++cmakectest

Linking runtime library for test with cmake


Is there any simple way to link at runtime a locally built library to a test with CMAKE?

For example:

enable_testing()
add_executable(Test test/Test.cpp)
target_link_libraries(Test -L../lib/libzmq/build/lib/ zmq)
add_test(
  NAME TestClientZmq
  COMMAND "LD_PRELOAD=../lib/libzmq/build/lib/libzmq.so Test")

Running the test will complain about the missing library at runtime:

error while loading shared libraries: libzmq.so.4.2.0: cannot open shared object file: No such file or directory

I can either:

  1. Set LD_PRELOAD when running ctest
  2. Write a wrapper script which does this and then calls the executable (what I have currently)

I would prefer to do everything in cmake though, since I think it's best to keep all this configuration in a single place to avoid bugs in the future.


Solution

  • Add

    SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
    

    to your CMakeLists.txt. As explained in this wiki article.

    After build, use the below command to make sure the RPATH is properly set:

    objdump -x Test | grep RPATH