c++includegoogle-style-guide

Google C++ Style Guide include order


Google C++ Style Guide recommends to include the header files (.h) to the implementation files (.cpp, .cc) in the following order:

In dir/foo.cc or dir/foo_test.cc, whose main purpose is to implement or test the stuff in dir2/foo2.h, order your includes as follows:

dir2/foo2.h.
A blank line
C system files.
C++ system files.
A blank line
Other libraries' .h files.
Your project's .h files.

As said such order allows to see the omitted dependencies in dir2/foo2.h while compiling the foo-unit, rather than other innocent units. Seems quite logically.

But why Other libraries' .h files. and Your project's .h files. placed to the end of the list? In theory there also could be missing dependencies which will be hidden by including the C system files. and C++ system files. before.

Maybe there is assumed that other (header) files problems should be detected in related implementation files? What about header-only libraries in that case?

In other words, would the following order of includes:

dir2/foo2.h.
A blank line
Other libraries' .h files.
Your project's .h files.
A blank line
C system files.
C++ system files.

will be better to more fast finding hidden dependencies?

For instance, if I have only header that requires <stdio.h> (but not specified in that file). Using the Google order the probabily of direct or indirect include of <stdio.h> is higher, than when the system files are included on the last step (as I suggested before). Hence, low probability to find hidden dependency. So what we will win if include the system files before other lib/your project files?

Also it's not clear, should I use recommended order of include files in other (user defined) header files.


Solution

  • Every header file(h, hpp,...) should have an implementation file (cpp, cc,...) where the order of including is the same as specified in the question. (Even if the implentation file is empty, except for this 1 include)

    So just like "Your" header is included first in "Your" implementation file, so every "other" header file should be included first in the "other" implementation file.

    This way if the "other" header does not include a required header, the "other" implementation file will not compile.

    enter link description here