I have such pretty little code:
//example1
namespace
{
int a;
}
int a;
main()
{
a++;
return 0;
}
Of course, g++ 4.6.1 compiler can't compile it and outputs an error:
./temp.cpp: In function ‘int main()’:
./temp.cpp:10:5: error: reference to ‘a’ is ambiguous
./temp.cpp:6:5: error: candidates are: int a
./temp.cpp:2:9: error: int {anonymous}::a
It's all right!
But when I delete the reference to variable "a" within "main" function, the program is being compiled well:
//example2
namespace
{
int a;
}
int a;
main()
{
return 0;
}
1) Why does the g++ compiler allows the definition of variable "a", when in such case it disallows the references to it?
2) Is it just the g++ compiler's feature, and no other compiler is able to compile such code (example2)?
3) Does the g++ compiler have corresponding flags to interpret such code (example2) as faulty?
Thanks a lot for everyone!
The second example is valid because you can still access the global a
from outside that translation unit.
The a
in the anonymous namespace provides a definition for a variable that has internal linkage. The a
at global namespace scope is a definition for a variable with external linkage. You can declare a extern int a;
in a different translation unit and use it.