用于 C 和 C++ 的函数签名的可移植 UNUSED 参数宏

2022-01-11 00:00:00 c macros warnings c++

我有兴趣创建一个宏来消除未使用的变量警告.

I'm interested in creating a macro for eliminating the unused variable warning.

这个问题描述了一种通过在函数代码中编写宏来抑制未使用参数警告的方法:

This question describes a way to suppress the unused parameter warning by writing a macro inside the function code:

通用编译器独立的实现方式C/C++ 中的 UNUSED 宏

但我对可以在函数签名中使用的宏感兴趣:

But I'm interested in a macro that can be used in the function signature:

void 回调(int UNUSED(some_useless_stuff)) {}

这是我用谷歌挖出来的(source)

This is what I dug out using Google (source)

#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

这可以针对其他编译器进一步扩展吗?

Can this be further expanded for other compilers?

对于那些不明白标记是如何工作的人:我想要一个同时适用于 C 和 C++ 的解决方案.这就是为什么这个问题同时被标记为 C 和 C++,这就是为什么不能接受仅 C++ 的解决方案.

For those who can't understand how tagging works: I want a solution for both C and C++. That is why this question is tagged both C and C++ and that is why a C++ only solution is not acceptable.

推荐答案

经过测试和评论,问题中提到的原始版本已经足够了.

After testing and following the comments, the original version mentioned in the question turned out to be good enough.

使用:#define UNUSED(x) __pragma(warning(suppress:4100)) x(在评论中提到),可能是在 MSVC 上编译 C 所必需的,但这是一个奇怪的组合,我最后没有把它包括在内.

Using: #define UNUSED(x) __pragma(warning(suppress:4100)) x (mentioned in comments), might be necessary for compiling C on MSVC, but that's such a weird combination, that I didn't include it in the end.

相关文章