C中未命名的参数

Mat*_*ner 5 c macros gcc

在C中,与C++不同,必须命名函数定义的所有参数.

我创建了以下宏,而不是使用(void)a或公开使用来撤销"未使用的参数"错误__attribute__((unused)):

#define UNUSED2(var, uniq) UNUSED_ ## line ## var __attribute((unused))
// squash unused variable warnings, can it be done without var?
#define UNUSED(var) UNUSED2(var, __func__)
Run Code Online (Sandbox Code Playgroud)

像这样使用

void blah(char const *UNUSED(path)) {}
Run Code Online (Sandbox Code Playgroud)

有没有一些方法,我可以保证一个独特的"虚拟"变量名(显然LINE__func__不能削减它),或忽视的名字在所有未使用的变量?

Update0

使用的最终代码可在此处获得.

#ifdef __cplusplus
    // C++ allows you to omit parameter names if they're unused
#   define OMIT_PARAM
#else
    // A variable name must be provided in C, so make one up and mark it unused
#   define OMIT_PARAM3(uniq) const omitted_parameter_##uniq VARATTR_UNUSED
#   define OMIT_PARAM2(uniq) OMIT_PARAM3(uniq)
#   define OMIT_PARAM OMIT_PARAM2(__COUNTER__)
#endif

#ifdef _MSC_VER
#   define VARATTR_UNUSED
#else
#   define VARATTR_UNUSED __attribute__((unused))
#endif
Run Code Online (Sandbox Code Playgroud)

它的使用方式如下:

void blah(char const *OMIT_PARAM) {}
Run Code Online (Sandbox Code Playgroud)

并且避免使用未使用的参数,未命名的参数警告,并保证它不会破坏其他变量名称.

R..*_*R.. 5

停止寻找丑陋的不可移植的,特定于编译器的黑客攻击.即使函数没有使用它的一个参数,大概存在参数存在的原因:匹配特定的原型/签名,最有可能出于函数指针类型兼容性的目的.假如是这样的话,参数由什么呼叫者有望通过确定名称; 你的特定功能没有使用任何参数的事实在很大程度上是无关紧要的.所以给它正确的名称,__attribute__((unused))如果你坚持启用此警告,请使用它.我总是禁用未使用的参数警告,因为它显然是假的.


Mot*_*tti 2

VC有一个__COUNTER__具有唯一性的宏,GCC 似乎在 4.3.5 版本中有一个同名的等效宏(尽管我目前找不到实时链接)。