IWYU: include only necessary headers

hacker_compIWYU (include-what-you-use) is a built-in utility for clang to remove unnecessary #include directives in your programs. What it might not seem like a problem in small projects, larger projects tend to have increasing number of header inclusions with time.

Benefits

  • faster compilation time
  • fewer recompiles
  • easy refactoring
  • self-documentation
  • dependency removals
  • suggests forward-declares where possible

Build

IWYU uses clang internals heavily and comes with Clang cource. You can build the tool either out-of-tree or in-tree. We will explore the out-of-tree procedure on Ubuntu.

Out-of-tree

Run the following commands:

$ sudo apt-get install libclang-dev cmake
$ mkdir iwyu-trunk
$ git clone https://github.com/include-what-you-use/include-what-you-use.git
$ cd include-what-you-use
$ git checkout clang_version
$ cd ..
$ mkdir build && cd build
$ cmake -G "Unix Makefiles" -DLLVM_PATH=/usr/lib/llvm-version ../include-what-you-use
$ make

Replace version with your version of libclang-dev, e.g. 3.4.

Usage

Add Clang’s built-in headers to a location where IWYU can find it. By default it searches in path/to/iwyu/../lib/clang/version/include. The Clang internal headers are installed in /usr/lib/clang/version/include.

IWYU can be used as an option to make, e.g.:

$ make -k CXX=/path/to/include-what-you-use

The fix_includes.py utility (from IWYU git repo) can fix include issues automatially.

$ make -k CXX=/path/to/include-what-you-use > /tmp/iwyu.out
$ python fix_includes.py < /tmp/iwyu.out

More help on fix_includes.py:

$ python fix_includes.py --help

Webpage: IWYU

Comment

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