我想链接第三方 libLibrary.so
并将其与我的程序一起分发。如果用户解压缩我的文件,他将得到这个文件夹结构:
game
libLibrary.so
game_executable
game_executable
依赖于 ./libLibrary.so
。
我的项目结构:
game
bin
libLibrary.so
lib
Library.h
src
game_executable.cpp
CMakeLists.txt
我的CMakeLists.txt
:
cmake_minimum_required(VERSION 3.7)
project(game)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/bin)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})
set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR})
set(SOURCE_FILES src/game_executable.cpp)
include_directories(${CMAKE_SOURCE_DIR}/lib)
add_executable(game ${SOURCE_FILES})
target_link_libraries(${PROJECT_NAME} ${CMAKE_BINARY_DIR}/libLibrary.so)
但是,我得到的是我的game_executable
取决于.../game/bin/libLibrary.so
,而不是./libLibrary。所以
它在game_executable
的文件夹中,这使得它完全不可移植!
如何使链接路径成为相对路径而不是绝对路径?
最佳答案
来自documentation :
By default if you don't change any RPATH related settings, CMake will link the executables and shared libraries with full RPATH to all used libraries in the build tree.
这就是您看到的行为。
但是,有多种方法可以更改此设置以匹配您需要的行为。
上述链接文档中的一些示例:
# use, i.e. don't skip the full RPATH for the build tree
SET(CMAKE_SKIP_BUILD_RPATH FALSE)
# when building, don't use the install RPATH already
# (but later on when installing)
SET(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
# the RPATH to be used when installing
SET(CMAKE_INSTALL_RPATH "")
# don't add the automatically determined parts of the RPATH
# which point to directories outside the build tree to the install RPATH
SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)
使用上面的方法,您可能需要设置 CMAKE_INSTALL_RPATH
,然后分发已安装 二进制文件。
如果您想从构建树中的二进制文件进行分发,也可以绕过 CMake 的 rpath 处理并使用链接器标志直接修改 rpath:
set_target_properties(game PROPERTIES LINK_FLAGS "-Wl,-rpath,./")
关于c++ - 如何使用相对路径将共享库与 CMake 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43330165/