gpt4 book ai didi

c++ - 需要一个 undefs 所有在 windows.h 中定义的头文件

转载 作者:可可西里 更新时间:2023-11-01 12:44:06 25 4
gpt4 key购买 nike

为了整洁起见,我想#undef windows.h 中定义的所有内容。

例如:

namespace os_stuff
{
#include <windows.h>

// ARGH! Macros everywhere!

// at least I can keep the rest of the API in here
}

// include a bunch of files here that use the Windows API through os_stuff

namespace os_stuff
{
#include <unwindows.h> // <- #undefs all that was #defined in windows.h
}

// All clean, as though windows.h was never here. Though os_stuff, used nowhere else,
// still has all of the API declarations in it (which is OK).

最佳答案

与其取消对所有内容的定义,不如首先避免定义它们。您可以通过 preprocessor 显式传递模块的第一部分(作为单独的源文件)来完成此操作。并在模块的主源文件中包含预处理器输出,而不是原始源代码。

我使用 Visual Studio 2010 对此进行了试验。为了试验,我创建了三个源文件。这是 headers.cpp,类似于示例代码的第一部分:

namespace os_stuff
{
#undef _MSC_EXTENSIONS
#define _WIN32_WINNT 0x0601
#include <windows.h>
}

#include "xyzzy.h"

#undef _MSC_EXTENSIONS 是为了防止包含 sourceannotations.h,因为从命名空间内部包含该文件时会产生错误。

这是 xyzzy.h,用于演示示例代码中的“在此处包含一堆文件”:

os_stuff::DWORD myFunction(os_stuff::HANDLE h);

这是 test.cpp,类似于示例代码的“全部干净”部分:

#include "headers.h"

int main(int argc, char ** argv)
{
os_stuff::DWORD UNALIGNED;
os_stuff::HANDLE h = 0;
UNALIGNED = myFunction(h);
return UNALIGNED;
}

请注意,我们使用 UNALIGNED 作为变量名,不是因为它有意义,而是作为一个示例,如果您直接包含 windows.h 则无法正常工作(因为它扩展为 __unaligned 关键字)。

从 Visual Studio 2010 命令行创建 headers.h,如下所示:

cl /P headers.cpp /Fiheaders.h

/P 选项是 documented here .

然后您可以按照通常的方式编译test.cpp:

cl test.cpp

(显然在这种情况下程序不会链接,因为我们还没有定义 myFunction,但它编译得非常愉快。)

通过一些摆弄,自动构建 headers.h 而不是从命令行执行它应该不会太难。

在一些 C++ 编译器中,预处理器实际上是一个单独的可执行文件(这是传统模型),但如果不是,应该仍然有一个选项可以在不调用编译器的情况下运行预处理器。

关于c++ - 需要一个 undefs 所有在 windows.h 中定义的头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11487857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com