I've read everything I could find on this topic, including a couple of very helpful discussions on this site, the NASA coding guidelines and Google C++ guidelines. I even bought the "physical C++ design" book recommended on here (sorry, forgot the name) and got some useful ideas from that. Most sources seem to agree - header files should be self-contained, i.e. they include what they need so that a cpp file could include the header without including any others and it would compile. I also get the point about forward declaring rather than including whenever possible.
That said, how about if foo.cpp
includes bar.h
and qux.h
, but it turns out that bar.h
itself includes qux.h
? Should foo.cpp
then avoid including qux.h
? Pro: cleans up foo.cpp
(less "noise"). Con: if someone changes bar.h to no longer include qux.h
, foo.cpp
mysteriously starts failing to compile. Also causes the dependency between foo.cpp
and qux.h
not to be obvious.
If your answer is "a cpp file should #include every header it needs", taken to its logical conclusion that would mean that pretty much every cpp file has to #include <string>, <cstddef>
etc. since most code will end up using those, and if you're not supposed to rely on some other header including them, your cpp needs to include them explicitly. That seems like a lot of "noise" in the cpp files.
Thoughts?
Previous discussions:
http://stackoverflow.com/questions/181921/your-preferred-cc-header-policy-for-big-projects
http://stackoverflow.com/questions/51561/how-do-i-automate-finding-unused-include-directives
ETA: Inspired by previous discussions on here, I've written a Perl script to successively comment out each 'include' and 'using', then attempt to recompile the source file, to figure out what's not needed. I've also figured out how to integrate it with VS 2005, so you can double-click to go to "unused" includes. If anyone wants it let me know...very much experimental right now though.