Saturday, February 19, 2022

[SOLVED] How can printf issue a compiler warning?

Issue

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?


Solution

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 10...) 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 your GCC plugin



Answered By - Basile Starynkevitch
Answer Checked By - Mildred Charles (WPSolving Admin)