0

I received a double definition error from the linker in a larger project I'm working on. I was surprised to see that I was allowed to accidentally include an initializer together with extern.

The following compiles, but I did not expect it to.

extern int var{3}; // declaration or definition?

//int var{3};

int main()
{
    int varb = var;
    return 0;
}

I would expect extern to specify that a variable is only being declared, not defined, yet if I add an initializer, does it then become defined, why?

I have looked at the following questions, but they don't explain to me why this is allowed.

The second answer does clarify the following:

a declaration is a definition unless it contains the extern keyword without an initializer or function body

So the specification does indicate that this should then be a definition, but why? Does that mean that the following two lines mean exactly the same thing?

extern int var{3};
int var{3};
Community
  • 1
  • 1
wally
  • 10,717
  • 5
  • 39
  • 72
  • Like it says, extern with an initializer is a declaration and a definition. It declares the var symbol as extern, and defines var as {3} in the same compilation unit. –  Apr 22 '16 at 15:59
  • @Rei So it has external linkage and then links to itself? Does that change anything? – wally Apr 22 '16 at 16:05
  • 1
    external linkage means the symbol is undefined until linking stage. In this case, you define it in the same compilation unit, so it basically does nothing. –  Apr 22 '16 at 16:06
  • 1
    http://stackoverflow.com/a/8069831/560648 – Lightness Races in Orbit Apr 22 '16 at 16:35

0 Answers0