如何使用相对路径将共享库与CMake链接 [英] How to link a shared library with CMake with relative path

查看:707
本文介绍了如何使用相对路径将共享库与CMake链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想链接第三方 libLibrary.so 并将其与我的程序一起分发。如果用户解压缩我的存档,他将获得以下文件夹结构:

I want to link a third-party libLibrary.so and distribute it with my program. If user unzips my archive, he will get this folder structure:

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.so 位于具有 game_executable 的文件夹中,这使得该文件完全不可移植!

However, what I get is my game_executable depends on the .../game/bin/libLibrary.so, not on the ./libLibrary.so that is in the folder with game_executable, making this totally unportable!

我该如何使链接路径

推荐答案

来自文档


默认情况下,如果您不更改任何与RPATH相关的设置,则CMake将链接

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.

这是您所看到的行为。

>

但是,有多种方法可以更改此设置以匹配您所需的行为。

However, there are a number of ways to change this to match the behaviour you require.

上面的一些示例链接文档:

Some examples from the above linked docs:

# 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 ,然后分发已安装的二进制文件。

Using the above you'll likely want to set CMAKE_INSTALL_RPATH and then distribute the installed binary.

如果要从构建树中的二进制文件分发,也可以绕过CMake的rpath处理并使用链接器标志直接修改rpath:

If you want to distribute from the binary in your build tree, it is also possible to bypass CMake's rpath handling and modify the rpath directly using linker flags:

set_target_properties(game PROPERTIES LINK_FLAGS "-Wl,-rpath,./")

这篇关于如何使用相对路径将共享库与CMake链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