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

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

在实现存根等时,您希望避免未使用的变量"警告.多年来,我遇到了一些 UNUSED() 宏的替代方案,但从来没有一种被证明适用于所有"编译器,也没有一种按照标准是密封的.

When implementing stubs etc. you want to avoid "unused variable" warnings. I've come across a few alternatives of UNUSED() macros over the years, but never one which either is proven to work for "all" compilers, or one which by standard is air tight.

或者我们是否坚持使用每个构建平台的 #ifdef 块?

Or are we stuck with #ifdef blocks for each build platform?

由于有许多不符合 c 的替代方案的答案,我想澄清一下,我正在寻找一个对 C 和 C++ 都有效的定义,所有风格等等

Due to a number of answers with non c-compliant alternatives, I'd like to clarify that I'm looking for a definition which is valid for both C and C++, all flavours etc.

推荐答案

根据this answer by 用户 GMan 典型方式是强制转换为void:

According to this answer by user GMan the typical way is to cast to void:

#define UNUSED(x) (void)(x)

但是如果 x 被标记为 volatile 这将强制从变量中读取并因此产生副作用,因此几乎可以保证无操作和抑制编译器警告如下:

but if x is marked as volatile that would enforce reading from the variable and thus have a side effect and so the actual way to almost guarantee a no-op and suppress the compiler warning is the following:

// use expression as sub-expression,
// then make type of full expression int, discard result
#define UNUSED(x) (void)(sizeof((x), 0))

相关文章