Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get warnings of incorrect string formatting (C++)

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.

like image 310
orion elenzil Avatar asked Feb 08 '10 18:02

orion elenzil


People also ask

How do I show all warnings in GCC?

GCC 4.3+ now has -Q --help=warnings , and you can even specify --help=warnings,C to just print out the C related warnings.

What is Werror?

-Werror= Make the specified warning into an error. The specifier for a warning is appended; for example -Werror=switch turns the warnings controlled by -Wswitch into errors.

What are warnings C++?

Compiler warnings are messages produced by a compiler regarding program code fragments to be considered by the developer, as they may contain errors. Unlike compilation errors, warnings don't interrupt the compilation process.


1 Answers

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.

like image 67
Paul R Avatar answered Oct 24 '22 18:10

Paul R