我有一个小示例项目,我试图将动态库链接到可执行文件。
文件结构如下:
-项目
cmake_minimum_required (VERSION 3.3.2)
# Project
# --------------
project (cmakefun)
# Subdirectories
# --------------
add_subdirectory(dlibs)
add_subdirectory(exes)
# Target
# --------------
set(CMAKE_INSTALL_PREFIX "${PROJECT_SOURCE_DIR}/cmakefun")
--dlibs
----引擎.h
#pragma once
#include <iostream>
class Engine {
public:
Engine();
void Function();
};
----引擎.cpp
#include "engine.h"
using namespace std;
Engine::Engine(){}
void Engine::Function() {
cout << "Function" << endl;
}
----CMakeLists.txt
# Project
# --------------
project(engine)
# Headers and Sources
# --------------
set(${PROJECT_NAME}_headers engine.h)
set(${PROJECT_NAME}_sources engine.cpp)
# Create Binaries
# --------------
add_library (${PROJECT_NAME} SHARED ${${PROJECT_NAME}_headers} ${${PROJECT_NAME}_sources})
# Target
# --------------
install(TARGETS ${PROJECT_NAME}
RUNTIME DESTINATION bin
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib/static)
- 可执行程序
----main.h
#pragma once
#include <iostream>
----main.cpp
#include "main.h"
#include "../dlibs/engine.h"
int main( int argc, char* args[] ) {
Engine a;
a.Function();
return 0;
}
----CMakeLists.txt
# Project
# --------------
project(exe)
set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib")
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
# Headers and Sources
# --------------
set(${PROJECT_NAME}_headers "")
set(${PROJECT_NAME}_sources main.cpp)
# Create Binaries
# --------------
add_executable (${PROJECT_NAME} ${${PROJECT_NAME}_headers} ${${PROJECT_NAME}_sources})
# Linker
# --------------
target_link_libraries(${PROJECT_NAME} engine)
# Target
# --------------
install(TARGETS ${PROJECT_NAME}
RUNTIME DESTINATION bin
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib/static)
这就是我运行它的方法:
mkdir build
cd build
cmake ..
make install
../cmakefun/bin/exe
我得到的错误:
dyld: Library not loaded: @rpath/libengine.dylib
Referenced from: *absolute path*/cmakefun/bin/exe
Reason: image not found
Trace/BPT trap: 5
但是,构建文件夹中生成的文件有效。据我所知,如果我使用“make install”,我需要设置相对 RPath,并且我已经尝试过:
set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib")
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
在 CMakteLists.txt(exe 文件夹)内,但结果相同。
我尝试了其他几种设置 RPath 的方法,但无济于事。
任何帮助是极大的赞赏。
此致