362

I often find that the headers section of a file gets larger and larger all the time, but it never gets smaller. Throughout the life of a source file, classes may have moved and been refactored and it's very possible that there are quite a few #includes that don't need to be there and anymore. Leaving them there only prolong the compile time and adds unnecessary compilation dependencies. Trying to figure out which are still needed can be quite tedious.

Is there some kind of tool that can detect superfluous #include directives and suggest which ones I can safely remove? Does lint do this maybe?

2

19 Answers 19

201

Google's cppclean (links to: download, documentation) can find several categories of C++ problems, and it can now find superfluous #includes.

There's also a Clang-based tool, include-what-you-use, that can do this. include-what-you-use can even suggest forward declarations (so you don't have to #include so much) and optionally clean up your #includes for you.

Current versions of Eclipse CDT also have this functionality built in: going under the Source menu and clicking Organize Includes will alphabetize your #include's, add any headers that Eclipse thinks you're using without directly including them, and comments out any headers that it doesn't think you need. This feature isn't 100% reliable, however.

13
77

Also check out include-what-you-use, which solves a similar problem.

5
  • 6
    IMHO this answer needs a lot more upvotes, as once the kinks are worked out Google's IWYU tool will be the definitive tool for this task.
    – Dan Olson
    Apr 12, 2011 at 19:28
  • 7
    sudo apt-get install iwyu Oct 15, 2015 at 15:21
  • Seems great - with two cavaets 1) last update Feb 2106 2) Gogole themselves use it only for C++, not C, which the OP requested.
    – Mawg
    Sep 7, 2016 at 6:47
  • Can you explain a little bit how a user should use it ? The README isn't very clear about what contains the output of the python script.
    – user6547518
    Aug 10, 2017 at 8:45
  • I am using this, but it is not always 100% correct. Maybe 70% times it gives the correct suggestions. Feb 27, 2018 at 14:25
43

It's not automatic, but Doxygen will produce dependency diagrams for #included files. You will have to go through them visually, but they can be very useful for getting a picture of what is using what.

6
  • 5
    This is a great way to see chains.. seeing A -> B -> C -> D and A -> D immediately reveals the redundancy.
    – Tom
    Mar 6, 2009 at 1:36
  • 48
    @Tom: That is a horrible Idea: For one It doesn't show if those includes are needed or not and second, the list of includes should not depend on indirect includes that may change in the future (Redundant includes are usually not such a big problem anyway, thanks to include guards and compiler magic), but on which classes / functions are actually used in the file (Your compiler shouldn't have to go through thousands of lines of template code that don't even get instantiated)
    – MikeMB
    Feb 25, 2016 at 22:39
  • @albert, can you include screenshots of this, and briefly describe where to click in the doxygen output? May 12, 2020 at 0:20
  • @GabrielStaples It is not my answer, so I don't want to add information to it. I only corrected the link (as the hosting place it referred to stopped / seized to be used).
    – albert
    May 12, 2020 at 7:42
  • @GabrielStaples (or anyone else still wanting to know this): see the INCLUDE_GRAPH option in the configuration
    – wovano
    Sep 15, 2021 at 6:24
30

The problem with detecting superfluous includes is that it can't be just a type dependency checker. A superfluous include is a file which provides nothing of value to the compilation and does not alter another item which other files depend on. There are many ways a header file can alter a compile, say by defining a constant, redefining and/or deleting a used macro, adding a namespace which alters the lookup of a name some way down the line. In order to detect items like the namespace you need much more than a preprocessor, you in fact almost need a full compiler.

Lint is more of a style checker and certainly won't have this full capability.

I think you'll find the only way to detect a superfluous include is to remove, compile and run suites.

6
  • 9
    None of this will be an issue if the include files are laid out well. If you ever need to include file A before file B, you're doing it wrong (and I've worked on projects where they did it wrong). Mar 5, 2009 at 14:50
  • 13
    @David, yes but that depends on the years of devs before you doing it correctly. I can say with great certainty that the odds of that happening favor the house, not you :(
    – JaredPar
    Mar 5, 2009 at 15:38
  • Yes, but I generally find out about that when modifying a program, and suddenly I've got a compilation error (if I'm lucky) or an obscure bug. That seems to keep the #include files honest, at least in the long run. Mar 5, 2009 at 19:10
  • I'd say the exact contrary. All you need is a type dependency checker. It might not compile after you've arranged includes accordingly, but these are problems that should be dealt with anyway.
    – Benoît
    Mar 5, 2009 at 20:30
  • 2
    @Benoit, then you would be ignoring a class of issues that compile but semantically change the meaning of your program. Consider how a #define in one file can alter a #if branch in another. Removing a header can still allow this to compile with different results
    – JaredPar
    Mar 5, 2009 at 20:45
14

I thought that PCLint would do this, but it has been a few years since I've looked at it. You might check it out.

