Struct vs. Function Definitions in Scope

  • A+

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


struct foo {    int a; }; 


struct foo {     char a; }; 

But the same thing with functions is illegal:


int foo() {     return 1; } 


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++?


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 not that there is a difference in how C and C++ deal with incompatible struct defintions.

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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: