如何在windows/msvs上的同一cmake项目中构建可执行库和共享库

How to build executable and shared libraries in same cmake project on windows/msvs

本文关键字:项目 cmake 构建 可执行 共享 windows msvs      更新时间:2023-10-16

我想做的是:

  • 创建共享库并导出其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这样的库中使用。