我的 header 文件应该能够自行编译吗?

Should my header files be able to compile on their own?

一位同事最近声称 header 文件应该始终能够自行编译(例如调用 g++ someHeader.hpp 应该导致 someHeader.hpp.gch 而不会失败)。

这个说法是"true"吗?

检查您的 header 是否能够自行编译是一种 good/common 做法吗?

如果是,这样的测试有什么好处?

对我来说,这似乎违反直觉,因为 headers 被预处理器包含在编译单元中,并且只需要在该单元的上下文中编译。

Is it a good/common practice to check if your headers are able to compile on their own?

是的。这种做法很好,据我所知,很普遍。

If yes, what would be the advantage

A header 本身不起作用必须依赖于将要包含它的上下文。 让 header 仅在包含在特定上下文中时才起作用是很脆弱的。脆弱性是一种代码味道。

... headers are included by the preprocessor in the compilation unit and only have to compile in the context of that unit.

... 以及包含 header 的所有其他单元。包括那些还没有写的单元。当对这些单位进行更改时,它也应该继续工作。

一个 header 在一个时间点只能在一个翻译单元中工作,从长远来看并不是一个非常有用的 header。