我有一个跨平台的应用程序,在我的几个函数中,并不是所有传递给函数的值都被利用。因此我从GCC得到一个警告,告诉我有未使用的变量。

绕开警告的最佳编码方式是什么?

在函数周围使用#ifdef ?

#ifdef _MSC_VER
void ProcessOps::sendToExternalApp(QString sAppName, QString sImagePath, qreal qrLeft, qreal qrTop, qreal qrWidth, qreal qrHeight)
#else
void ProcessOps::sendToExternalApp(QString sAppName, QString sImagePath, qreal /*qrLeft*/, qreal /*qrTop*/, qreal /*qrWidth*/, qreal /*qrHeight*/)
#endif
{

这是如此丑陋,但似乎是编译器更喜欢的方式。

还是把函数末尾的变量赋值为0 ?(我讨厌这样做,因为它改变了程序流中的某些东西,从而使编译器警告静音)。

有正确的方法吗?


当前回答

在GCC和Clang中,你可以使用__attribute__((未使用))预处理器指令来实现你的目标。 例如:

int foo (__attribute__((unused)) int bar) {
   return 0;
}

其他回答

使用编译器的标志,例如GCC的标志: -Wno-unused-variable

你可以使用__unused来告诉编译器这个变量可能不会被使用。

- (void)myMethod:(__unused NSObject *)theObject    
{
    // there will be no warning about `theObject`, because you wrote `__unused`

    __unused int theInt = 0;
    // there will be no warning, but you are still able to use `theInt` in the future
}

使用UNREFERENCED_PARAMETER(p)可以工作。我知道它是在Windows系统的WinNT.h中定义的,也可以很容易地为gcc定义(如果它还没有)。

未引用参数(p)定义为

#define UNREFERENCED_PARAMETER(P)          (P)

在WinNT.h。

一种更简洁的方法是只注释掉变量名:

int main(int /* argc */, char const** /* argv */) {
  return 0;
}

你可以把它放在"(void)var;"表达式中(什么都不做),这样编译器就可以看到它被使用了。这在编译器之间是可移植的。

E.g.

void foo(int param1, int param2)
{
    (void)param2;
    bar(param1);
}

Or,

#define UNUSED(expr) do { (void)(expr); } while (0)
...

void foo(int param1, int param2)
{
    UNUSED(param2);
    bar(param1);
}