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

时间:2018-11-29 12:26:03

标签: 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})

main.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设置为指向我的lib
  2. 将我的库复制到可执行目录

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

也许我可以使用cmake和$ CMAKE_CURRENT_SOURCE_DIR设置libname libsaylib.dylib作为对可执行文件的依赖,而且可以为/usr/lib/libc++.1.dylib设置绝对路径?

1 个答案:

答案 0 :(得分:1)