简体   繁体   English

如何在Windows / MSVS的同一cmake项目中构建可执行文件和共享库

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

what I want to do is : 我想做的是:

  • create a shared library and export its API to be usable by other programs 创建一个共享库并导出其API以供其他程序使用
  • create a simple executable in the same project that uses the library (to show concrete example of how to use the library for example 在使用该库的同一项目中创建一个简单的可执行文件(例如,显示有关如何使用该库的具体示例
  • build it using cmake, must work with Visual Studio (2010) and windows 7 使用cmake构建它,必须与Visual Studio(2010)和Windows 7一起使用

I tried this code (quick test case) : 我尝试了这段代码(快速测试用例):

CMakeLists.txt 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})

macros.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

func_simple.h func_simple.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

func_simple.cpp func_simple.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;
  }
}

test-pure-cpp.cpp 测试纯cpp.cpp

#include "func_simple.h"

int main(int argc, char *argv[]){
    sample::f1(5);
    return 0;
}

This code compiles but crashes directly at execution. 该代码可以编译,但是直接在执行时崩溃。

Error message : 错误信息 :

Le programme s'est terminé subitement.
... a quitté avec le code -1073741515

I am a beginner in C++ on windows, what did I do wrong ? 我是Windows上C ++的初学者,我做错了什么? Thank you very much 非常感谢你

see [g-makulik] answer : 看到[g-makulik]答案:

In this case, this message means that dll is not found and that is why application crashes. 在这种情况下,此消息表示找不到dll,这就是应用程序崩溃的原因。 One solution is to say to cmake to put dll and executable in same directory, in bin for example : 一种解决方案是说cmake将dll和可执行文件放在同一目录中,例如,在bin中:

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)

This convention is used in libraries like Qt for example. 例如,该约定在Qt之类的库中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM