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

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


当前回答

有两种类型的多余的#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.

其他回答

还可以查看include-what-you-use,它可以解决类似的问题。

Clangd现在正在为你做这件事。clang-tidy可能很快也能做到这一点。

本文解释了一种使用Doxygen解析来删除#include的技术。这只是一个perl脚本,所以它很容易使用。

我从来没有找到一个成熟的工具来完成你的要求。我使用过的最接近的工具是IncludeManager,它将头包含树图形化,以便您可以直观地发现只包含在一个文件中的头和循环头包含之类的内容。

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

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