How to use the tool include-what-you-use together with CMake to detect unused headers?

前端 未结 4 1097
滥情空心
滥情空心 2020-12-22 22:59

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

4条回答
  •  醉梦人生
    2020-12-22 23:45

    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.

    Running the tool manually

    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 .
    

    Adding a custom target to your cmake project

    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()
    

    Notes

    The include-what-you-use binary needs to be in your path for any of the above to work properly.

提交回复
热议问题