0

I know a variable with initialization is a definition no matter if it is extern. However, since extern int x=1; is a definition, why doesn't the compiler throw redefinition error running the following code?

//ok,no error
int x;
extern int x=1;
int main()
{
}

//however,this is an error
extern int x=1;
int x;
int main()
{
}

Why can this happen? Is there any difference?

Update:You are right.When I compile with VS 2013,there is no error.Now I tried with gcc on linux and got an redefinition error just as I expected.

Just as @Bo Persson said,it's all about tentative definition in C. And when I change the file suffix to .c, gcc takes it as a warning rather than an error and it can be compiled.

lionel
  • 415
  • 1
  • 5
  • 14
  • They are both errors. –  Feb 27 '17 at 12:23
  • first throws error, too: http://coliru.stacked-crooked.com/a/99912d81a14f3a04 – pergy Feb 27 '17 at 12:24
  • In the C language you have a [Tentative definition](http://stackoverflow.com/questions/3095861/about-tentative-definition). Perhaps the compiler allows this in C++ a well, for compatibility reasons. – Bo Persson Feb 27 '17 at 12:33

1 Answers1

0

Firstly, both of your snippets are ill-formed - please use a modern compiler to try them out.

When declaring a variable in global scope, it is automatically zero-initialized. This is the reason you're getting a redefinition error - x is already defined to zero.

The following snippet will compile:

extern int x;
int x;
int main()
{
}
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416