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

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


当前回答

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

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

其他回答

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

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

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

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

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的唯一方法是删除、编译和运行套件。

CLion是JetBrains开发的C/ c++ IDE,可以即时检测冗余内容。这些在编辑器中是灰色的,但也有一些函数可以优化当前文件或整个项目中的包含。

我发现你需要为这个功能付费;当第一次加载时,CLion需要一段时间来扫描和分析您的项目。