The tool include-what-you-use can be used to detect unneeded headers. I am using CMake for my C++ software project. How can I instruct CMake to run include-what-you-use auto
If you don't have access to CMake 3.3, include-what-you-use
comes with a python tool called iwyu_tool.py which can do what you want.
It works by parsing a clang compilation database, which is easily produced with CMake.
Assuming you already have a CMake build dir for your project, you first need to tell CMake to produce the compilation database:
$ cd build
$ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON .
This generates a file, compile_commands.json
containing compiler invocations for every object file in your project. You don't need to rebuild the project.
You can now run include-what-you-use
on your project by running the python tool on your build directory:
$ python /path/to/iwyu_tool.py -p .
The following snippet can be used to add an iwyu
target to a cmake project.
# Generate clang compilation database
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
find_package(PythonInterp)
find_program(iwyu_tool_path NAMES iwyu_tool.py)
if (iwyu_tool_path AND PYTHONINTERP_FOUND)
add_custom_target(iwyu
ALL # Remove ALL if you don't iwyu to be run by default.
COMMAND "${PYTHON_EXECUTABLE}" "${iwyu_tool_path}" -p "${CMAKE_BINARY_DIR}"
COMMENT "Running include-what-you-use tool"
VERBATIM
)
endif()
The include-what-you-use
binary needs to be in your path for any of the above to work properly.