c++clibc

-Werror=format: how can the compiler know


I wrote this intentionally wrong code

printf("%d %d", 1);

compiling with g++ and -Werror=format.

The compiler gives this very impressive warning:

error: format '%d' expects a matching 'int' argument [-Werror=format]

As far as I can see, there's no way the compiler can tell that the code is wrong, because the format string isn't parsed until runtime.

My question: does the compiler have a special feature that kicks in for printf and similar libc functions, or is this a feature I could use for my own functions? String literals?


Solution

  • As far as I can see, there's no way the compiler can tell that the code is wrong, because the format string isn't parsed until runtime.

    As long as the format string is a string literal, it can be parsed at compile time. If it isn't (which is usually a bad idea anyway), then you can get a warning about that from -Wformat-security.

    does the compiler have a special feature that kicks in for printf and similar libc functions?

    Yes.

    or is this a feature I could use for my own functions?

    Yes, as long as you're using the same style of format string as printf (or various other standard functions like scanf or strftime).

    void my_printf(Something, char const * format, SomethingElse, ...)
        __attribute__ ((format (printf,2,4)));
    

    to indicate that the second argument is a printf-style format string, and the values to format begin with the fourth. See http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html.