John Friendson
John Friendson

Reputation: 87

Cannot declare global variable with the name of a struct

Struct members can use the same name as a type, but it appears that global variables cannot. Does anyone know why? I am using MinGW-64, an implementation of GNU C.

typedef struct foo{

}foo;

foo foo;

int main()
{

}

Thanks!

Upvotes: 1

Views: 271

Answers (2)

adrian
adrian

Reputation: 1457

When compiled with gcc, this error is produced:

test.c:5:5: error: ‘foo’ redeclared as different kind of symbol
 foo foo;

This is the issue. The statement foo foo; tries to re-declare the symbol foo as a variable when it has already been declared to refer to struct foo. You can fix your issue by changing the name of the variable to something else.

Upvotes: 0

The issue here is fairly simple. You cannot redefine the meaning of a name in the same scope it is defined. To contrast, this would be valid

typedef struct foo{
  char c;
}foo;

int main()
{
    foo foo;
}

Following the declaration in the scope of main, the meaning of foo is altered. But when you do it in the same scope as the type alias, you are basically providing conflicting definitions.

Struct fields aren't in the scope of the type definition itself. So that's why those don't conflict either.

Upvotes: 1

Related Questions