Reputation:
I'm writing a compiler and I want to implement the type check in printf
:
printf("%f", i);
warning: format specifies type 'double' but the argument has type 'int' [-Wformat]
printf("%f", 1);
~~ ^~
%d
As you can see, gcc knows what does %f mean, and try to warn me about the type mismatching.
So how I can implement this?
P.S. Is there any chance there are no mysteries, just a special rule gcc write for printf?
Upvotes: 2
Views: 1140
Reputation: 107769
It's a combination of two special rules, described in the documentation of -Wformat
.
The printf
function is built in, which allows GCC both to optimize it and to warn about its misuse. About the specific case of printf
, there's a note in the documentation:
In addition, when a function is recognized as a built-in function, GCC may use information about that function to warn about problems with calls to that function, or to generate more efficient code, even if the resulting code still contains calls to that function. For example, warnings are given with
-Wformat
for bad calls toprintf
whenprintf
is built in andstrlen
is known not to modify global memory.
In addition, you can declare your own functions as printf-like for warning purposes with the format
attribute.
__attribute__((__format__(__printf__, 2, 3))) /*printf-like function, the format string is parameter 2, the first element is parameter 3*/
int myprintf(int stuff, const char *format, ...);
With a built-in function, GCC tries to replace the function call by something more efficient. For printf
, this generally means that when the format argument is a string literal, GCC replaces it by a series of calls to print the individual elements. For example it's likely to compile printf("%d %s\n", x, s);
as if the program contained __some_internal_function_to_print_a_dcimal_integer__(x); putc(' '); puts(s);
. While the compiler is performing this optimization, it'll notice any mismatch between the format string and the argument types and warn accordingly. If the function isn't built in but has a format
attribute, you just get the warnings.
Upvotes: 2