How can printf issue a compiler warning?

2020-08-19 07:05发布

问题:

I was wondering how can a function issue a compile-time warning?

This came to my mind because when we supply wrong format specifier in the first argument of printf (scanf) for the variable matched with that type specifier and compile with gcc with -Wall option on, compiler issues a warning.

Now, printf and scanf are regularly implemented variadic functions as I understand and I dont know any way to check the value of the string at the compile-time, let alone issue a warning if something doesnt match.

Can someone explain me how I get compiler warning then?

回答1:

Warnings are implementation (i.e. compiler & C standard library) specific. You could have a compiler giving very few warnings (look into tinycc...), or even none...

I'm focusing on a recent GCC (e.g. 4.9 or 5.2...) on Linux.

You are getting such warnings, because printf is declared with the appropriate __attribute__ (see GCC function attributes)

(With GCC you can likewise declare your own printf-like functions with the format attribute...)

BTW, a standard conforming compiler is free to implement very specially the <stdio.h> header. So it could process #include <stdio.h> without reading any header file but by changing its internal state.

And you could even add your own function attributes, e.g. by customizing your GCC with MELT



回答2:

How can printf issue a compiler warning?

Some compilers analyze the format and other arguments type of printf() and scanf() at compile time.

printf("%ld", 123);  // type mis-match  `long` vs. `int`
int x;
printf("%ld", &x);  // type mis-match 'long *` vs. `int *`

Yet if the format is computed, then that check does not happen as it is a run-time issue.

const char *format = foo();
printf(format, 123);  // mis-match? unknowable.


标签: c gcc printf scanf