头文件,包括最佳实践 [英] Header files and include best practice

查看:62
本文介绍了头文件,包括最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对头文件,包含语句和良好的编码风格有一个快速的问题。假设我有2个具有关联的源文件和头文件的类,然后是main()所在的最终源文件。

I have a quick question regarding header files, include statements, and good coding style. Suppose I have 2 classes with associated source and header files, and then a final source file where main() is located.

在Foo.hpp中,我有以下语句:

Within Foo.hpp I have the following statements:

#include <string>
#include <iostream>
#include <exception>

现在有了Bar.hpp我有以下语句:

Now withing Bar.hpp I have the following statements:

#include "Foo.hpp"
#include <string>

最后使用Myprogram.cpp我有以下语句:

And finally withing Myprogram.cpp I have the following statements:

#include "Bar.hpp"
#include <string>
#include <iostream>
#include <exception>

我知道Myprogram.cpp和Bar.hpp中的<>中的include语句不是必需的程序可以编译和运行,但是什么是最佳实践或正确的处理方式?有没有理由不在每个文件中明确包含必要的头文件?

I know the include statements in <> in Myprogram.cpp and Bar.hpp aren't necessary for the program to compile and function, but what is the best practice or right way of doing things? Is there any reason to not explicitly include the necessary header files in each file?

推荐答案

应该在需要它们的每个文件中包括所有必需的文件。如果 MyProgram.cpp 需要 string ,请包含它,而不要依赖包含它Bar.hpp 。不能保证从现在起的2周内 Bar.hpp 仍将包含它,然后您将遇到编译器错误。

You should include all necessary files in every file that needs them. If MyProgram.cpp needs string, include it, instead of relying on it being included by Bar.hpp. There's no guarantee 2 weeks from now Bar.hpp will still include it, and then you'll be left with compiler errors.

请注意必要,即确保您确实需要包含,当前向声明或什至完全不包含它时,都可以。

Note the necessary - i.e. make sure you actually need an include, when a forward declaration or even leaving it out completely will do.

此外,请注意,某些系统标头可能包含其他标头-除了少数例外,没有要求。因此,即使同时使用< iostream> < string> 同时包含这两者,

Also, note that some system headers might include others - apart from a few exceptions, there's no requirement. So if you need both <iostream> and <string> include both, even if you can compile only with one of them.

包含的显示顺序(系统包含与用户包含)取决于您遵循的编码标准-一致性比选择本身更重要

The order in which the includes appear (system includes vs user includes) is up to the coding standard you follow - consistency is more important than the choice itself.

这篇关于头文件,包括最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