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.


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


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.


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.


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

Leave a Reply

Your email address will not be published. Required fields are marked *