Why is it an issue when an object defined in the file scope has the same name as an existing namespace? Why is this ok in the function scope (e.g. inside main)?
Example:
#include <iostream>
namespace foo {
class Foo {};
}
namespace bar {
class Bar {};
}
// foo::Foo foo; // <-- This will give error
int main () {
bar::Bar bar; // <-- This is ok
std::cout << "Program ran successfully" << std::endl;
return 0;
}
The error I get is
ns_main.cpp:11:10: error: ‘foo::Foo foo’ redeclared as different kind of symbol
foo::Foo foo;
^
ns_main.cpp:3:15: error: previous declaration of ‘namespace foo { }’
namespace foo {
This situation is quite easy to achieve if a lot of files are included where a lot of different namespaces have been defined.
Can someone explain this? Thanks! Cheers
The same identifier can be declared and used in different, possibly nested scopes, but not in the same one. Your problem has nothing to do with the fact that the namespaces are defined at file scope. Moving them into another namespace
outer
does not solve the error:The variable
bar
inbar::Bar bar;
however belongs to another, more local scope than the namespacebar
. The variablefoo
infoo::Foo foo;
and the namespacefoo
are in the exact same scope.As most of your variables and namespaces should not not be declared in global/file scope, having many namespaces is not a problem at all.