gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 14:00:21 26 4
gpt4 key购买 nike

工具include-what-you-use可用于检测不需要的 header 。我正在使用 CMake对于我的 C++ 软件项目。如何指示 CMake 在我的软件项目的源文件中自动运行 include-what-you-use?

最佳答案

CMake 3.3引入了新的目标属性 CXX_INCLUDE_WHAT_YOU_USE可以设置为程序的路径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 发出警告:不需要包含的标题 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})

关于c++ - 如何使用 include-what-you-use 工具与 CMake 一起检测未使用的 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30951492/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com