我有一个跨平台的应用程序,在我的几个函数中,并不是所有传递给函数的值都被利用。因此我从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 ?(我讨厌这样做,因为它改变了程序流中的某些东西,从而使编译器警告静音)。

有正确的方法吗?


当前回答

一个同事刚给我指了这个小宏

为了方便起见,我将包括下面的宏。

#ifdef UNUSED
#elif defined(__GNUC__) 
# define UNUSED(x) UNUSED_ ## x __attribute__((unused)) 
#elif defined(__LCLINT__) 
# define UNUSED(x) /*@unused@*/ x 
#else 
# define UNUSED(x) x 
#endif

void dcc_mon_siginfo_handler(int UNUSED(whatsig))

其他回答

无宏且可移植的声明一个或多个参数为未使用的方法:

template <typename... Args> inline void unused(Args&&...) {}

int main(int argc, char* argv[])
{
    unused(argc, 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);
}
void func(void *aux UNUSED)
{
    return;
}

SMTH是这样的,在这种情况下,如果你不使用aux,它就不会警告你

c++ 17现在提供了[[maybe_unused]]属性。

http://en.cppreference.com/w/cpp/language/attributes

非常漂亮和标准。

我发现大多数给出的答案只适用于局部未使用的变量,并且会导致未使用的静态全局变量的编译错误。

另一个宏需要抑制未使用的静态全局变量的警告。

template <typename T>
const T* UNUSED_VARIABLE(const T& dummy) { 
    return &dummy;
}
#define UNUSED_GLOBAL_VARIABLE(x) namespace {\
    const auto dummy = UNUSED_VARIABLE(x);\
}

static int a = 0;
UNUSED_GLOBAL_VARIABLE(a);

int main ()
{
    int b = 3;
    UNUSED_VARIABLE(b);
    return 0;
}

这是因为匿名命名空间中的非静态全局变量不会报告任何警告。

c++ 11是必需的

 g++  -Wall -O3  -std=c++11 test.cpp