cgccgcc-extensionsgcc-pedantic

Why does this gcc -pedantic ignore an extension?


The gcc warning options document says the -pedantic option is supposed to give warnings for forbidden extensions out of strict ISO C.

However, when I compile the following code with my gcc version 9.4.0 with -pedantic only, it warns nothing.

#include <stdio.h>
int main(void) {
    int foo;
    typeof(foo) bar = 42;
    printf("%d\n", bar);
}

I thought gcc would catch typeof() as an error since it is a gcc extension and not a part of the C17 standard. Only when both -pedantic and -std=c17 were set, instead of the default -std=gnu17, I could find desired warnings ("implicit declaration of function ‘typeof’").

How does exactly -pedantic work? Is it being "weakly pedantic" without specifying an ISO C version?


Solution

  • -pedantic (like any other gcc option) is not documented well/does not behave like the documentation claims. And therefore behaves in fickle ways. The documentation claims:

    Where the standard specified with -std represents a GNU extended dialect of C, such as ‘gnu90’ or ‘gnu99’, there is a corresponding base standard, the version of ISO C on which the GNU extended dialect is based. Warnings from -Wpedantic are given where they are required by the base standard.

    Clearly this is not so. In ISO C17, typeof(foo) is some sort of macro or function call and needs to be defined in advance or otherwise the code should not pass compilation silently. Only using -pedantic gives an error diagnostic for this strictly conforming C17 code:

    #include <stdio.h>
    int main(void) {
        int typeof = 0;
    }
    

    As you noticed, specifying -std=c17 etc makes the compiler fall in line, so the gcc documentation about -pedantic following a "base standard" (ISO C17) is clearly incorrect/outdated. Perhaps this was once the case back in the C89 days or so.

    Note that newer versions of gcc also struggle with diagnostics even in strict mode in many cases, so using these compiler options are by no means a guarantee that your code is conforming C.