c++ - cmake,无法运行与预编译共享库链接的可执行文件

标签 c++ macos cmake shared-libraries dynamic-linking

这是我的项目结构:

➜  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

要解决这个问题,我需要做以下两件事之一:

  1. 将 DYLD_LIBRARY_PATH 设置为指向我的库
  2. 将我的lib复制到可执行目录

还有其他选择吗?有没有办法通过 cmake 设置此路径以运行可执行文件而不会出现此错误?

也许我不仅可以设置一个库名称 libsaylib.dylib 作为对可执行文件的依赖,还可以使用 cmake 和 $CMAKE_CURRENT_SOURCE_DIR 为/usr/lib/libc++.1.dylib 设置一个绝对路径?

最佳答案

关于c++ - cmake,无法运行与预编译共享库链接的可执行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53539044/

相关文章:

c++ - 如何让 QML map 流量通过代理,并为程序的其余部分禁用该代理?

c++ - 使用 Cereal 库序列化 Eigen::Matrix

C++ 值未按需要存储

macos - 如何使用 g++ 在 Mac 上使用 freeglut 库编译程序

cmake - 导致 CMAKE 产生错误

c++ - 如何在 CMake 中链接第三方库 (LibUSB)

c++ - 动态分配数组的地址会根据数组的声明方式而变质吗?

ios - 无法运行 'Pod Setup'

macos - Tomcat 连接器 (mod_jk) 出错

windows - 如何从 cmake 执行当前的 MSbuild?