如何自动查找未使用的#include指令?

通常在编写新代码时,您会发现缺少#include,因为该文件无法编译。 很简单,你添加了所需的#include。 但是后来你以某种方式重构代码,现在不再需要一些#include指令。 如何发现不再需要哪些?

当然,我可以手动删除部分或全部#include行并将其添加回来,直到文件再次编译,但这在包含数千个文件的大型项目中实际上并不可行。 是否有任何工具可以帮助自动化任务?

您可以使用PC-Lint / FlexeLint来执行此操作。

不同寻常的是,该工具没有免费的操作系统版本。

您可以通过引用传递#includes而不是传递值并转发声明来删除#includes。 这是因为编译器不需要在编译时知道对象的大小。 但是,这需要您进行大量的手工操作。 好处是它会减少编译时间。

您可以编写一个“powershell”命令行工具,逐个注释#includes并测试编译是否仍然有效。 什么时候开始工作让我知道。 ; 0)

有一个名为includator的Eclipse插件,它有助于管理C / C ++项目中的包含依赖项

http://includator.com/

本文介绍了使用Doxygen解析进行#include删除的技巧。 这只是一个perl脚本,所以它很容易使用。

这是’暴力’VC6宏,它可以在编辑器中打开的单个.cpp.h文件中通过注释包含并运行编译:

Sub RemoveNotUsedIncludes() 'Check if already processed; Exit if so ActiveDocument.Selection.FindText "//INCLUDE NOT USED", dsMatchFromStart IF ActiveDocument.Selection <> "" THEN ActiveDocument.Selection.SetBookmark MsgBox "Already checked" ActiveDocument.Selection.ClearBookmark EXIT SUB END IF 'Find first #include; Exit if not found ActiveDocument.Selection.FindText "#include", dsMatchFromStart IF ActiveDocument.Selection = "" THEN MsgBox "No #include found" EXIT SUB END IF Dim FirstIncludeLine FirstIncludeLine = ActiveDocument.Selection.CurrentLine FOR i=1 TO 200 'Test build ActiveDocument.Selection.SetBookmark ActiveDocument.Selection = "//CHECKING... #include" Build ActiveDocument.Undo ActiveDocument.Selection.ClearBookmark IF Errors = 0 THEN 'If build failed add comment ActiveDocument.Selection.EndOfLine ActiveDocument.Selection = " //INCLUDE NOT USED" END IF 'Find next include ActiveDocument.Selection.EndOfLine ActiveDocument.Selection.FindText "#include" 'If all includes tested exit IF ActiveDocument.Selection.CurrentLine = FirstIncludeLine THEN EXIT FOR NEXT 

结束子

在案例中,可以改进整个项目的工作。