我经常发现文件的头部分总是变得越来越大,但它从来没有变小过。在源文件的整个生命周期中,类可能会被移动和重构,并且很可能有相当多的#include不需要存在。保留它们只会延长编译时间,并增加不必要的编译依赖关系。试图找出哪些仍然需要是相当乏味的。
是否有某种工具可以检测多余的#include指令,并建议哪些我可以安全地删除? 棉绒会这样吗?
我经常发现文件的头部分总是变得越来越大,但它从来没有变小过。在源文件的整个生命周期中,类可能会被移动和重构,并且很可能有相当多的#include不需要存在。保留它们只会延长编译时间,并增加不必要的编译依赖关系。试图找出哪些仍然需要是相当乏味的。
是否有某种工具可以检测多余的#include指令,并建议哪些我可以安全地删除? 棉绒会这样吗?
当前回答
您可以编写一个快速脚本,删除单个#include指令,编译项目,并在没有发生编译错误的情况下记录#include中的名称和它被删除的文件。
让它在晚上运行,第二天你就会有一个100%正确的可以删除的包含文件列表。
有时候蛮力很管用:-)
编辑:有时它不会:-)。下面是一些来自评论的信息:
Sometimes you can remove two header files separately, but not both together. A solution is to remove the header files during the run and not bring them back. This will find a list of files you can safely remove, although there might a solution with more files to remove which this algorithm won't find. (it's a greedy search over the space of include files to remove. It will only find a local maximum) There may be subtle changes in behavior if you have some macros redefined differently depending on some #ifdefs. I think these are very rare cases, and the Unit Tests which are part of the build should catch these changes.
其他回答
结束这个讨论:c++预处理器是图灵完成的。包含是否是多余的,这是一个语义属性。因此,由Rice定理可知,包含是否多余是不可判定的。不可能有一个程序(总是正确地)检测包含是否多余。
很抱歉(再次)在这里发帖,人们通常不扩展评论。
检查我对crashmstr的评论,FlexeLint / PC-Lint会为你做这件事。信息信息766号。我的手册(8.0版)的11.8.1节讨论了这个问题。
另外,这一点很重要,不断迭代,直到消息消失。换句话说,在删除了不需要的头文件后,重新运行lint,一旦删除了一些不需要的头文件,更多的头文件可能已经成为“不需要的”。(这可能听起来很傻,慢慢读并分析它,这是有道理的。)
有一个免费的工具包括文件依赖监视器,它可以集成到可视化工作室中。它用红色显示多余的#include。
您可以编写一个快速脚本,删除单个#include指令,编译项目,并在没有发生编译错误的情况下记录#include中的名称和它被删除的文件。
让它在晚上运行,第二天你就会有一个100%正确的可以删除的包含文件列表。
有时候蛮力很管用:-)
编辑:有时它不会:-)。下面是一些来自评论的信息:
Sometimes you can remove two header files separately, but not both together. A solution is to remove the header files during the run and not bring them back. This will find a list of files you can safely remove, although there might a solution with more files to remove which this algorithm won't find. (it's a greedy search over the space of include files to remove. It will only find a local maximum) There may be subtle changes in behavior if you have some macros redefined differently depending on some #ifdefs. I think these are very rare cases, and the Unit Tests which are part of the build should catch these changes.
如果您正在使用Eclipse CDT,您可以尝试http://includator.com,它对beta测试人员是免费的(在撰写本文时),并自动删除多余的#includes或添加缺失的#includes。对于那些拥有FlexeLint或PC-Lint并正在使用Elicpse CDT的用户,http://linticator.com可能是一个选项(beta测试也是免费的)。虽然它使用了Lint的分析,但它提供了自动删除多余的#include语句的快速修复。