如何使用工具 include-what-you-use 与 CMake 一起检测未使用的 headers?

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

我的 C++ 软件项目的工具 include-what-you-use can be used to detect unneeded headers. I am using CMake。如何指示 CMake 在我的软件项目的源文件上自动 运行 include-what-you-use?

CMake 3.3 introduced the new target property CXX_INCLUDE_WHAT_YOU_USE that can be set to the path of the program include-what-you-use。例如这个 CMakeLists.txt

cmake_minimum_required(VERSION 3.3 FATAL_ERROR)
add_executable(hello main.cc)

find_program(iwyu_path NAMES include-what-you-use iwyu REQUIRED)

# If using CGAL<3.18, you remove REQUIRED and use
# if(NOT iwyu_path)
#   message(FATAL_ERROR "Could not find the program include-what-you-use")
# endif()

set_property(TARGET hello PROPERTY CXX_INCLUDE_WHAT_YOU_USE ${iwyu_path})

能够构建文件 main.cc

#include <iostream>
#include <vector>

int main() {
  std::cout << "Hello World!" << std::endl;
  return 0;
}

同时 include-what-you-use 发出警告 不需要包含的 header vector

user@ubuntu:/tmp$ ls ~/hello
CMakeLists.txt  main.cc
user@ubuntu:/tmp$ mkdir /tmp/build
user@ubuntu:/tmp$ cd /tmp/build
user@ubuntu:/tmp/build$ ~/cmake-3.3.0-rc2-Linux-x86_64/bin/cmake ~/hello
-- The C compiler identification is GNU 4.9.2
-- The CXX compiler identification is GNU 4.9.2
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /tmp/build
user@ubuntu:/tmp/build$ make
Scanning dependencies of target hello
[ 50%] Building CXX object CMakeFiles/hello.dir/main.cc.o
Warning: include-what-you-use reported diagnostics:

/home/user/hello/main.cc should add these lines:

/home/user/hello/main.cc should remove these lines:
- #include <vector>  // lines 2-2

The full include-list for /home/user/hello/main.cc:
#include <iostream>  // for operator<<, basic_ostream, cout, endl, ostream
---

[100%] Linking CXX executable hello
[100%] Built target hello
user@ubuntu:/tmp/build$ ./hello 
Hello World!
user@ubuntu:/tmp/build$

如果您想将自定义选项传递给 include-what-you-use,例如 --mapping_file,您可以通过

set(iwyu_path_and_options
    ${iwyu_path}
    -Xiwyu
    --mapping_file=${my_mapping})

set_property(TARGET hello
    PROPERTY CXX_INCLUDE_WHAT_YOU_USE ${iwyu_path_and_options})

如果您无法访问 CMake 3.3,include-what-you-use 附带了一个名为 iwyu_tool.py 的 python 工具,它可以执行您想要的操作。

它通过解析 JSON 编译数据库来工作,该数据库很容易用 CMake 生成(见下文)。

运行 手动工具

假设您已经为您的项目创建了一个 CMake 构建目录,您首先需要告诉 CMake 生成编译数据库:

$ cd build
$ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON .

这会生成一个文件,compile_commands.json 包含对项目中每个目标文件的编译器调用。您不需要重建项目。

您现在可以 运行 include-what-you-use 您的项目,方法是 运行 在您的构建目录中使用 python 工具:

$ python /path/to/iwyu_tool.py -p .

将自定义目标添加到您的 cmake 项目

以下代码片段可用于将 iwyu 目标添加到 cmake 项目。

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

注释

include-what-you-use 二进制文件需要在您的路径中才能使上述任何一项正常工作。

默认情况下,iwyu_tool.py 是单线程的,对于大型项目来说可能会很慢。您可以使用 --jobs 参数来增加将被并行处理的源文件的数量。

我扩展了 Alastair Harrison 的源代码,以创建可重用的解决方案。我想出了以下应该适用于 all CMake 版本的内容:

文件iwyu.cmake:

