如何制作一个可以不带参数调用的 __VA_ARGS__ 宏?
How to make a __VA_ARGS__ macro which can be called with no arguments?
我有一个宏:
#define debug(fmt, ...) printf("%lu %s:%s:%i " fmt, ms(), __FILE__, __func__, __LINE__, __VA_ARGS__)
这正是我想要的。
我可以这样调用它:
debug("i: %i\n", i);
打印i
的值。
我的问题是我无法调用它:
debug("got here");
扩展为:
printf("%lu %s:%s:%i %s " "got here", ms(), __FILE__, __func__, __LINE__,)
这是一个尾随逗号错误。
如何更改我的 __VA_ARGS__
宏,使其可以处理 "no variables"/"only format string" 情况?
您可以分两步完成:
#define debug(...) DEBUG(__VA_ARGS__, "")
#define DEBUG(fmt, ...) printf("%lu %s:%s:%i " fmt "%s", ms(), __FILE__, __func__, __LINE__, __VA_ARGS__)
debug("%d\n", 42);
debug("Hello\n");
这样,即使您不传递第二个参数,它也会被 ""
替换并导致 NOP。
您可以将 printf
分成两部分,而不是尝试在宏本身中连接字符串文字:一部分用于统计信息,另一部分用于您的调试消息。用旧的 do { ... } while (0)
宏技巧将它们结合在一起。
#define debug(...) do { \
printf("%lu %s:%s:%i ", ms(), __FILE__, __func__, __LINE__); \
printf(__VA_ARGS__); \
} while (0)
那么你不需要 fmt
作为单独的参数,只需将 __VA_ARGS__
传递给第二个 printf
.
我有一个宏:
#define debug(fmt, ...) printf("%lu %s:%s:%i " fmt, ms(), __FILE__, __func__, __LINE__, __VA_ARGS__)
这正是我想要的。
我可以这样调用它:
debug("i: %i\n", i);
打印i
的值。
我的问题是我无法调用它:
debug("got here");
扩展为:
printf("%lu %s:%s:%i %s " "got here", ms(), __FILE__, __func__, __LINE__,)
这是一个尾随逗号错误。
如何更改我的 __VA_ARGS__
宏,使其可以处理 "no variables"/"only format string" 情况?
您可以分两步完成:
#define debug(...) DEBUG(__VA_ARGS__, "")
#define DEBUG(fmt, ...) printf("%lu %s:%s:%i " fmt "%s", ms(), __FILE__, __func__, __LINE__, __VA_ARGS__)
debug("%d\n", 42);
debug("Hello\n");
这样,即使您不传递第二个参数,它也会被 ""
替换并导致 NOP。
您可以将 printf
分成两部分,而不是尝试在宏本身中连接字符串文字:一部分用于统计信息,另一部分用于您的调试消息。用旧的 do { ... } while (0)
宏技巧将它们结合在一起。
#define debug(...) do { \
printf("%lu %s:%s:%i ", ms(), __FILE__, __func__, __LINE__); \
printf(__VA_ARGS__); \
} while (0)
那么你不需要 fmt
作为单独的参数,只需将 __VA_ARGS__
传递给第二个 printf
.