Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

c++ - How to get printf style compile-time warnings or errors

I would like to write a routine like printf, not functionally-wise, but rather I'd like the routine to have the same time compile check characteristics as printf.

For example if i have:

{
   int i;
   std::string s;
   printf("%d %d",i);
   printf("%d",s.c_str());
}

The compiler complains like so:

1 cc1plus: warnings being treated as errors
2 In function 'int main()':
3 Line 8: warning: too few arguments for format
4 Line 9: warning: format '%d' expects type 'int', but argument 2 has type 'const char*'

code example

Are printf and co special functions that the compiler treats differently or is there some trick to getting this to work on any user defined function? The specific compilers I'm interested in are gcc and msvc

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Different compilers might implement this functionality differently. In GCC it is implemented through __attribute__ specifier with format attribute (read about it here). The reason why the compiler performs the checking is just that in the standard header files supplied with GCC the printf function is declared with __attribute__((format(printf, 1, 2)))

In exactly the same way you can use format attribute to extend the same format-checking functionality to your own variadic functions that use the same format specifiers as printf.

This all will only work if the parameter passing convention and the format specifiers you use are the same as the ones used by the standard printf and scanf functions. The checks are hardcoded into the compiler. If you are using a different convention for variadic argument passing, the compiler will not help you to check it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...