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

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


当前回答

有一个免费的工具包括文件依赖监视器,它可以集成到可视化工作室中。它用红色显示多余的#include。

其他回答

结束这个讨论:c++预处理器是图灵完成的。包含是否是多余的,这是一个语义属性。因此,由Rice定理可知,包含是否多余是不可判定的。不可能有一个程序(总是正确地)检测包含是否多余。

The problem with detecting superfluous includes is that it can't be just a type dependency checker. A superfluous include is a file which provides nothing of value to the compilation and does not alter another item which other files depend. There are many ways a header file can alter a compile, say by defining a constant, redefining and/or deleting a used macro, adding a namespace which alters the lookup of a name some way down the line. In order to detect items like the namespace you need much more than a preprocessor, you in fact almost need a full compiler.

Lint更多的是一个样式检查器,当然不会有这个完整的功能。

我想你会发现检测多余include的唯一方法是删除、编译和运行套件。

这不是自动的,但是doxygen会为#included文件生成依赖关系图。你必须从视觉上看它们,但它们对于了解什么在使用什么是非常有用的。

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

这里有一个简单的暴力方法来识别多余的头包含。它并不完美,但消除了“明显的”不必要的包含。清除这些代码对清理代码大有帮助。

这些脚本可以直接在GitHub上访问。