Build Windows DllMain DLL with CMake

℡╲_俬逩灬. 提交于 2019-12-12 12:29:48

问题


I have a question similar to this one. I am trying to compile a DLL for windows similar to how Visual Studio would, except with CLion and CMake. I've tried the answer in the question, as well as the steps shown here, but I still get an error while injecting.

My dll code is very simple, a similar dll compiled in visual studio works fine:

#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;
}

Also, here's what I tried in CMakeLists.txt: sorry, there should have been a space between PROJECT_NAME and 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:


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



来源:https://stackoverflow.com/questions/47707173/build-windows-dllmain-dll-with-cmake

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!