I looked at this blog and the author talked a bit about configuring PCLint to find unused includes. It might be worth a look.

2
  • 5
    I use PCLint regularly and it does tell me of unused headers. I'm careful to comment out the header #include and re-compile to be sure that the header is truly unused... Mar 5, 2009 at 17:23
  • 12
    too expensive. not a viable tool for the masses.
    – Matthieu N.
    Jan 2, 2011 at 7:08
7

The CScout refactoring browser can detect superfluous include directives in C (unfortunately not C++) code. You can find a description of how it works in this journal article.

6

Sorry to (re-)post here, people often don't expand comments.

Check my comment to crashmstr, FlexeLint / PC-Lint will do this for you. Informational message 766. Section 11.8.1 of my manual (version 8.0) discusses this.

Also, and this is important, keep iterating until the message goes away. In other words, after removing unused headers, re-run lint, more header files might have become "unneeded" once you remove some unneeded headers. (That might sound silly, read it slowly & parse it, it makes sense.)

1
  • I know exactly what you mean, and my reaction was "Ewwww". I hate code like that. Mar 5, 2009 at 19:12
5

I've never found a full-fledged tool that accomplishes what you're asking. The closest thing I've used is IncludeManager, which graphs your header inclusion tree so you can visually spot things like headers included in only one file and circular header inclusions.

4

If you are using Eclipse CDT you can try http://includator.com which is free for beta testers (at the time of this writing) and automatically removes superfluous #includes or adds missing ones. For those users who have FlexeLint or PC-Lint and are using Elicpse CDT, http://linticator.com might be an option (also free for beta test). While it uses Lint's analysis, it provides quick-fixes for automatically remove the superfluous #include statements.

3
  • The reason for that is that our bookkeeping department is not able to invoice lesser amounts. If you count the time you might save it is not that unreasonable. Once, we've got the ability to get credit card payments we can lower the price significantly. Another option would be a sponsor for our development efforts. Our financing model requires us to gain profits to finance our research work. I would be happy to sell licenses much cheaper, but can't. May be we will contribute it to CDT and you get it for free, but that I have to finance somehow. I forgot, you can try for free!
    – PeterSom
    Dec 11, 2013 at 8:02
  • Re "free for beta testers": Is that still relevant (not a rhetorical question)? Nov 21, 2023 at 19:21
  • OK, the OP has left the building: "Last seen more than 1 year ago" Nov 21, 2023 at 20:52
4

You can write a quick script that erases a single #include directive, compiles the projects, and logs the name in the #include and the file it was removed from in the case that no compilation errors occurred.

Let it run during the night, and the next day you will have a 100% correct list of include files you can remove.

Sometimes brute-force just works :-)


And sometimes it doesn't :-). Here's a bit of information from the comments:

  1. Sometimes you can remove two header files separately, but not both together. A solution is to remove the header files during the run and not bring them back. This will find a list of files you can safely remove, although there might a solution with more files to remove which this algorithm won't find. (it's a greedy search over the space of include files to remove. It will only find a local maximum)
  2. There may be subtle changes in behavior if you have some macros redefined differently depending on some #ifdefs. I think these are very rare cases, and the Unit Tests which are part of the build should catch these changes.
7
  • 2
    Be careful of this - say there are two header files which both include a definition of something. You can remove either, but not both. You'll need to be a bit more thorough in your brute force approach. Mar 5, 2009 at 14:21
  • 1
    Maybe this is what you meant, but a script that removes a single include, and leaves the last removed include out if it was successfully removed would do the trick. Mar 5, 2009 at 14:21
  • 3
    Bad idea. If a header file #defines a constant BLAH and another header file checks #ifdef BLAH, removing the first header file may still successfully compile but your behaviour has changed. Mar 5, 2009 at 14:31
  • 2
    This also can cause problems with system headers, since different implementations might have different things included in #include <vector>. Even if you stick to one compiler, the headers could change over different versions. Mar 5, 2009 at 14:52
  • 2
    This won't find cases where you're including a header that includes the header that you really need.
    – bk1e
    Mar 5, 2009 at 15:44
4

I've tried using FlexeLint (the Unix version of PC-Lint) and had somewhat mixed results. This is likely because I'm working on a very large and knotty code base. I recommend carefully examining each file that is reported as unused.

The main worry is false positives. Multiple includes of the same header are reported as an unneeded header. This is bad since FlexeLint does not tell you what line the header is included on or where it was included before.

One of the ways automated tools can get this wrong:

In A.hpp:

class A {
  // ...
};

In B.hpp:

#include "A.hpp

class B {
    public:
        A foo;
};

In C.cpp:

#include "C.hpp"

#include "B.hpp"  // <-- Unneeded, but lint reports it as needed
#include "A.hpp"  // <-- Needed, but lint reports it as unneeded

If you blindly follow the messages from Flexelint you'll muck up your #include dependencies. There are more pathological cases, but basically you're going to need to inspect the headers yourself for best results.

