Search code examples
c++compiler-errorsdeclarationdefinitionredeclaration

C++ multiple declarations in a local scope


As far as I know, in C++ one can declare the same name multiple times, as far as it has the same type in all these declarations. To declare an object of type int, but NOT define it, the extern keyword is used. So the following should be correct and compile without errors:

extern int x;
extern int x; // OK, still declares the same object with the same type.
int x = 5;    // Definition (with initialization) and declaration in the same
              // time, because every definition is also a declaration.

But once I moved this to the inside of a function, the compiler (GCC 4.3.4) complains that I am redeclaring x and that it's illegal. The error message is the following:

test.cc:9: error: declaration of 'int x'
test.cc:8: error: conflicts with previous declaration 'int x'

where int x = 5; is in line 9, and extern int x is in line 8.

My question is:
If multiple declarations are not supposed to be errors, then WHY is it an error in this particular case?


Solution

  • An extern declaration declares something to have external linkage (meaning the definition is expected to appear at file scope in some compilation unit, possibly the current one). Local variables cannot have external linkage, so the compiler complains that you're trying to do something contradictory.