私の知る限り、C++ では、これらすべての宣言で同じ型を持っている限り、同じ名前を複数回宣言できます。type のオブジェクトを宣言するが、int
それを定義しない場合は、extern
キーワードが使用されます。したがって、以下は正しく、エラーなしでコンパイルされるはずです。
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.
x
しかし、これを関数の内部に移動すると、コンパイラ (GCC 4.3.4) は、再宣言していて違法であると不平を言います。エラーメッセージは次のとおりです。
test.cc:9: error: declaration of 'int x'
test.cc:8: error: conflicts with previous declaration 'int x'
whereint x = 5;
は 9 行目、extern int x
は 8 行目です。
私の質問は次のとおりです。
複数の宣言がエラーであると想定されていない場合、この特定のケースでエラーになるのはなぜですか?