I highly recommend this article on Physical Structure and C++ from the blog Games from within. They recommend a comprehensive approach to cleaning up the #include mess:

Guidelines

Here’s a distilled set of guidelines from Lakos’ book that minimize the number of physical dependencies between files. I’ve been using them for years and I’ve always been really happy with the results.

  1. Every cpp file includes its own header file first. [snip]
  2. A header file must include all the header files necessary to parse it. [snip]
  3. A header file should have the bare minimum number of header files necessary to parse it. [snip]
1
  • Lakos's book is great for education -- aside from his outdated observations on compiler technology.
    – Tom
    Mar 6, 2009 at 1:38
2

This article explains a technique of #include removing by using the parsing of Doxygen. That's just a perl script, so it's quite easy to use.

1
  • 1
    The script finds some includes to remove but it gives also a lots of includes that cannot be removed. It seems that it doesn't support class enum, seems also that it has a bad time with macro and sometimes with namespace. Oct 30, 2012 at 2:53
2

CLion, the C/C++ IDE from JetBrains, detects redundant includes out-of-the-box. These are grayed-out in the editor, but there are also functions to optimise includes in the current file or whole project.

I've found that you pay for this functionality though; CLion takes a while to scan and analyse your project when first loaded.

1
  • No longer available in new clion :( Only showing as grayed-out that this include isn't used but there is no "action" to cleanup
    – Gelldur
    Sep 16, 2023 at 10:17
2

Here is a simple brute force way of identifying superfluous header includes. It's not perfect but eliminates the "obvious" unnecessary includes. Getting rid of these goes a long way in cleaning up the code.

The scripts can be accessed directly on GitHub.

1

clangd is doing that for you now. Possibly clang-tidy will soon be able to do that as well.

1

There is a free tool, Include File Dependencies Watcher, which can be integrated into Visual Studio. It shows superfluous #includes in red.

0
1

There are two types of superfluous #include files:

  1. A header file is actually not needed by the module (.c, .cpp) at all
  2. A header file is needed by the module, but it is being included more than once, directly, or indirectly.

There are two ways in my experience that works well for detecting it:

  1. gcc -H or cl.exe /showincludes (resolve problem 2)

    In the real world, you can export CFLAGS=-H before make, if all the Makefiles do not override CFLAGS options. Or as I used it, you can create a cc/g++ wrapper to add -H options forcibly to each invoke of $(CC) and $(CXX). And prepend the wrapper's directory to the $PATH variable. Then your make will all use your wrapper command instead. Of course, your wrapper should invoke the real GCC compiler. This tricks need to change if your Makefile uses GCC directly. Instead of $(CC) or $(CXX) or by implied rules.

    You can also compile a single file by tweaking the command line. But if you want to clean headers for the whole project. You can capture all the output by:

    make clean
    
    make 2>&1 | tee result.txt
    
  2. PC-Lint/FlexeLint (resolve problem, both 1 and 2)

    Make sure to add the +e766 options. This warning is about:

    unused header files.

    pclint/flint  -vf   ...
    

    This will cause the pclint output to include header files, and nested header files will be indented appropriately.

1
  • Is "/flint" literal? Why isn't there a space before /flint? Nov 21, 2023 at 20:44
1

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:

find-extra-includes (in webkit/branches/old/safari-3-2-branch/WebKitTools/Scripts)

(This is an old branch because trunk doesn't have the file anymore.)

-2

To end this discussion: the C++ preprocessor is Turing complete. It is a semantic property, whether an include is superfluous. Hence, it follows from Rice's theorem that it is undecidable whether an include is superfluous or not. There can’t be a program that (always correctly) detects whether an include is superfluous.

17
  • 8
    Did I ask for an "always correct" solution? This answer is not very productive for the discussion.
    – shoosh
    Apr 7, 2014 at 20:03
  • 1
    Well there have been numerous posts discussing problems that such a program would have to deal with. My post gives a conclusive and correct answer to that part of the discussion. And I for one would not like it, if a program told me, I could safely remove an #include and then my code doesn't compile anymore. (or worse - still compiles but does something differently). ANY such program bears this risk.
    – Algoman
    Apr 8, 2014 at 8:29
  • 4
    Between all the SPECULATION about how hard that would be and how you MIGHT solve one obstacle or another, I gave you the only 100% correct answer. I find it quite impudent to say that this wasn't productive...
    – Algoman
    Apr 9, 2014 at 8:50
  • 1
    I remembered that Rice's theorem states "There can't be a program which always can check if a given program solve this superfluous-includes problem". There can be a few programs which solve the superfluous-includes problem.
    – Zhe Yang
    Jan 13, 2016 at 14:20
  • 1
    personally I found @Algoman's input very helpful. makes me realize how hard this problem is.
    – bogardon
    Feb 1, 2017 at 6:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.