【问题标题】:How do I automate finding unused #include directives?如何自动查找未使用的#include 指令?
【发布时间】:2010-09-08 06:29:29
【问题描述】:

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

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

【问题讨论】:

标签: c


【解决方案1】:

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

该工具通常没有免费的操作系统版本。

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

【讨论】:

  • 我找不到任何说它可以做到这一点的 lint 文档。你有指针吗?
  • 不幸的是,我也找不到免费提供的。我有一个 PC-Lint 许可证,我可以保证它在那里。也许您应该直接联系 Gimpel?他们可能会向您发送手册的摘录。
  • +e766 // 包含头文件 FileName not used in module String
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      http://includator.com/

      【讨论】:

        【解决方案5】:

        这里是 'brute force' VC6 宏,它适用于在编辑器中打开的单个 .cpp.h 文件,方法是通过 include 注释 include并运行编译:

        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
        

        结束子

        当然可以改进以适用于整个项目。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-10-02
          • 2014-12-10
          • 2014-09-10
          • 1970-01-01
          • 1970-01-01
          • 2014-02-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多