在 C++ 中是否有一种方法可以使某些 header 必须完全按照所示顺序排序,并且重新排序会破坏程序?
例如:
// WARNING , THE TWO HEADERS BELOW MUST BE IN THIS ORDER EXACTLY.
#include <winsock2.h>
#include <windows.h>
// END WARNING.
#include <iphlpapi.h>
#include <stdio.h>
#include <stdint.h>
#pragma comment(lib, "Ws2_32.lib")
是我现在拥有的,但我觉得 C++ 应该具有将 header 组合在一起的功能,例如:
#include_order <winsock2.h, windows.h>
#include <windows.h>
#include <winsock2.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <stdint.h>
#pragma comment(lib, "Ws2_32.lib")
这样,无论以后人们如何重新排列你的代码,只要强制执行在先,代码就不会被破坏。
这足以为它编写一个预处理器,但我想知道我是否可以在不编写自己的情况下做到这一点。
完整代码:
// WARNING , THE TWO HEADERS BELOW MUST BE IN THIS ORDER EXACTLY.
#include <winsock2.h>
#include <windows.h>
// END WARNING.
#include <iphlpapi.h>
#include <stdio.h>
#include <stdint.h>
#pragma comment(lib, "Ws2_32.lib")
int main()
{
return 0;
}
处理该问题的标准方法:(WIN32_LEAN_AND_MEAN 确实用词不当)
/* this definition must precede any includes. */
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <windows.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <stdint.h>
#pragma comment(lib, "Ws2_32.lib")
int main()
{
return 0;
}
最佳答案
如果您使用的是 visual studio,解决这个问题的 future 证明方法是:
Properties => C/C++ => Preprocessor => Definitions => WIN32_LEAN_AND_MEAN
它将为您的整个项目全局定义 WIN32_LEAN_AND_MEAN
。如果您不使用 visual studio,请在您的 IDE 中找到可以让您执行相同操作的设置。
您还可以通过使用预编译 header header 来解决此问题。如果您在那里定义 WIN32_LEAN_AND_MEAN
,那么您是安全的,因为在预编译 header 之前不能包含任何 header 。
如果有人修改了预编译头并想知道为什么整个项目不再编译,那么我很确定他们会知道去哪里找。此外,您还可以在此处添加重要的评论。
关于C++ 依赖头排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36521614/