Search code examples
c++clinkage

Struct vs. Function Definitions in Scope


So, as far as I know, this is legal in C:

foo.c

struct foo {
   int a;
};

bar.c

struct foo {
    char a;
};

But the same thing with functions is illegal:

foo.c

int foo() {
    return 1;
}

bar.c

int foo() {
    return 0;
}

and will result in linking error (multiple definition of function foo).

Why is that? What's the difference between struct names and function names that makes C unable to handle one but not the other? Also does this behavior extend to C++?


Solution

  • Why is that?

    struct foo {
       int a;
    };
    

    defines a template for creating objects. It does not create any objects or functions. Unless struct foo is used somewhere in your code, as far as the compiler/linker is concerned, those lines of code may as well not exist.

    Please note that there is a difference in how C and C++ deal with incompatible struct definitions.

    The differing definitions of struct foo in your posted code, is ok in a C program as long as you don't mix their usage.

    However, it is not legal in C++. In C++, they have external linkage and must be defined identically. See 3.2 One definition rule/5 for further details.