Search code examples
cgccstructwarningsdefinition

Why no GCC warning for re-definition of struct in C?


main.h
struct tagname {
     int m1;
     int m2;
};

main.c
#include "main.h"

int main(void) {
    
    struct tagname d1;
    d1.m1 = 7;

    struct tagname {
        float s1;
        float s2;
        float s3;
    };

    struct tagname e1;
    e1.s1 = 0;
}

I am using XC16 v1.60 (which I believe uses GCC v4.5.1 as the base) with -Wall, -Wextra, -Wshadow, and a host of other flags which I don't think are relevant, and I would have thought (hoped?) that the compiler would issue a warning here. What am I missing? Edit: Apologies, I have updated the question with the extra detail desired.


Solution

  • C allows new declarations of identifiers in new scopes. When you declare a function or start a compound statement with {, that starts a new scope. Iteration and selection statements also start new scopes. Inside a new scope, a new declaration of an identifier generally hides the previous declaration. Since this is legal C, the compiler allows this.

    In GCC 4.5.1, the documentation for -Wshadow says it warns “whenever a local variable shadows another local variable, parameter or global variable or whenever a built-in function is shadowed.” A structure tag is not a local variable or a built-in function.

    Incidentally, the return type of main should be int except in special situations; using int main(void) or int main(int argc, char *argv), not void main(void).