让CMake为MSVC构建共享库

时间:2016-05-10 02:59:57

标签: visual-c++ cmake

我一直在使用CMake在unix环境中构建C和C ++项目。但是,我也希望在MSVC中开始编译,我试图了解cmake文档,但是我遇到了问题。 我在尝试构建时不断收到以下消息。

  

LINK:致命错误LNK1104:无法打开文件' Debug \ MyLibrary.lib' [C:\沙盘\项目\ CPP \ DummyChelloWorld \编译\马   inProgram.vcxproj]

你能告诉我我做错了什么吗?

的CMakeLists.txt

    cmake_minimum_required(VERSION 3.4)
    project(helloWorld)

    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
    include(GenerateExportHeader)

    ADD_LIBRARY(MyLibrary SHARED myShared.cpp)

    set(SOURCE_FILES main.cpp)

    GENERATE_EXPORT_HEADER( MyLibrary
                 BASE_NAME MyLibrary
                 EXPORT_MACRO_NAME MyLibrary_EXPORT
                 EXPORT_FILE_NAME ${CMAKE_BINARY_DIR}/MyLibrary_Export.h
                 STATIC_DEFINE MyLibrary_BUILT_AS_STATIC
            )

    add_executable(mainProgram ${SOURCE_FILES})
    TARGET_LINK_LIBRARIES(mainProgram MyLibrary)
    TARGET_INCLUDE_DIRECTORIES(mainProgram PUBLIC exports)

的main.cpp

#include "myShared.h"

int main() {
  sayHI();
  return 0;
}

myShared.cpp

#include <iostream>
#include "myShared.h"

using namespace std;

void sayHI() {
  cout << "Hello World lib" << endl;
}

myShared.h

    #ifndef HELLOWORLD_HELLO_H
    #define HELLOWORLD_HELLO_H

    void sayHI();

    #endif //HELLOWORLD_HELLO_H

1 个答案:

答案 0 :(得分:3)

将我的评论转化为答案

适用于CMake版本&gt; = 3.4

只需使用CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS

cmake_minimum_required(VERSION 3.4)
project(helloWorld)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS 1)

add_library(MyLibrary SHARED myShared.cpp)

set(SOURCE_FILES main.cpp)
add_executable(mainProgram ${SOURCE_FILES})
TARGET_LINK_LIBRARIES(mainProgram MyLibrary)

适用于CMake版本&lt; 3.4

您需要将您的函数/符号声明为已导出。因此,在您的情况下,您必须修改以下文件:

<强> myShared.h

#ifndef HELLOWORLD_HELLO_H
#define HELLOWORLD_HELLO_H

#include "MyLibrary_Export.h"

void MyLibrary_EXPORT sayHI();

#endif //HELLOWORLD_HELLO_H

<强>的CMakeLists.txt

cmake_minimum_required(VERSION 3.4)
project(helloWorld)

set(CMAKE_CXX_STANDARD 11)
include(GenerateExportHeader)

add_library(
    MyLibrary 
    SHARED 
        myShared.cpp
        myShared.h
        MyLibrary_Export.h   
)
GENERATE_EXPORT_HEADER( 
    MyLibrary
    BASE_NAME MyLibrary
    EXPORT_MACRO_NAME MyLibrary_EXPORT
    EXPORT_FILE_NAME MyLibrary_Export.h
    STATIC_DEFINE MyLibrary_BUILT_AS_STATIC
)
target_include_directories(MyLibrary PUBLIC "${CMAKE_CURRENT_BINARY_DIR}")

set(SOURCE_FILES main.cpp)
add_executable(mainProgram ${SOURCE_FILES})
TARGET_LINK_LIBRARIES(mainProgram MyLibrary)

我已经

  1. MyLibrary_EXPORT添加到您的函数声明
  2. CMAKE_CURRENT_BINARY_DIR添加到共享库包含路径(指向生成的导出定义标题)
  3. 使用了更多跨平台的CMAKE_CXX_STANDARD定义。
  4. <强>替代

    <强>参考