Cppcoreguidelines: new SF guideline, "header files should include the other headers they depend on"

Created on 16 Mar 2018  路  9Comments  路  Source: isocpp/CppCoreGuidelines

This seems obvious, but I've found myself in this discussion a few times, recently in the context of the Windows SDK header files that have a history of getting this wrong. (wincon.h being a case were we fixed a circular dependency and then violated this guideline in the process).

Should there be a guideline that .h files should include all of the headers that contain the types they depend on (and no more)?

Most helpful comment

Oh I see, so "don't assume foo.h has been included before bar.h, make bar.h self-sufficient". Yes, that annoys me, and is one of the things I'm surprised even needs to be explained to people (but experience suggests it does).

A sensible application of the same rule works for both cases: Include the necessary headers for everything your file (header or source file) uses. I think it could be added to SF.10, or as a new SF.11 following it.

All 9 comments

I think this is covered by https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rs-implicit (although not the "and no more" part).

That appears to be about consumers of header files not depending on what those files include to facilitate their implementation. I'm interested in describing what header file authors should do.

Oh I see, so "don't assume foo.h has been included before bar.h, make bar.h self-sufficient". Yes, that annoys me, and is one of the things I'm surprised even needs to be explained to people (but experience suggests it does).

A sensible application of the same rule works for both cases: Include the necessary headers for everything your file (header or source file) uses. I think it could be added to SF.10, or as a new SF.11 following it.

Does that allow for forward declarations?

If you don't use the complete type, you don't need to include the definition.

Forward declarations should be used judiciously though, trying to declare something you don't own is fragile, and for entities from the standard library it's undefined.

"Header files should be self-sufficient."

@ChrisGuzak, this is a great suggestion! We'd love for you to provide a PR with your suggested guidance. This rule should probably be SF.11. Thank you!

See PR #1181

Thank you!

Was this page helpful?
0 / 5 - 0 ratings