<p>I am working on a large C++ project in Visual Studio 2008, and there are a lot of files with unnecessary <code>#include</code> directives. Sometimes the <code>#include</code>s are just artifacts and everything will compile fine with them removed, and in other cases classes could be forward declared and the #include could be moved to the <code>.cpp</code> file.  Are there any good tools for detecting both of these cases?</p>

[{'answer_id': 74491, 'author': 'Eclipse', 'author_id': 8701, 'author_profile': 'https://Stackoverflow.com/users/8701', 'pm_score': 7, 'selected': True, 'text': "<p>While it won't reveal unneeded include files, Visual studio has a setting <code>/showIncludes</code> (right click on a <code>.cpp</code> file, <code>Properties-&gt;C/C++-&gt;Advanced</code>) that will output a tree of all included files at compile time.  This can help in identifying files that shouldn't need to be included.</p>\n\n<p>You can also take a look at the pimpl idiom to let you get away with fewer header file dependencies to make it easier to see the cruft that you can remove.</p>\n"}, {'answer_id': 74539, 'author': 'Max Lybbert', 'author_id': 10593, 'author_profile': 'https://Stackoverflow.com/users/10593', 'pm_score': 3, 'selected': False, 'text': '<p>Like Timmermans, I\'m not familiar with any tools for this.  But I have known programmers who wrote a Perl (or Python) script to try commenting out each include line one at a time and then compile each file.</p>\n\n<hr>\n\n<p>It appears that now Eric Raymond <a href="http://catb.org/~esr/deheader/" rel="nofollow noreferrer">has a tool for this</a>.</p>\n\n<p>Google\'s <a href="http://google-styleguide.googlecode.com/svn/trunk/cpplint/cpplint.py" rel="nofollow noreferrer">cpplint.py</a> has an "include what you use" rule (among many others), but as far as I can tell, no "include <strong>only</strong> what you use."  Even so, it can be useful.</p>\n'}, {'answer_id': 74547, 'author': 'Graeme Perrow', 'author_id': 1821, 'author_profile': 'https://Stackoverflow.com/users/1821', 'pm_score': 4, 'selected': False, 'text': '<p>I don\'t know of any such tools, and I have thought about writing one in the past, but it turns out that this is a difficult problem to solve.</p>\n\n<p>Say your source file includes a.h and b.h; a.h contains <code>#define USE_FEATURE_X</code> and b.h uses <code>#ifdef USE_FEATURE_X</code>. If <code>#include "a.h"</code> is commented out, your file may still compile, but may not do what you expect. Detecting this <em>programatically</em> is non-trivial.</p>\n\n<p>Whatever tool does this would need to know your build environment as well. If a.h looks like:</p>\n\n<pre><code>#if defined( WINNT )\n   #define USE_FEATURE_X\n#endif\n</code></pre>\n\n<p>Then <code>USE_FEATURE_X</code> is only defined if <code>WINNT</code> is defined, so the tool would need to know what directives are generated by the compiler itself as well as which ones are specified in the compile command rather than in a header file.</p>\n'}, {'answer_id': 74859, 'author': 'Joe', 'author_id': 12567, 'author_profile': 'https://Stackoverflow.com/users/12567', 'pm_score': 5, 'selected': False, 'text': '<p><a href="http://www.gimpel.com/html/pcl.htm" rel="noreferrer" title="PC Lint">PC Lint</a> works quite well for this, and it finds all sorts of other goofy problems for you too. It has command line options that can be used to create External Tools in Visual Studio, but I\'ve found that the <a href="http://www.riverblade.co.uk/products/visual_lint/index.html" rel="noreferrer" title="Visual Lint">Visual Lint</a> addin is easier to work with. Even the free version of Visual Lint helps. But give PC-Lint a shot. Configuring it so it doesn\'t give you too many warnings takes a bit of time, but you\'ll be amazed at what it turns up. </p>\n'}, {'answer_id': 79991, 'author': 'Roger Nelson', 'author_id': 14964, 'author_profile': 'https://Stackoverflow.com/users/14964', 'pm_score': 2, 'selected': False, 'text': '<p>Adding one or both of the following #defines \nwill exclude often unnecessary header files and \nmay substantially improve\ncompile times especially if the code that is not using Windows API functions.</p>\n\n<pre><code>#define WIN32_LEAN_AND_MEAN\n#define VC_EXTRALEAN\n</code></pre>\n\n<p>See <a href="http://support.microsoft.com/kb/166474" rel="nofollow noreferrer">http://support.microsoft.com/kb/166474</a></p>\n'}, {'answer_id': 80423, 'author': 'bk1e', 'author_id': 8090, 'author_profile': 'https://Stackoverflow.com/users/8090', 'pm_score': 2, 'selected': False, 'text': '<p>If you are looking to remove unnecessary <code>#include</code> files in order to decrease build times, your time and money might be better spent parallelizing your build process using <a href="http://msdn.microsoft.com/en-us/library/bb385193.aspx" rel="nofollow noreferrer">cl.exe /MP</a>, <a href="http://www.gnu.org/software/make/manual/make.html#Parallel" rel="nofollow noreferrer">make -j</a>, <a href="http://www.xoreax.com/solutions_vs.htm" rel="nofollow noreferrer">Xoreax IncrediBuild</a>, distcc/<a href="http://en.opensuse.org/Icecream" rel="nofollow noreferrer">icecream</a>, etc.</p>\n\n<p>Of course, if you already have a parallel build process and you\'re still trying to speed it up, then by all means clean up your <code>#include</code> directives and remove those unnecessary dependencies.</p>\n'}, {'answer_id': 81402, 'author': 'MSalters', 'author_id': 15416, 'author_profile': 'https://Stackoverflow.com/users/15416', 'pm_score': 0, 'selected': False, 'text': "<p>Some of the existing answers state that it's hard. That's indeed true, because you need a full compiler to detect the cases in which a forward declaration would be appropriate. You cant parse C++ without knowing what the symbols mean; the grammar is simply too ambiguous for that. You must know whether a certain name names a class (could be forward-declared) or a variable (can't). Also, you need to be namespace-aware.</p>\n"}, {'answer_id': 82033, 'author': 'Richard Corden', 'author_id': 11698, 'author_profile': 'https://Stackoverflow.com/users/11698', 'pm_score': 5, 'selected': False, 'text': '<p>!!DISCLAIMER!! I work on a commercial static analysis tool (not PC Lint). !!DISCLAIMER!!</p>\n\n<p>There are several issues with a simple non parsing approach:</p>\n\n<p>1) Overload Sets:</p>\n\n<p>It\'s possible that an overloaded function has declarations that come from different files.  It might be that removing one header file results in a different overload being chosen rather than a compile error!  The result will be a silent change in semantics that may be very difficult to track down afterwards.</p>\n\n<p>2) Template specializations:</p>\n\n<p>Similar to the overload example, if you have partial or explicit specializations for a template you want them all to be visible when the template is used.  It might be that specializations for the primary template are in different header files.  Removing the header with the specialization will not cause a compile error, but may result in undefined behaviour if that specialization would have been selected.  (See: <a href="https://stackoverflow.com/questions/59331/visibility-of-template-specialization-of-c-function">Visibility of template specialization of C++ function</a>)</p>\n\n<p>As pointed out by \'msalters\', performing a full analysis of the code also allows for analysis of class usage.  By checking how a class is used though a specific path of files, it is possible that the definition of the class (and therefore all of its dependnecies) can be removed completely or at least moved to a level closer to the main source in the include tree.</p>\n'}, {'answer_id': 82080, 'author': 'anon6439', 'author_id': 15477, 'author_profile': 'https://Stackoverflow.com/users/15477', 'pm_score': 1, 'selected': False, 'text': '<p>If you aren\'t already, using a precompiled header to include everything that you\'re not going to change (platform headers, external SDK headers, or static already completed pieces of your project) will make a huge difference in build times.</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/library/szfdksca(VS.71).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/szfdksca(VS.71).aspx</a></p>\n\n<p>Also, although it may be too late for your project, organizing your project into sections and not lumping all local headers to one big main header is a good practice, although it takes a little extra work.</p>\n'}, {'answer_id': 85296, 'author': 'selwyn', 'author_id': 16314, 'author_profile': 'https://Stackoverflow.com/users/16314', 'pm_score': 2, 'selected': False, 'text': '<p>Start with each include file, and ensure that each include file only includes what is necessary to compile itself.  Any include files that are then missing for the C++ files, can be added to the C++ files themselves.</p>\n\n<p>For each include and source file, comment out each include file one at a time and see if it compiles.</p>\n\n<p>It is also a good idea to sort the include files alphabetically, and where this is not possible, add a comment.</p>\n'}, {'answer_id': 109890, 'author': 'Sam', 'author_id': 19791, 'author_profile': 'https://Stackoverflow.com/users/19791', 'pm_score': 2, 'selected': False, 'text': '<p>If your header files generally start with</p>\n\n<pre><code>#ifndef __SOMEHEADER_H__\n#define __SOMEHEADER_H__\n// header contents\n#endif\n</code></pre>\n\n<p>(as opposed to using #pragma once) you could change that to:</p>\n\n<pre><code>#ifndef __SOMEHEADER_H__\n#define __SOMEHEADER_H__\n// header contents\n#else \n#pragma message("Someheader.h superfluously included")\n#endif\n</code></pre>\n\n<p>And since the compiler outputs the name of the cpp file being compiled, that would let you know at least which cpp file is causing the header to be brought in multiple times.</p>\n'}, {'answer_id': 144427, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>PC-Lint can indeed do this. One easy way to do this is to configure it to detect just unused include files and ignore all other issues. This is pretty straightforward - to enable just message 766 ("Header file not used in module"), just include the options -w0 +e766 on the command line.</p>\n\n<p>The same approach can also be used with related messages such as 964 ("Header file not directly used in module") and 966 ("Indirectly included header file not used in module").</p>\n\n<p>FWIW I wrote about this in more detail in a blog post last week at <a href="http://www.riverblade.co.uk/blog.php?archive=2008_09_01_archive.xml#3575027665614976318" rel="nofollow noreferrer">http://www.riverblade.co.uk/blog.php?archive=2008_09_01_archive.xml#3575027665614976318</a>.</p>\n'}, {'answer_id': 273669, 'author': 'Adrian', 'author_id': 23624, 'author_profile': 'https://Stackoverflow.com/users/23624', 'pm_score': 2, 'selected': False, 'text': '<p>If you\'re interested in this topic in general, you might want to check out Lakos\' <a href="https://rads.stackoverflow.com/amzn/click/com/0201633620" rel="noreferrer" rel="nofollow noreferrer" title="Large-Scale C++ Software Design">Large Scale C++ Software Design</a>.  It\'s a bit dated, but goes into lots of "physical design" issues like finding the absolute minimum of headers that need to be included.  I haven\'t really seen this sort of thing discussed anywhere else.</p>\n'}, {'answer_id': 1047706, 'author': 'Alex', 'author_id': 129233, 'author_profile': 'https://Stackoverflow.com/users/129233', 'pm_score': 2, 'selected': False, 'text': '<p>Give <a href="http://www.profactor.co.uk/includemanager.php" rel="nofollow noreferrer">Include Manager</a> a try. It integrates easily in Visual Studio and visualizes your include paths which helps you to find unnecessary stuff.\nInternally it uses Graphviz but there are many more cool features. And although it is a commercial product it has a very low price.</p>\n'}, {'answer_id': 2543781, 'author': 'Vladimir', 'author_id': 304903, 'author_profile': 'https://Stackoverflow.com/users/304903', 'pm_score': 2, 'selected': False, 'text': '<p>You can build an include graph using <a href="http://www.mobile-mir.com/cpp/" rel="nofollow noreferrer">C/C++ Include File Dependencies Watcher</a>, and find unneeded includes visually.</p>\n'}, {'answer_id': 3150373, 'author': 'rubenvb', 'author_id': 256138, 'author_profile': 'https://Stackoverflow.com/users/256138', 'pm_score': 0, 'selected': False, 'text': '<p>Maybe a little late, but I once found a WebKit perl script that did just what you wanted. It\'ll need some adapting I believe (I\'m not well versed in perl), but it should do the trick:</p>\n\n<p><a href="http://trac.webkit.org/browser/branches/old/safari-3-2-branch/WebKitTools/Scripts/find-extra-includes" rel="nofollow noreferrer">http://trac.webkit.org/browser/branches/old/safari-3-2-branch/WebKitTools/Scripts/find-extra-includes</a></p>\n\n<p>(this is an old branch because trunk doesn\'t have the file anymore)</p>\n'}, {'answer_id': 5109452, 'author': 'Josh Kelley', 'author_id': 25507, 'author_profile': 'https://Stackoverflow.com/users/25507', 'pm_score': 5, 'selected': False, 'text': '<p>There\'s a new Clang-based tool, <a href="https://github.com/include-what-you-use/include-what-you-use" rel="noreferrer">include-what-you-use</a>, that aims to do this.</p>\n'}, {'answer_id': 6201332, 'author': 'PeterSom', 'author_id': 779373, 'author_profile': 'https://Stackoverflow.com/users/779373', 'pm_score': 1, 'selected': False, 'text': '<p>If you would work with Eclipse CDT you could try out <a href="http://includator.com" rel="nofollow">http://includator.com</a> to optimize your include structure. However, Includator might not know enough about VC++\'s predefined includes and setting up CDT to use VC++ with correct includes is not built into CDT yet.</p>\n'}, {'answer_id': 26853966, 'author': 'Britton Kerin', 'author_id': 3973301, 'author_profile': 'https://Stackoverflow.com/users/3973301', 'pm_score': 0, 'selected': False, 'text': "<p>If there's a particular header that you think isn't needed anymore (say\nstring.h), you can comment out that include then put this below all the\nincludes:</p>\n\n<pre><code>#ifdef _STRING_H_\n#  error string.h is included indirectly\n#endif\n</code></pre>\n\n<p>Of course your interface headers might use a different #define convention\nto record their inclusion in CPP memory.  Or no convention, in which case\nthis approach won't work.</p>\n\n<p>Then rebuild.  There are three possibilities:</p>\n\n<ul>\n<li><p>It builds ok. string.h wasn't compile-critical, and the include for it\ncan be removed.</p></li>\n<li><p>The #error trips. string.g was included indirectly somehow\nYou still don't know if string.h is required.  If it is required, you\nshould directly #include it (see below).</p></li>\n<li><p>You get some other compilation error. string.h was needed and isn't being\nincluded indirectly, so the include was correct to begin with.</p></li>\n</ul>\n\n<p>Note that depending on indirect inclusion when your .h or .c directly uses\nanother .h is almost certainly a bug: you are in effect promising that your\ncode will only require that header as long as some other header you're using\nrequires it, which probably isn't what you meant.</p>\n\n<p>The caveats mentioned in other answers about headers that modify behavior\nrather that declaring things which cause build failures apply here as well.</p>\n"}, {'answer_id': 29883562, 'author': 'Jean-Michaël Celerier', 'author_id': 1495627, 'author_profile': 'https://Stackoverflow.com/users/1495627', 'pm_score': 1, 'selected': False, 'text': '<p>The latest Jetbrains IDE, CLion, automatically shows (in gray) the includes that are not used in the current file.</p>\n\n<p>It is also possible to have the list of all the unused includes (and also functions, methods, etc...) from the IDE.</p>\n'}]
['https://Stackoverflow.com/questions/74326', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13013/']