需要一个头文件,在windows.h中取消所有定义

def*_*ube 9 c++ windows winapi

为了整洁,我想要#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).
Run Code Online (Sandbox Code Playgroud)

Har*_*ton 4

与其取消一切定义,不如从一开始就避免定义它们。您可以通过将模块的第一部分(作为单独的源文件)显式传递给预处理器并将预处理器输出(而不是原始源代码)包含在模块的主源文件中来实现此目的。

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

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

#include "xyzzy.h"
Run Code Online (Sandbox Code Playgroud)

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

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

os_stuff::DWORD myFunction(os_stuff::HANDLE h);
Run Code Online (Sandbox Code Playgroud)

这是 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

cl /P headers.cpp /Fiheaders.h
Run Code Online (Sandbox Code Playgroud)

/P 选项记录在此处

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

cl test.cpp
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • @CareyGregory:它满足了OP的要求。这是否明智完全是另一个问题!我认为在极少数情况下,如果大部分代码不是特定于操作系统的,但需要一些粘合,并且 Windows SDK 宏实际上与现有代码发生冲突,则可能会出现这种情况。(不可否认,不太可能,除非最初的程序员非常喜欢前导下划线。) (3认同)
  • 向我展示一个不平凡的 Windows 应用程序(无论是 GUI 还是控制台),它使用这种方案并且并非完全不可理解和不可维护。 (2认同)