11

When the C printf() and its family is compiled by gcc and -Wall is used on command line, the compiler warns about misplaced arguments according to the format string that is being used. As an example the code below would get an error message saying the format specified 3 arguments but actually you have only passed in two.

printf("%d%d%d", 1, 2);

When writing a wrapper to the printf(), how do you keep this capability? A form of function or a macro would be what I can think about. But simple parsers could be acceptable too.

A few ways of writing a printf wrapper can be found on the stackoverflow. Two common approaches are using vprintf with varargs, and using __builtin_apply. I've tried these two approaches, none worked.

Community
  • 1
  • 1
minghua
  • 5,981
  • 6
  • 45
  • 71

1 Answers1

11

You can use gcc format function attribute in order to check the parameters against the format string.

extern int my_printf (void *my_object, const char *my_format, ...)
           __attribute__ ((format (printf, 2, 3)));

Check the gcc manual "6.31.1 Common Function Attributes"

Picodev
  • 506
  • 4
  • 8
  • 2
    a note if `my_printf` is a class member: add 1 to the argument numbering. it would become `__attribute__ ((format (printf, 3, 4)));` – minghua May 12 '16 at 19:24