有了这个 #define PRINTF(...) printf(__VA_ARGS__)
我想创建一个调用 PRINTF
的宏,但会向打印的字符串添加前缀,例如示例:
#define PRINTF_P(<args>) PRINTF(<whatever>)
// let's suppose that the desired prefix is 'prefix - '
PRINTF_P("Hello world\n");
PRINTF_P("Hello world, num = %d\n", 25);
// Result:
prefix - Hello world
prefix - Hello world, num = 20
我该怎么做?
我尝试过的
以下内容适用于像 PRINTF_P("string with argument %d\n", arg)
这样的调用,但不适用于像`PRINTF_P("string with no argument\n"这样的调用);
#include <stdio.h>
#include <stdarg.h>
#define PRINTF(...) printf(__VA_ARGS__)
#define A(fmt, ...) fmt
#define B(fmt, ...) __VA_ARGS__
#define PRINTF_P(...) printf( "prefix - " A(__VA_ARGS__), B(__VA_ARGS__))
int main(void)
{
PRINTF_P("No number\n"); // This fails
PRINTF_P("Number = %d\n", 20); // This works
return 0;
}
编辑
我仅指字符串文字的情况,而不是 char *
。
最佳答案
这很简单:
#include <stdio.h>
#include <stdarg.h>
#define PRINTF(...) printf(__VA_ARGS__)
#define PRINTF_P(...) printf( "prefix " __VA_ARGS__)
int main(void)
{
PRINTF("No number\n");
PRINTF("Number = %d\n", 20);
PRINTF_P("No number\n");
PRINTF_P("Number = %d\n", 20);
return 0;
}
关于c - 为调用 printf 的宏添加前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72161692/