头文件顺序

可能重复:
C ++标题顺序

// Here is module This.cpp #include <boost/regex.hpp> #include <iostream> #include <math.h> #include "mystring_written_by_c.h" #include "mystring_written_by_cpp.h" #include <list> #include <string> #include <stdio.h> #include "stdafx.h" // for precomp #include <tchar.h> #include "This.h" #include <Windows.h> #include <Winsock2.h> 

他们现在按字母顺序排列。
我正在find订购它们的最佳做法。 (有一个很好的公式?)

你将如何订购这些头文件? 为什么?

应该尽可能地写入标题1)独立于已经包含的内容,2)不为后面包括的标题引入问题(例如用于公共标识符的宏)。 当这两个都是真实的,你包括的顺序并不重要。 如果不是这样,你应该在你自己的头文件中解决这个问题,或者在必要的时候处理它。

因此,选择是任意的,但是你做出选择仍然是重要的! “计划是没有的,但计划就是一切。” 一致性导致更可读的代码。

一个相对常见的顺序是标准库,系统(如OS),外部库,然后是与当前文件相同的项目的头文件 – 除了包含其“对应”头文件(如果有的话)首先,在任何包含或其他代码之前。 在每个组中,我按照习惯按字母顺序排序,因为再一次,它完全是任意的,但一些易于使用的顺序让我快速阅读和更新列表。

适用于你的清单:

 // first only because this is required in your precompiled header setup #include "stdafx.h" // it's too bad this can't really be first // I'm guessing "This" refers to the corresponding header #include "This.h" // C stdlib then C++ stdlib is what I usually do, // whether the C headers are spelled XXX.h or cXXX. #include <math.h> #include <stdio.h> #include <iostream> #include <list> #include <string> // someone mentioned winsock2 needs to be before windows #include <Winsock2.h> #include <tchar.h> #include <Windows.h> #include <boost/regex.hpp> #include "mystring_written_by_c.h" #include "mystring_written_by_cpp.h" 

上面的分行分组是故意的。 我会留下评论,为什么winsock2是自己的组,但其余的意见通常不会在那里。

把你的头文件放在什么顺序上并不重要。 这主要是一个选择的问题。 很多人把系统头文件(<>之间的头文件)和后面的私有头文件放在一起,但这取决于你。

这是高度依赖于你如何需要他们包括在内。 如果没有一个依赖于另一个,你可以相对自由的使用你自己的方案(一般来说,如果需要的话,最重要的头文件将被隐含地包括在内)。

但请注意,WinSock2.h必须包含在Windows.h之前,否则很有可能在编译时出现链接器错误。

祝你好运!
丹尼斯

标准库,然后系统标题不在标准库,然后私人标题。 用空行分隔每个类别。 评论任何需要解释的东西。

如果你有依赖关系,在依赖它们的头文件之前加入头文件依赖的头文件(doi!)。