Home > Back-end >  Add prefix to a macro that calls printf
Add prefix to a macro that calls printf

Time:05-09

Having this #define PRINTF(...) printf(__VA_ARGS__) I want to create a macro that calls PRINTF but that adds prefix to the printed string, for example:

#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

How can I do this?

What I have tried

The following works for calls like PRINTF_P("string with argument %d\n", arg), but it doesn't for calls like `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;
}

EDIT

I'm referring only to the case of string literals, not char *.

CodePudding user response:

I'm not sure why you should use a macro at all.

Just write an encapsulating function using vprintf and variable args.

IDEOne Link

#include <stdarg.h>
int prefix_printf(const char* fmt, ...)
{
    printf("prefix ");                // Print desired Prefix

    va_list args;                     // Declare a variable for the "..."
    va_start(args, fmt);              // Initialize the variable arguments as after parameter "fmt"

    int result = vprintf(fmt, args);  // Version of printf that accepts args instead of ...
    va_end(args);                     // Clean up the var-args
    return result;                    // Return the same value printf would've returned
}


int main(void) {
    prefix_printf("No number\n");
    prefix_printf("Number = %d\n", 20);
    return 0;
}

Result:

Success #stdin #stdout 0.01s 5536KB
prefix No number
prefix Number = 20

CodePudding user response:

It is as easy as:

#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;
}
  • Related