Header file dependencies

A brute force method of reducing superfluous header includes in a project

Header files are just a part and parcel of the C/C++ programming language. However, the number of header file includes go out of control very quickly. In most C/C++ based projects, maintaining minimal or optimal header includes is a challenge. Sooner or later, you will find many unnecessary header includes in the source files.

This causes a few problems.

  • It multiplies the time taken to compile C++ code by the number of times it’s used in a program.1
  • For an incremental minimal build, every unnecessary include potentially increases the number of files that get recompiled.1
  • Refactoring and reorganizing code becomes difficult.

There are free tools2 to identify dependencies but reducing the superfluous dependencies is a painful manual task. Then there are some expensive heavy duty tools. This however, is a simple and free alternative, not perfect but quite effective.

It’s a brute force method which leverages the compiler to identify true dependencies. For each file, it comments out an include and builds the project. If it builds successfully, it is assumed that the header is not required. If the build fails, the include in uncommented (and built again as a sanity check). It is recommended to run it on all on the .h first and then the .cxx.

The script files can be accessed from GitHub at https://github.com/cognitivewaves/misc/tree/master/check-header-includes.

As mentioned earlier, it’s not perfect, as it does not identify changes in behavior due to the order of an “unnecessary” header. E.g.There may be subtle changes in behavior if you have some macros redefined differently depending on some #ifdefs from a previous header identified as “not required”. However, it is nice to have a tool which gets rid of the “obvious” and “silly” superfluous dependencies. So it is best to review the identified unnecessary headers before committing it.

Currently, the script works only on Windows using Visual Studio projects. But it is easy enough to replicate it on Linux and other compilers.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s