17

apologies in advance if i use poor terminology.

when i compile a C++ app under gdb and use printf() it gives me awesome warnings relating to the consistency of the format string and the arguments passed in.

eg, this code:

printf("%s %s", "foo");

results in a compiler warning "too few arguments for format", which is super-useful. it will also give warnings about format string type vs. argument type. it must have inspected the format string and compared that against the supplied argument types. - is this sort of compile-time introspection something which can be added to ordinary source code, or is it something which needs to be compiled into gcc itself ?

fwiw this is under gcc 4.2.1 on os x.

ideasman42
  • 42,413
  • 44
  • 197
  • 320
orion elenzil
  • 4,484
  • 3
  • 37
  • 49

1 Answers1

12

You can do stuff like this for your own printf-like functions (as well as for scanf/strftime/strfmon-like functions):

#define PRINTF_FORMAT_CHECK(format_index, args_index) __attribute__ ((__format__(printf, format_index, args_index)))

void my_printf(const char *fmt, ...) PRINTF_FORMAT_CHECK(1, 2);

See the gcc manual for further details.

Paul R
  • 208,748
  • 37
  • 389
  • 560
  • 3
    There are a bunch of other options in the manual; they can't be enough to cover the general case of all variadic functions though. – Carl Norum Feb 08 '10 at 18:47
  • 2
    huh; nifty. thanks Paul. from the man page: "The format attribute specifies that a function takes printf, scanf, strftime or strfmon style arguments which should be type-checked against a format string" so it looks like if i have my own nutty constraints (eg something other than the printf- family of functions) this wouldn't really do the trick, but there's a whole bunch of other interesting __attributes__ in the page you linked to. thanks ! – orion elenzil Feb 08 '10 at 20:19
  • Awesome. Anyone know if the Intel C compiler has something similar? I couldn't find anything in the manual. – pavon Sep 26 '14 at 17:37
  • @pavon: I *think* ICC may support this also, but I can't easily check right now - give it a try - it either supports it or just silently ignores it, but I'm not sure which. – Paul R Sep 26 '14 at 18:35