问题描述
如何将嵌套的#define 定义为带有可变参数的宏
#ifndef MY_PRINTF
#define MY_PRINTF(f_,...) { \
#ifdef USE_WRITE_DEBUG_INFO \
char buff[200]; \
sprintf(buff,(f_),__VA_ARGS__); \
WriteDebugInfo(buff); \
#else \
printf((f_),__VA_ARGS__); \
#endif \
}
#endif
Visual Studio 抱怨缺少指令。如有任何提示,我将不胜感激。
解决方法
在定义 #define
时不能使用预处理器指令。这意味着您的 #ifdef USE_WRITE_DEBUG_INFO
将无法工作。
对于这种情况,请使用函数而不是宏:
#include <cstdarg>
void my_printf(const char* format,...) {
#ifdef USE_WRITE_DEBUG_INFO
char buff[200];
va_list args;
va_start(args,format);
// Note: uses the snprintf variant rather than sprintf variant,// avoiding buffer overlows.
vsnprintf(buff,200,format,args);
va_end(args);
WriteDebugInfo(buff);
#else
va_list args;
va_start(args,format);
vprintf(format,args);
va_end(args);
#endif
}
通常,您必须将预处理器指令置于 #define
之外:
#ifndef MY_PRINTF
#ifdef USE_WRITE_DEBUG_INFO
// do { ... } while (false) makes the macro behave mostly like a regular function call.
#define MY_PRINTF(f_,...) do { \
char buff[200]; \
sprintf(buff,(f_),__VA_ARGS__); \
WriteDebugInfo(buff); \
} while (false)
#else
#define MY_PRINTF(f_,...) printf((f_),__VA_ARGS__)
#endif
#endif