我有一个跨平台的应用程序,在我的几个函数中,并不是所有传递给函数的值都被利用。因此我从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;
}

你可以使用__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
}

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

首先,警告是由源文件中的变量定义生成的,而不是头文件。头文件可以保持原始状态,而且应该保持原始状态,因为您可能正在使用类似doxygen的东西来生成api文档。

我假设您在源文件中有完全不同的实现。在这些情况下,您可以注释掉有问题的参数,或者直接写入参数。

例子:

func(int a, int b)
{
    b;
    foo(a);
}

这可能看起来很神秘,所以定义了一个像UNUSED这样的宏。MFC的做法是:

#ifdef _DEBUG
#define UNUSED(x)
#else
#define UNUSED(x) x
#endif

像这样,在调试版本中仍然会看到警告,可能会有帮助。

当前的解决方案是最好的——如果不使用参数名,就注释掉它。这适用于所有编译器,因此不需要使用预处理程序专门为GCC做这件事。