【问题标题】:CppCheck ignores the usage of variables in macro definitions, how to change that?CppCheck 忽略了宏定义中变量的使用,如何改变它?
【发布时间】:2021-02-23 17:26:27
【问题描述】:

在我的代码上运行 CppCheck 的输出显示以下错误: Variable 'strFullPath' is assigned a value that is never used. [unreadVariable]

下面的方法是讨论中的方法。

void DebugLogging::GetDebugLogSettings(const std::string& sAppProfile)
{
    std::string strFullPath = ROOT_KEY_NAME + sAppProfile;
    
#ifdef _WIN32
    std::string strFullPathLocal = strFullPath + "Local";
#else
    std::string sAppProfileLocal = sAppProfile + "Local";
    std::ifstream settingsLocalfile(sAppProfileLocal.c_str());
#endif
}

CppCheck 声明strFullPath 的值从未使用过。但是,它在宏内部使用。

如何设置 CppCheck 使其能够发现变量的使用情况?

【问题讨论】:

    标签: cppcheck


    【解决方案1】:

    将它移到宏内。

    void DebugLogging::GetDebugLogSettings(const std::string& sAppProfile)
    {
    #ifdef _WIN32
        std::string strFullPath = ROOT_KEY_NAME + sAppProfile;
        std::string strFullPathLocal = strFullPath + "Local";
    #else
        std::string sAppProfileLocal = sAppProfile + "Local";
        std::ifstream settingsLocalfile(sAppProfileLocal.c_str());
    #endif
    }
    

    【讨论】:

      【解决方案2】:

      我是一名 Cppcheck 开发人员。 Damian-Teodor Beles 建议的修复方法很好。

      我只是想补充一些哲学。在我看来,这个特别的警告是不幸的。我认为这是误报,作为人类,我可以看到使用了该值。

      这种误报可以在 Cppcheck 中修复。我们已经修复了一些相关的误报,但显然不是这个。将来可能会在 Cppcheck 中修复,但我不能保证什么时候会发生。

      一般来说,我认为移动变量是一个很好的解决方法。但也许有时你不想移动变量。然后你现在可以内联抑制警告。当我们在 Cppcheck 中修复此问题时,您将收到一条警告,指出从未使用过内联抑制......然后您可以删除评论。

      【讨论】:

      • 这种误报会影响 catch2 和 doctest,其中模板/宏不幸被使用。任何包含在 CHECK() 或 REQUIRE 中的东西都可以产生 'unreadvariable'
      • 在示例代码中 OP 显示.. 如果将变量移动到正确的 #ifdef 代码中,代码将更加干净和正确分离。如果你对 CHECK() 和 REQUIRE 有问题,那么我猜你有一些不同的问题。
      猜你喜欢
      • 1970-01-01
      • 2022-09-25
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多