c - 为调用 printf 的宏添加前缀

标签 c macros printf c-preprocessor variadic-functions

有了这个 #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/

相关文章:

C 中的大小写可变宏

python - 使用缓存的退出代码退出程序

c++ - 一维或三维数组?

c++ - 在资源中连接定义和字符串

bash - 使用 bash 将十六进制转换为带符号的 64 位

c++ - 为什么在 msvc++ 中我们有 _snprintf 而其他编译器允许 snprintf

C : printf() not thread safe with flockfile()

c - 按字符串对结构体数组进行排序

c - 为什么我的程序不能用于大型数组?

具有多个语句的 C++ 宏