Google C++ Style Guide include order

被刻印的时光 ゝ 提交于 2019-12-11 09:09:07

问题


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.


回答1:


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.




回答2:


The C and C++ header files to include there are those used by the source code below, they should not cover dependencies of other libraries or project's header files.

And header only modules like templates: You do write a test program for your modules, right? Include the template header file first in the test program, then you can detect missing includes there too.



来源:https://stackoverflow.com/questions/54347804/google-c-style-guide-include-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!