如何获取错误的字符串格式警告(C ++) [英] How to get warnings of incorrect string formatting (C++)
问题描述
当我使用gdb编译C ++应用程序并使用printf()时,请提前道歉。
例如,这段代码:
printf(%s%s, foo);
导致编译器警告格式的参数太少,这很有用。
还将给出有关格式字符串类型与参数类型的警告。
它必须检查格式字符串并将其与提供的参数类型进行比较。
-这种编译时自省的东西可以添加到普通的源代码中吗,还是需要将其编译为gcc本身?
在os x上这在gcc 4.2.1下。
您可以为自己的printf-like做类似的事情函数(以及用于scanf / strftime / strfmon之类的函数):
#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);
请参见 gcc手册以获取更多详细信息。
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.
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.
这篇关于如何获取错误的字符串格式警告(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!