CMake include-what-you-use (IWYU)
Include-what-you-use
IWYU
is a static analysis tool that helps find missing and unused #include
statements in C / C++ source files.
Like any tool, IWYU makes mistakes, so make changes incrementally and be ready to rollback edits.
CMake has IWYU support that is enabled in project CMakeLists.txt by including this stanza BEFORE any targets are defined:
option(iwyu "Run include-what-you-use")
if(iwyu)
find_program(IWYU_EXE NAMES include-what-you-use REQUIRED)
set(CMAKE_C_INCLUDE_WHAT_YOU_USE ${IWYU_EXE})
set(CMAKE_CXX_INCLUDE_WHAT_YOU_USE ${IWYU_EXE})
endif()
Upon building the project, CMake will run IWYU on all source files. IWYU emits messages as each source file is built, if there are any issues. IWYU does not emit messages by default when there are no issues.
Troubleshooting
Ensure that IWYU is working by deliberately including an unused header. For example, on MSYS2 sometimes IWYU never emits messages with CMake.