Search code examples
cmakelinkerrelative-path

CMake: Linking shared lib with other libs with relative path for distribution


Context: I am developing a shared library to... well... share with other user. My library depends on a lot of other libraries which forces me to also share all these dependencies. I want to build this lib using CMake.

Problem: Because my lib users will certainly relocate it to a directory tree different from mine, my lib has to search for its dependencies using a relative path. I mean always, or at least also, search at ./libs directory.

Question: How to modify my CMakeLists.txt in order to accomplish this task?

My project tree:

myproject/
|---- CMakeLists.txt
|---- build/
|---- libs/
  |---- libdep1.so.1.2
  |---- libdep2.so.2.1
  |---- libdep3.so.0.6
|---- src/
  |---- file0.cpp
  |---- file1.cpp
  |---- file1.hpp
  |---- file2.cpp
  |---- file2.hpp
  • build is the directory where I will cd/build to call cmake .. and make.
  • libs is the directory where I will copy in all dependencies (other libs) to share with my lib.
  • src is the directory where I have all my cpp and hpp files.

My CMakeLists.txt

cmake_minimum_required(VERSION 2.8.12)
project(myproject)

SET(CMAKE_BUILD_TYPE Debug)
SET(CMAKE_VERBOSE_MAKEFILE ON)

add_definitions(-std=c++11 -fPIC -m64)

SET (THIRD_PARTY_INCLUDE_ONE /home/3rdparty/xpto/include/)
SET (THIRD_PARTY_INCLUDE_TWO /home/3rdparty/ypto/include/)

include_directories(${THIRD_PARTY_INCLUDE_ONE} ${THIRD_PARTY_INCLUDE_TWO})

add_library(
    mysharedlib SHARED
    ${CMAKE_SOURCE_DIR}/src/file0.cpp
    ${CMAKE_SOURCE_DIR}/src/file1.cpp
    ${CMAKE_SOURCE_DIR}/src/file2.cpp)

SET (DEP_LIBS ${CMAKE_SOURCE_DIR}/libs)

target_link_libraries(
    mysharedlib
    ${DEP_LIBS}/libdep1.so.1.1
    ${DEP_LIBS}/libdep2.so.2.1
    ${DEP_LIBS}/libdep3.so.0.6)

EDIT 1:

I tried to use SET (CMAKE_SHARED_LINKER_FLAGS "-Wl,-rpath,$ORIGIN/libs") just before add_library(...), but seems to have no effect. I thought it could be because I am linking the dependencies using ${DEP_LIBS}/, but If I remove it, it can't find the libs anymore and also causes an error, saying that I should recompile dependencies using -fPIC. I am convinced that this is a side effect, because the libs are all shared libs (libnameofthelib.so) and it works with the CMakeFile.txt without this new flag.


Solution

  • I've made some more tests and actually, the use of SET (CMAKE_SHARED_LINKER_FLAGS "-Wl,-rpath,$ORIGIN/libs") solved the problem.