使用 include-what-you-use 检测冗余头文件

include-what-you-use 可以很方便的检测未使用的头文件,使用的时候绕了点路,google后解决,记录一下。

###1、安装clang
ubuntu下直接apt-get 安装就行了。需要注意的是,我的机器上安装clang3.8 后有问题,装了clang3.4后一切正常。暂不研究原因了,先用起来再说。

###2、切换编译器到clang

sudo update-alternatives --config cc
sudo update-alternatives --config c++

###3、编译 include-what-you-use
参考官方文档就行,没有任何错误。

###4、可以开始玩了 (参考的贴子)

  • 写个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)
if(NOT iwyu_path)
  message(FATAL_ERROR "Could not find the program include-what-you-use")
else()
  set_property(TARGET hello PROPERTY CXX_INCLUDE_WHAT_YOU_USE ${iwyu_path})
endif()
  • 写个源码main.cc
#include 
#include 

int main() {
  std::cout << "Hello World!" << std::endl;
  return 0;
}
  • 跑跑试试
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   // lines 2-2

The full include-list for /home/user/hello/main.cc:
#include   // 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$

###5、改进一下CMakeLists
上面的CMakeLists不太适合产品使用,因为打印太多了,可以在需要的时候再打开include-what-you-use。

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

if (ENABLE_IWYU)
  find_program(iwyu_path NAMES include-what-you-use iwyu)
  if(NOT iwyu_path)
    message(FATAL_ERROR "Could not find the program include-what-you-use")
  else()
    set_property(TARGET hello PROPERTY CXX_INCLUDE_WHAT_YOU_USE ${iwyu_path})
  endif()
endif()

用法:

cmake . -DENABLE_IWYU=ON

你可能感兴趣的:(------【c/c++】,☀编程语言)