How do you maintain the #include statements in your C or C++ project? It seems almost inevitable that eventually the set of include statements in a file is either insufficient (but happens to work because of the current state of the project) or includes stuff that is no longer needed.
Have you created any tools to spot or rectify problems? Any suggestions?
I've been thinking about writing something that compiles each non-header file individually many times, each time removing an #include statement. Continue doing this until a minimal set of includes is achieved.
To verify that header files are including everything they need, I would create a source file that all it does is include a header file and try to compile it. If the compile fails, then the header file itself is missing an include.
Before I create something though, I thought I should ask here. This seems like a somewhat universal problem.
If you are coding in Eclipse with CDT, you can use Organize Includes command. Just hit Ctrl+Shift+O and it will add the necessary includes and remove the unneeded ones.
Yup. We have a preprocessor of our own which gives us access to our own macro language. It also checks that header files are only included one time. Creating a simple preprocessor checking for multiple includes should be fairly easy.
Take a look at the cppclean project. Though they haven't implemented that feature yet, but it's planned to be done.
From the project site:
And particularly on the #include feature:
Here you can find a mirror at BitBucket.
Detecting superfluous includes has already been discussed in this question.
I'm not aware of any tools to help detect insufficient-but-happens-to-work includes, but good coding conventions can help here. For example, the Google C++ Style Guide mandates the following, with the goal of reducing hidden dependencies:
In
dir/foo.cc
, whose main purpose is to implement or test the stuff indir2/foo2.h
, order your includes as follows:dir2/foo2.h
(preferred location — see details below).As far as tools go, I've used Imagix (this was about 6 years ago) on windows to identify includes that are unneeded as well as includes which are needed but are indirectly included thru another include.
If you use Visual Studio compiler, you can try /showIncludes compiler option and then parse what it emits to stderr. MSDN: "Causes the compiler to output a list of the include files. Nested include files are also displayed (files that are included from the files that you include)."