如何在windows/msvs上的同一cmake项目中构建可执行库和共享库
How to build executable and shared libraries in same cmake project on windows/msvs
我想做的是:
- 创建共享库并导出其API以供其他程序使用
- 在使用库的同一项目中创建一个简单的可执行文件(例如,显示如何使用库的具体示例
- 使用cmake构建,必须与Visual Studio(2010)和windows7一起使用
我试过这个代码(快速测试用例):
CMakeLists.txt
PROJECT (minimalcpp)
CMAKE_MINIMUM_REQUIRED (VERSION 2.6)
SET(LIBSAMPLE_HEADERS func_simple.h)
SET(LIBSAMPLE_SRCS func_simple.cpp)
ADD_LIBRARY (minimalcpp SHARED ${LIBSAMPLE_SRCS})
ADD_EXECUTABLE (test-pure-cpp test-pure-cpp.cpp)
TARGET_LINK_LIBRARIES (test-pure-cpp minimalcpp)
# THIS WORKS BUT IT IS NOT WHAT I WANT :
# ADD_EXECUTABLE (test-pure-cpp test-pure-cpp.cpp ${LIBSAMPLE_SRCS})
宏.h
#ifndef MACROS_H
#define MACROS_H
#if defined _WIN32 || defined __CYGWIN__
#if minimalcpp_EXPORTS
#define MINIMALCPP_API __declspec(dllexport)
#else
#define MINIMALCPP_API __declspec(dllimport)
#endif
#endif
#endif
函数_简单.h
#ifndef LIB_SAMPLE_FUNC_SIMPLE_H
#define LIB_SAMPLE_FUNC_SIMPLE_H
#include "macros.h"
namespace sample {
MINIMALCPP_API void f1(int nmax);
}
#endif // LIB_SAMPLE_FUNC_SIMPLE_H
函数_示例.cpp
#include <iostream>
#include "func_simple.h"
void sample::f1(int nmax) {
int i ;
for(i=0 ; i < nmax ; i++) {
std::cout << i << " -> " << i*i << std::endl;
}
}
测试-图片-pp.cpp
#include "func_simple.h"
int main(int argc, char *argv[]){
sample::f1(5);
return 0;
}
此代码可编译,但在执行时直接崩溃。
错误消息:
Le programme s'est terminé subitement.
... a quitté avec le code -1073741515
我是windows上C++的初学者,我做错了什么?非常感谢
参见[g-makulik]答案:
在这种情况下,此消息表示找不到dll,这就是应用程序崩溃的原因。一种解决方案是对cmake说,将dll和可执行文件放在同一目录中,例如:
SET(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
例如,这个约定在像Qt这样的库中使用。
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- CMake-按正确顺序将项目与C运行时对象文件链接
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- cmake在我的项目中所需的所有静态库都不成功
- 使外部项目可用于find_package CMake
- 在 Mac 上使用 CMAKE 将 FFTW 和 FFTWPP 链接到项目中时未定义的符号
- 将 OpenCV 与 CMAKE 中的项目一起构建为第三方库的正确方法
- CMake WxWidgets项目成功地在Linux上构建,但没有在Windows上构建
- Visual Studio 中的 CMake 项目:如何添加其他包含和库目录?
- 尝试将 boost::stacktrace 添加到 CMake 项目时出现构建错误
- 当我尝试通过 mingw 使用 CMake 和 SFML 库编译项目时出错
- 如何将我的 CMake 项目配置为运行所有单元测试?
- CMake 生成的 MSVC 项目找不到符号,即使为其相关 dll 正确生成了 lib 文件也是如此
- 智能感知不适用于Visual Studio 2017中的cmake项目
- 如何在我的项目中从 CMAKE 中的同一项目获取多个库
- 在现有的C++可执行项目CMAKE中构建Apache Arrow
- 编译/添加 cuda 代码到现有项目 (CMake)
- 将 GLEW 添加到项目 (CMake)
- SDL项目CMake构建失败
- 如何在目标项目 (cmake) 中添加不用于创建目标的文件