首页 > 解决方案 > 使可变长度输入参数无效的 C 宏

问题描述

有没有办法定义一个使变量变量列表无效的宏?

#define VOID_ARGS(...) ((void)##__VA_ARGS__)

当警告被视为错误时,用例是用于抑制编译器错误 [-Werror=unused-value] 的 void 参数:

#define DEBUG 1
#ifdef DEBUG
    #define func(fmt, ...) dbg_func(fmt, ##__VA_ARGS__)
#else
    #define func(fmt, ...) VOID_ARGS(fmt, ##__VA_ARGS__)
#endif

标签: cmacrospreprocessorvariadic-macros

解决方案


这是否让您知道如何解决该问题?

调试.h:

extern int dbg_func(const char *format, ...);

//Does nothing
extern int ignoreDebug(const char *format, ...);


#define DEBUG 1

#ifdef DEBUG
    #define func(fmt, ...) dbg_func(fmt, ##__VA_ARGS__)
#else
    #define func(fmt, ...) ignoreDebug(fmt, ##__VA_ARGS__)
#endif

调试.c:

int ignoreDebug(const char *format, ...)
{
  (void)format;
  return 0;
}

int dbg_func(const char *format, ...)
{
  TODO: Some code needs to go here.
  return 0;
}

推荐阅读