2

Here is a section on #include's from Google's C++ style guide:

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).

When I read this, these sentences seem to contradict. To me they say:

  1. If foo.cc needs stuff in bar.h, it must include bar.h.
  2. If foo.cc needs stuff in bar.h, and foo.cc includes foo.h, and foo.h includes bar.h, then foo.cc doesn't need to include bar.h.

Why don't these sentences contradict?

Community
  • 1
  • 1
kvu787
  • 943
  • 2
  • 10
  • 13
  • 4
    I interpret as always include the header yourself unless it is included in the header file **associated with the source file**. In other words, if the other header file has nothing to do with the source file your talking about, include it yourself. If its the header file that contains the declarations of the stuff you implement in the source file, don't include it. – eesiraed Mar 23 '18 at 03:05
  • See [Include What You Use](https://github.com/include-what-you-use/include-what-you-use). See also the Goddard Space Flight Center rules for C and C++. The C++ rules are still available on the web, but the C rules are harder to find — see [Should I use `#include` in headers](https://stackoverflow.com/questions/1804486/should-i-use-include-in-headers/1804719?s=2|32.1204#1804719) for references to the GSFC rules for C. C++ is particularly prone to problems because standard C++ headers can include others, whereas standard C restricts that — `` can include `` but that's all. – Jonathan Leffler Mar 23 '18 at 05:51
  • Why do you think Google's C++ style guide applies to C? Don't spam language tags needlessly. – Lundin Mar 23 '18 at 09:08

1 Answers1

7

The second paragraph is talking about one special case: the .cc file that implements the functions declared in the corresponding .h file. Since the .cc and .h file are intended to be closely related and maintained in tandem (often by the same programmer), the .cc file can depend on what's in its related header file.

The first paragraph is talking about other files that include the header file.

So foo.cc can depend on the includes in foo.h, but bar.cc should include both foo.h and baz.h.

Barmar
  • 741,623
  • 53
  • 500
  • 612