cstructone-definition-rule

Are different translation units allowed to define structures with the same name?


Suppose I have a.c and b.c, which both define types called struct bar, with different definitions:

#include <stdio.h>

struct bar {
    int a;
};

int a_func(void) {
    struct bar b;
    b.a = 4;
    printf("%d\n", b.a);
    return b.a * 3;
}

 

#include <stdio.h>

struct bar { // same name, different members
    char *p1;
    char *p2;
};

void b_func(void) {
    struct bar b;
    b.p1 = "hello";
    b.p2 = "world";
    printf("%s %s\n", b.p1, b.p2);
}

In C, can these files both be linked together as part of a standards-conforming program?

(In C++, I believe this is forbidden by the One Definition Rule.)


Solution

  • Struct tags are identifiers with no linkage (C11 6.2.2/6)

    The rules about multiple definitions of identifiers with no linkage are found in 6.7/3:

    If an identifier has no linkage, there shall be no more than one declaration of the identifier (in a declarator or type specifier) with the same scope and in the same name space, except that:

    • a typedef name may be redefined to denote the same type as it currently does, provided that type is not a variably modified type;
    • tags may be redeclared as specified in 6.7.2.3.

    In your program, the two declarations of foo are in different scopes , so the condition "with the same scope" is not satisfied and therefore this rule is not violated.