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

Universally compiler independent way of implementing an UNUSED macro in C/C++(在 C/C++ 中实现 UNUSED 宏的通用编译器独立方式)

本文介绍了在 C/C++ 中实现 UNUSED 宏的通用编译器独立方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实现存根等时,您希望避免未使用的变量"警告.多年来,我遇到了一些 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))

这篇关于在 C/C++ 中实现 UNUSED 宏的通用编译器独立方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 C/C++ 中实现 UNUSED 宏的通用编译器独立方式

基础教程推荐