Detecting unused include files in C++ projects
Saturday 20th September, 2008
Sometimes the time to build or analyse your code can be a real pain. In C++, one of the things that can contribute to this is excessive header file nesting. As such, it is a good idea to take a look at your include file dependencies once in a while. Of course, one of the obvious and low risk things you can do is to remove any #include directives which aren't required.
You may not be aware that PC-lint can detect unused header files if you configure it correctly. The main PC-lint message you need to know about is 766 ("Header file not used in module"), but there are also ones for more subtle issues such as 964 ("Header file not directly used in module") and 966 ("Indirectly included header file not used in module").
All are informational, so if you have your warning level turned down to warnings or errors only (for example via -w1 or -w2) you simply won't see them. Of course, if your codebase has not been analysed before or is "noisy" turning up the warning level is likely to result in the issues you are looking for being drowned by others.
Fortunately, there is a simple way to show just the unused header file issues. All you need to do is set the warning level to 0 (which turns off everything!) and enable just the ones you are looking for - in this case only 766. In Visual Lint you can do this by defining custom analysis options -w0 +e766 on the "Command Line" options page:

When you re-analyse the code (use single file analysis, and make sure all projects are set to inherit default custom analysis option settings), the only issues shown now will be those messages you have enabled:

Although I've used Visual Lint to illustrate this, you can also do this directly from the PC-lint command line. You can also use the same approach to detect any specific issue - so if (for example) you want to detect all of the C style casts used in a C++ codebase you could use -w0 +e1924.
By the way, if you are looking at include dependencies within your code, you really should be aware of Profactor Software's IncludeManager:

Like Visual Lint, it is a Visual Studio add-in. Visual Studio 2003 and 2005 are supported, with Visual Studio 2008 support in beta. Highly recommended.
