Visual Studio 2013 不显示未引用的变量警告

Visual Studio 2013 not displaying unreferenced variable warnings

我在 Visual Studio 2013 年构建,如果我向函数添加未引用的变量,编译器不会抛出有关它们的警告。我尝试根据此线程启用代码分析: Visual Studio 2013 Compiler Warnings not Showing 但这仍然没有解决我的问题。一些附加信息:

示例代码:

bool MyClass::doSomething(int someParameter)
{
    int blah = 1;
    // run the normal function logic here
    // 'someParameter' is referenced, but 'blah' never is.
    // when i compile, i receive no warning that 'blah' is unreferenced.
    return true;
}

在您的示例代码中,语句 int blah = 1; 既声明了变量又对其赋值。 Visual Studio 将此赋值计为变量的 "reference",从而避免了您预期的 C4101 unreferenced local variable 错误。

要定位和删除已初始化但从未使用过的变量,您可以使用静态分析工具,例如Prefast 或CppCheck。有一个此类工具的列表 here,尽管它可能已过时。

请注意,编译器可以标记未使用的 参数 ,即使它们是使用默认参数初始化的。如果您通过 /W4/Wall 使用警告级别 4,则未使用的参数将导致 C4100 unreferenced parameter 警告。始终在 /W4/Wall 而不是默认的 /W3.

处构建是个好主意

正如 Ryan Bemrose 所述,静态代码分析工具可用于检测源代码中未使用的资源。

看看下面的函数:

bool foo(int unusedParameter)
{
  int unusedVariable = 1;
  return true;
}

它包含两个未使用的资源,一个未使用的参数和一个未使用但已初始化的局部变量。 Cppcheck 可以帮助您检测未使用的局部变量,使用以下命令:

$ cppcheck --enable=all test.cpp 
  Checking test.cpp...
  [test.cpp:3]: (style) Variable 'unusedVariable' is assigned a value that is never used.

目前不检测未使用的参数。