Let*_*_Be 34 c c++ macros warnings
我有兴趣创建一个用于消除未使用的变量警告的宏.
此问题描述了一种通过在函数代码中编写宏来抑制未使用的参数警告的方法:
但是我对可以在函数签名中使用的宏感兴趣:
void callback(int UNUSED(some_useless_stuff)) {}
这就是我用谷歌挖出来的(来源)
#ifdef UNUSED
#elif defined(__GNUC__)
# define UNUSED(x) UNUSED_ ## x __attribute__((unused))
#elif defined(__LCLINT__)
# define UNUSED(x) /*@unused@*/ x
#elif defined(__cplusplus)
# define UNUSED(x)
#else
# define UNUSED(x) x
#endif
Run Code Online (Sandbox Code Playgroud)
这可以进一步扩展到其他编译器吗?
编辑:对于那些无法理解标记如何工作的人:我想要一个C和C++的解决方案.这就是为什么这个问题被标记为C和C++的原因,这就是为什么只有C++的解决方案是不可接受的.
Mat*_*son 23
我这样做的方式是这样的:
#define UNUSED(x) (void)(x)
void foo(const int i) {
UNUSED(i);
}
Run Code Online (Sandbox Code Playgroud)
我在Visual Studio,Intel gcc和clang.中没有遇到过这个问题.
另一种选择是只注释掉参数:
void foo(const int /*i*/) {
// When we need to use `i` we can just uncomment it.
}
Run Code Online (Sandbox Code Playgroud)
在测试并遵循评论后,问题中提到的原始版本证明是足够好的.
使用:( #define UNUSED(x) __pragma(warning(suppress:4100)) x在评论中提到),可能需要在MSVC上编译C,但这是一个奇怪的组合,我最后没有包含它.
只是一件小事,更好地使用__attribute__((__unused__))as __attribute__((unused)),因为未使用的可能是定义为宏的地方,我个人对这种情况有一些问题.
但我正在使用的技巧是,我发现更具可读性:
#define UNUSED(x) (void)x;
但它只适用于变量和方法的参数,但不适用于函数本身.
在许多编译器中,我使用了以下内容,不包括对lint的支持.
#if (__GNUC__ > 2) || (__GNUC__ == 2 && __GNUC_MINOR__ > 4)
# define PGM_GNUC_UNUSED __attribute__((__unused__))
#else
# define PGM_GNUC_UNUSED
#endif
Run Code Online (Sandbox Code Playgroud)
经过测试的编译器:GCC,Clang,EKOPath,英特尔C编译器/作曲家XE,Cygwin/Linux/MSYS上的MinGW32,Cygwin/Linux上的MinGW-w64,Sun ONE Studio/Oracle Solaris Studio,Visual Studio 2008/2010.
用法示例:
pgm_tsc_init (
PGM_GNUC_UNUSED pgm_error_t** error
)
{
...
}
Run Code Online (Sandbox Code Playgroud)
PGM是此基于C的项目的标准前缀. GNUC是GLib对此属性的约定.
我认为编译器会__attribute__在某些情况下发出警告,但肯定没有错误.