使用CMake构建Windows DllMain DLL

时间:2017-12-08 03:15:52

标签: cmake clion

我有一个类似于this one的问题。我试图为Windows编译一个类似于Visual Studio的DLL,除了CLion和CMake。我已经在问题中尝试了答案,以及显示的步骤here,但在注入时仍然出错。

我的dll代码非常简单,在visual studio中编译的类似dll工作得很好:

#include <windows.h>
#include <iostream>
using namespace std;

void hello() {
    AllocConsole();
    freopen("CONOUT$", "w", stdout);
    cout << "Hello, World!" << endl;
}

bool __stdcall DllMain(HMODULE /*module*/, DWORD reason, LPVOID /*reserved*/) {
    if (reason == DLL_PROCESS_ATTACH) hello();
    return true;
}

另外,这是我在CMakeLists.txt尝试的内容:抱歉,PROJECT_NAME和MODULE之间应该有空格

cmake_minimum_required(VERSION 3.9)
project(PROJECT_NAME)
include (GenerateExportHeader)
set(CMAKE_CXX_STANDARD 17)

add_library(PROJECT_NAME MODULE main.cpp)
set_target_properties(PROJECT_NAME PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32")
GENERATE_EXPORT_HEADER(PROJECT_NAME
    BASE_NAME PROJECT_NAME
    EXPORT_MACRO_NAME PROJECT_NAME_EXPORT
    EXPORT_FILE_NAME PROJECT_NAME_Export.h
    STATIC_DEFINE PROJECT_NAME_BUILT_AS_STATIC)

1 个答案:

答案 0 :(得分:1)

You have two options:

  1. Add the BUILD_SHARED_LIBS variable to CMake's cache as a boolean value then check it. This will modify the behaviour of the add_library command to make a shared library i.e. a DLL file on Windows.
  2. Explicitly create the library as shared: add_library(PROJECT_NAMEMODULE SHARED main.cpp)

BUILD_SHARED_LIBS variable documentation: https://cmake.org/cmake/help/v3.10/variable/BUILD_SHARED_LIBS.html