我经常发现文件的头部分总是变得越来越大,但它从来没有变小过。在源文件的整个生命周期中,类可能会被移动和重构,并且很可能有相当多的#include不需要存在。保留它们只会延长编译时间,并增加不必要的编译依赖关系。试图找出哪些仍然需要是相当乏味的。

是否有某种工具可以检测多余的#include指令,并建议哪些我可以安全地删除? 棉绒会这样吗?


当前回答

谷歌的cppclean(链接到:下载,文档)可以找到几种类型的c++问题,现在它可以找到多余的#includes。

还有一个基于clang的工具(包括您所使用的工具)可以做到这一点。include-what-you-use甚至可以建议前向声明(因此您不必#include那么多),并可选地为您清理#includes。

当前版本的Eclipse CDT也内置了这个功能:在Source菜单下单击Organize Includes将按字母顺序排列#include,添加Eclipse认为您正在使用的任何标题,但不直接包括它们,并注释掉它认为您不需要的任何标题。然而,这个特性并不是100%可靠。

其他回答

我认为PCLint可以做到这一点,但我已经有几年没有研究它了。你可以去看看。

我看了这个博客,作者谈到了一些关于配置PCLint以查找未使用的包含的内容。也许值得一看。

谷歌的cppclean(链接到:下载,文档)可以找到几种类型的c++问题,现在它可以找到多余的#includes。

还有一个基于clang的工具(包括您所使用的工具)可以做到这一点。include-what-you-use甚至可以建议前向声明(因此您不必#include那么多),并可选地为您清理#includes。

当前版本的Eclipse CDT也内置了这个功能:在Source菜单下单击Organize Includes将按字母顺序排列#include,添加Eclipse认为您正在使用的任何标题,但不直接包括它们,并注释掉它认为您不需要的任何标题。然而,这个特性并不是100%可靠。

也许有点晚了,但我曾经找到一个WebKit perl脚本,它做的正是你想要的。我相信它需要一些调整(我不太精通perl),但它应该能做到:

http://trac.webkit.org/browser/branches/old/safari-3-2-branch/WebKitTools/Scripts/find-extra-includes

(这是一个旧的分支,因为trunk不再有文件了)

有两种类型的多余的#include文件:

头文件实际上不需要 模块(.c, .cpp) 模块需要头文件 而是不止一次,直接或间接地。

根据我的经验,有两种方法可以很好地检测到它:

gcc -H or cl.exe /showincludes (resolve problem 2) In real world, you can export CFLAGS=-H before make, if all the Makefile's not override CFLAGS options. Or as I used, you can create a cc/g++ wrapper to add -H options forcibly to each invoke of $(CC) and $(CXX). and prepend the wrapper's directory to $PATH variable, then your make will all uses you wrapper command instead. Of course your wrapper should invoke the real gcc compiler. This tricks need to change if your Makefile uses gcc directly. instead of $(CC) or $(CXX) or by implied rules. You can also compile a single file by tweaking with the command line. But if you want to clean headers for the whole project. You can capture all the output by: make clean make 2>&1 | tee result.txt PC-Lint/FlexeLint(resolve problem both 1 and 2) make sure add the +e766 options, this warning is about: unused header files. pclint/flint -vf ... This will cause pclint output included header files, nested header files will be indented appropriately.

如果您正在使用Eclipse CDT,您可以尝试http://includator.com,它对beta测试人员是免费的(在撰写本文时),并自动删除多余的#includes或添加缺失的#includes。对于那些拥有FlexeLint或PC-Lint并正在使用Elicpse CDT的用户,http://linticator.com可能是一个选项(beta测试也是免费的)。虽然它使用了Lint的分析,但它提供了自动删除多余的#include语句的快速修复。