c++ - cmake,无法运行与预编译共享库链接的可执行文件
问题描述
这是我的项目结构:
➜ helloWorld ls
[18/11/29|11:19AM]
CMakeLists.txt cmake-build-debug main.cpp third_parties
➜ helloWorld
➜ helloWorld ls third_parties/say
[18/11/29|11:19AM]
compilesaylib.sh libsaylib.dylib saylib.cpp saylib.h
➜ helloWorld
CMakeLists.txt 看起来像这样:
cmake_minimum_required(VERSION 3.12)
cmake_policy(SET CMP0015 NEW)
SET(CMAKE_SYSTEM_NAME Darwin)
project (myproject)
include_directories(${CMAKE_SOURCE_DIR}/third_parties/say)
file(GLOB LIBRARIES "third_parties/say/*.dylib")
message("LIBRARIES = ${LIBRARIES}")
add_executable(myproject main.cpp)
target_link_libraries(myproject ${LIBRARIES})
主.cpp:
#include <iostream>
#include "saylib.h"
int main() {
say("Hi there!");
return 0;
}
我得到的错误是下一个:
➜ cmake-build-debug ./helloWorld
[18/11/29|10:56AM]
dyld: Library not loaded: libsaylib.dylib
Referenced from: /Users/oleg/CLionProjects/helloWorld/cmake-build-debug/./helloWorld
Reason: image not found
[1] 17995 abort ./helloWorld
➜ cmake-build-debug
当我在可执行文件上使用 otool 时,我得到了这个:
➜ cmake-build-debug otool -L helloWorld
[18/11/29|10:56AM]
helloWorld:
libsaylib.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 400.9.4)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.200.5)
➜ cmake-build-debug
要解决此问题,我需要做以下两件事之一:
- 将 DYLD_LIBRARY_PATH 设置为指向我的库
- 将我的库复制到可执行目录
还有其他选择吗?有没有办法通过 cmake 设置此路径以运行可执行文件而不会出现此错误?
也许我可以以某种方式不仅将库名称 libsaylib.dylib 设置为对可执行文件的依赖项,还可以使用 cmake 和 $CMAKE_CURRENT_SOURCE_DIR 设置 /usr/lib/libc++.1.dylib 的绝对路径?
解决方案
第三个选项是使用 RPATH 变量来调整搜索库的位置。 https://gitlab.kitware.com/cmake/community/wikis/doc/cmake/RPATH-handling
推荐阅读
- database - 如何使用 awk 处理 ASCII 不可打印字符
- javascript - php变量通过javascript获取后如何转换为float?Php 的 (float) 转换函数返回 0 并且不转换
- c# - 从 JSON 中创建动态对象,忽略空字段
- python - 将列表拆分为批次以处理每个批次中的元素多线程
- sed - 如何用多行格式的多行替换一行?
- azure-data-factory - 通过 Azure 数据工厂加载 JSON 文件
- c - 为什么可以在嵌套循环中声明 STRUCT?
- reactjs - 如何为 React Native 中的 setState 切换通用处理程序
- java - 无法建立实体管理器工厂 - JPA/Hibernate
- python - 我可以声明不兼容的 python 依赖项吗?