.c 文件是否应该包含 .h 文件已经包含的内容?

Should a .c file include something that it's .h file already includes?

这是来自 Google's C++ style guide 的关于 #include 的部分:

If you rely on symbols from bar.h, don't count on the fact that you included foo.h which (currently) includes bar.h: include bar.h yourself, unless foo.h explicitly demonstrates its intent to provide you the symbols of bar.h.

However, any includes present in the related header do not need to be included again in the related cc (i.e., foo.cc can rely on foo.h's includes).

当我读到这里时,这些句子似乎相互矛盾。他们对我说:

  1. 如果 foo.cc 需要 bar.h 中的内容,它必须包括 bar.h
  2. 如果 foo.cc 需要 bar.h 中的内容,并且 foo.cc 包含 foo.h,并且 foo.h 包含 bar.h,那么 foo.cc不需要包含bar.h.

为什么这些句子不矛盾?

第二段讲的是一个特例:.cc文件实现了相应.h文件中声明的函数。由于 .cc.h 文件旨在密切相关并串联维护(通常由同一程序员),因此 .cc 文件可能取决于其相关头文件中的内容。

第一段说的是包含头文件的其他文件。

因此 foo.cc 可以依赖于 foo.h 中的包含,但是 bar.cc 应该同时包含 foo.hbaz.h