【问题标题】:How to import windows.h as module correctly如何正确导入 windows.h 作为模块
【发布时间】:2021-03-30 11:51:30
【问题描述】:

mybar.ixx

export module mybar;

#include "windows.h"

export
double trywinapi() {
    MEMORYSTATUSEX memInfo;
    memInfo.dwLength = sizeof(MEMORYSTATUSEX);
    GlobalMemoryStatusEx(&memInfo);
    return memInfo.ullTotalPageFile;
}

main.cpp

import mybar;

#include "windows.h"

void main() {
    trywinapi();
}

而visual studio 2019编译报错:

错误 LNK2019:未解析的外部符号 __imp__GlobalMemoryStatusEx@4:: 在函数“double __cdecl trywinapi(void)”(?trywinapi@@YANXZ::)中引用

【问题讨论】:

标签: c++ module c++20


【解决方案1】:

全局模块片段位于模块名称之前:

module;
#include<windows.h>
export module mybar;
export double trywinapi() {…}

【讨论】:

  • #include 在导出模块 mybar 工作之前进行。
【解决方案2】:

通过在 C++ 模块中包含 &lt;windows.h&gt; 并为 Debug/x64 构建,我仍然发现了许多警告,处理方式如下:

忽略外部库警告

mybar.cpp

module;
#pragma warning(push, 0)
#include <windows.h>
#pragma pop(0)
export module mybar;

这仍然会输出警告:

C:\Program Files (x86)\Windows Kits\10\Include\10.0.19041.0\um\winbase.h(9531,5):警告 C5105:产生“已定义”的宏扩展具有未定义的行为

更新 Windows SDK

上面的警告显然是 regression issue,已通过将 SDK 更新为 Windows 10 SDK (10.0.20348.0), version 2104 并确保 Visual Studio 项目使用了最后一个 Windows SDK 来解决:

Project > Properties > Configuration Properties > General > Windows SDK Version

完成。

我的环境

Edition Windows 11 Home
Update 21H2
OS build 22000.51
Experience Windows Feature Experience Pack 421.16300.0.3

Microsoft Visual Studio Community 2022 Preview
Version 17.0.0 Preview 1.1
VisualStudio.17.Preview/17.0.0-pre.1.1+31423.177
Version 4.8.04161

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 2020-01-10
    • 2021-03-13
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多