抑制编译器(在本例中为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)
use*_*610 25
void foo(int /*bar*/) {
...
}
Run Code Online (Sandbox Code Playgroud)
查看各种答案__attribute__((unused))
,各种#pragma
s等.(可选)在其周围包装预处理器宏以实现可移植性.
IDE可以直观地显示未使用的变量(不同的颜色或下划线).有了这个,编译器警告可能相当无用.
在GCC和Clang中,-Wno-unused-parameter
在命令行的末尾添加选项(在所有切换未使用的参数警告的选项之后,例如-Wall
,-Wextra
).
void foo(int bar) {
(void)bar;
}
Run Code Online (Sandbox Code Playgroud)
根据jamesdlin的回答和http://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/
Edw*_*eno 22
找到了解释UNUSED 的文章http://sourcefrog.net/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)
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 ...