Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C | Handling multiple arguments in macro function

I am trying to make a function similar to printf(), I want it to take multiple arguments so that I can use them when printing, roughly like the following:

void PRINT_RED(string, ...) {
  fprintf(stderr, "\033[91m");
  fprintf(stderr, "%s", string, __va_arg_pack());
  fprintf(stderr, "\033[0m");
}

Take in consideration that I want it to have the following example API PRINT_RED("%s %s %d", string1, string2, int1);.

But as a macro, so I tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#define PRINT_RED(string, ...) \
  fprintf(stderr, "\033[91m"); \
  fprintf(stderr, "%s", string, __va_arg_pack()); \
  fprintf(stderr, "\033[0m");

And apparently __va_arg_pack() can only be defined in inline functions… Can anybody guide me on how to handle multiple arguments in a macro function?

>Solution :

What you’re looking for is the macro __VA_ARGS__, which translates to the variable arguments passed to a macro.

#define PRINT_RED(string, ...) \
  fprintf(stderr, "\033[91m"); \
  fprintf(stderr, "%s", string, __VA_ARGS__); \
  fprintf(stderr, "\033[0m");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading