抑制"未使用的变量x" - 警告的最佳方法是什么

gus*_*taf 52 c gcc

抑制编译器(在本例中为gcc)的最佳/最佳方法是什么,如"未使用的变量x" - 警告?

我不想给gcc提供任何特定的标志来删除所有这些警告,仅用于特殊情况.

jam*_*lin 44

(void) variable 可能适用于某些编译器.

对于C++代码,另请参阅http://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/,其中Herb Sutter建议使用:

template<class T> void ignore( const T& ) { }

...

ignore(variable);
Run Code Online (Sandbox Code Playgroud)

  • `(void) variable` 很酷,因为它适用于任何未使用的变量,而不仅仅是像接受的答案那样的函数参数。 (2认同)

use*_*610 25

不要给变量命名(C++)

void foo(int /*bar*/) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

使用编译器特定的非标准机制告诉编译器

查看各种答案__attribute__((unused)),各种#pragmas等.(可选)在其周围包装预处理器宏以实现可移植性.

关闭警告

IDE可以直观地显示未使用的变量(不同的颜色或下划线).有了这个,编译器警告可能相当无用.

在GCC和Clang中,-Wno-unused-parameter在命令行的末尾添加选项(在所有切换未使用的参数警告的选项之后,例如-Wall,-Wextra).

添加一个转换为void

void foo(int bar) {
    (void)bar;
}
Run Code Online (Sandbox Code Playgroud)

根据jamesdlin的回答和http://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/

  • 我不敢相信评论它有效。如果您使用 C++ 并且它是兼容的,那么这就是要走的路。 (4认同)

Edw*_*eno 22

找到了解释UNUSED 的文章http://sourcefrog.n​​et/weblog/software/languages/C/unused.html.有趣的是,作者还破坏了未使用的变量名称,因此您将来不会无意中使用它.

摘抄:

#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)) 
Run Code Online (Sandbox Code Playgroud)

  • ...另一个只写头宏正是我们需要得到一个相当良性的警告. (8认同)

Cas*_*bel 13

如果这真的是你想要的,你可以使用未使用的属性(仅限gcc),例如:

void foo(int __attribute__((__unused__)) bar) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

当然,不仅仅是函数参数,而且这是最常见的用例,因为它可能是API的回调函数,您实际上并不需要所有输入.

另外,GLib有一个G_GNUC_UNUSED宏,我相信它会扩展到该属性.


Jam*_*ter 12

您可以使用静音警告 #pragma

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused"

int unususedVariable = 1;

#pragma clang diagnostic pop
Run Code Online (Sandbox Code Playgroud)

如果您使用的是GCC,请使用 #pragma gcc ...