在 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__)
像这样使用
void blah(char const *UNUSED(path)) {}
有什么方法可以保证唯一的“虚拟”变量名(显然 LINE
和 __func__
不能削减它),或者忽略命名未使用的变量有没有?
更新0
最终使用的代码是available here .
#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
它是这样使用的:
void blah(char const *OMIT_PARAM) {}
并且避免未使用参数、未命名参数警告,并保证它不会破坏其他一些变量名。
最佳答案
停止寻找丑陋的不可移植的、特定于编译器的 hack。即使该函数不使用其参数之一,也可能存在该参数存在的原因:匹配特定的原型(prototype)/签名,很可能是为了函数指针类型兼容性。假设是这种情况,参数有一个由调用者预期传递的内容决定的名称;您的特定函数没有使用任何参数这一事实在很大程度上是无关紧要的。因此,给它一个正确的名称,如果您坚持启用此警告,请使用 __attribute__((unused))
。我总是禁用未使用的参数警告,因为它显然是伪造的。
关于c - C 中的未命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3487135/