How to Remove Unused Headers
2024-01-31 #cpp, #include what you use, 273 Words 1 Min

Navigating a large legacy code base with inadequate documentation can be a daunting task. Learning from existing code becomes a pivotal strategy for acclimatization and implementation. However, inadvertent copying and pasting likely includes unnecessary header files, compounding the challenge of discerning which ones are truly essential.

include what you use (IWYU) is a powerful tool designed to detect and highlight unused headers, unraveling the complexities of code dependencies. Here's a step-by-step guide how to use it to detect unused headers:

  1. While the official README provides detailed instructions for building from source, Mac users can opt for a simpler approach. Leveraging Homebrew, execute the straightforward command: brew install include-what-you-use.

  2. Configure your Makefile to capture build commands, an essential step in the IWYU process. For CMake users, this involves adding the following line during configuration: CC="clang" CXX="clang++" cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON .... For those using in-house build scripts, incorporate the flag -gen-cdb-fragment-path to the OTHER_CFLAGS section. This flag generates build command fragments that need consolidation into a single JSON file.

  3. Perform a clean build of your project to trigger the generation of build command fragments. Once completed, use the following command to merge these fragments into a unified JSON file: sed -e '1s/^/[\'$'\n''/' -e '$s/,$/\'$'\n'']/' *.json > compile_commands.json.

  4. With the consolidated JSON file in hand, run the IWYU tool to analyze your project. Execute the following command within the designated folder: iwyu_tool.py -p ..

While IWYU is a robust tool, it's crucial to note the possibility of false positives. Exercise discernment when interpreting the generated reports, and be mindful of any unexpected results.

Another method, as suggested by colleagues, is the include cleaner tool. If you're working in Visual Studio Code, enable this tool through the clangd extension to receive warnings about unused headers.

Leave a Comment on Github