#.rst:
# include-what-you-use (iwyu)
# ----------------------------
#
# Allows to run the static code analyzer `include-what-you-use (iwyu)
# <http://include-what-you-use.org>`_ as a custom target with the build system
# `CMake <http://cmake.org>`_.
#
# .. topic:: Dependencies
#
#  This module requires the following *CMake* modules:
#
#  * ``FindPythonInterp``
#
# .. topic:: Contributors
#
#  * Florian Wolters <wolters.fl@gmail.com>

#===============================================================================
# Copyright 2015 Florian Wolters
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#===============================================================================

# ------------------------------------------------------------------------------
# Include guard for this file.
# ------------------------------------------------------------------------------

if(iwyu_included)
  return()
endif()

set(iwyu_included TRUE)

option(BUILD_IWYU
       "Run the include-what-you-use static analyzer on the source code of the project."
       OFF)

function(iwyu_enable)
  set(iwyu_EXECUTABLE_NAME include-what-you-use)
  find_program(iwyu_EXECUTABLE ${iwyu_EXECUTABLE_NAME})

  if(iwyu_EXECUTABLE)
    # This is not exactly the same behavior as with CMake v3.3, since here all
    # compiled targets are analyzed.
    set(iwyu_tool_EXECUTABLE_NAME iwyu_tool.py)

    find_package(PythonInterp)
    find_program(iwyu_tool_EXECUTABLE ${iwyu_tool_EXECUTABLE_NAME})

    if(PYTHONINTERP_FOUND AND iwyu_tool_EXECUTABLE)
      set(CMAKE_EXPORT_COMPILE_COMMANDS ON PARENT_SCOPE)

      add_custom_target(iwyu
                        ALL
                        COMMAND "${PYTHON_EXECUTABLE}" "${iwyu_tool_EXECUTABLE}" -p "${CMAKE_BINARY_DIR}"
                        COMMENT "Running the ${iwyu_tool_EXECUTABLE_NAME} compilation database driver"
                        VERBATIM)
    else()
      message(STATUS
              "Unable to find the Python interpreter and/or the ${iwyu_tool_EXECUTABLE_NAME} script")
    endif()
  else()
    message(STATUS "Unable to find the ${iwyu_EXECUTABLE_NAME} executable")
  endif()
endfunction()

文件CMakeLists.txt:

cmake_minimum_required(VERSION 3.0)

include(iwyu.cmake)

project(hello_world)
add_executable(${PROJECT_NAME} main.cc)

if(BUILD_IWYU)
  iwyu_enable()
endif()

调用 CMake 如下 运行 include-what-you-useall 目标被调用:

cmake -DBUILD_IWYU=ON <path-to-source>
cmake --build . --target all

输出应该如下:

-- Configuring done
-- Generating done
-- Build files have been written to: /home/wolters/workspace/include-what-you-use_example/build
[ 66%] Built target hello_world
[100%] Running the iwyu_tool.py compilation database driver

/home/wolters/workspace/include-what-you-use_example/develop/main.cc should add these lines:

/home/wolters/workspace/include-what-you-use_example/develop/main.cc should remove these lines:
- #include <vector>  // lines 1-1

The full include-list for /home/wolters/workspace/include-what-you-use_example/develop/main.cc:
#include <iostream>  // for operator<<, basic_ostream, cout, endl, ostream
---
[100%] Built target iwyu

编辑 2015-08-19: CMake 属性 <LANG>_INCLUDE_WHAT_YOU_USE 的方法无效对我来说 CMake 版本 3.3.1。因此我更新了解决方案。

编辑 2015-09-30: 输出错误,因为我的 include-what-you-use 安装被破坏了。 include-what-you-useiwyu_tool.py 文件必须与 clangclang++ 等文件位于同一目录中

您还可以通过设置 cmake 变量在 cmake 脚本之外全局启用它:

cmake -DCMAKE_CXX_INCLUDE_WHAT_YOU_USE="iwyu" <builddir> 

然后它将在每个 CXX 目标上调用它。