redundant includes in c/c++
From time to time, when i remove redundant #include statements from our project, i wonder - is there an automatic tool to do this?
As a first step it’d be nice to have a tool which removes really redundant #includes - those which will not interfere with project build. As a second step - it’d be really nice to have suggestions to use forward declarations where possible instead of #includes.
For a small project the problem can be solved manually, but for a large one, with several build targets… well - automation is a must.
Any suggestions on such a tool?
Technorati Tags: c++, #include, programming


I believe it’s hard to automate this. The human “algorithm” for doing this is:
1. Replace #include with forward declaration
2. Build and see if everything is OK.
Naturally, the compiler can’t help yo with the forward declarations because it doesn’t even see them. It sees the end product of the pre-processor’s work, which is one big file with the #includes already inside.
So that leaves you with two options for a tool:
1. A tool that understands C++, recognizes what’s used by reference in the including header file and which #include it originated from and then try to replace. I think this is very hard, if only for the reason that parsing C++ syntax is hard as it is.
Also - if you use something like a pre-compiled header (or a “common-includes” header) then the tool will probably think all the #includes there aren’t needed.
2. A tool that follows the “human algorithm” mentioned above. A tool like that will have to work for a long time, because when you make a header file change (any change) many other files will need to be rebuilt because they may have an implicit dependency on that specific #include you just removed.
So maybe just a tool that recommends you what it thinks can be removed will be good enough. However, for that you need a tool that understands C++ syntax pretty well.
Comment by Amit — April 16, 2007 @ 08:54
First step should be relatively easy with brute force, and, if applied on source files (not headers) should even run fast enough.
Second step is difficult, i fully agree with you. Maybe g++ developers have easier way of doing it.
Optimizing include tree is a totally different and even harder story
Comment by linux4all — April 16, 2007 @ 09:27