Вопрос

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.

Другие советы

Just because you can't reference the a in the anonymous namespace from main doesn't mean the code is invalid.

The a in the anonymous namespace can still be referenced from within the anonymous namespace.

The global a can be referenced from everywhere (you'd have to use ::a in main to remove the ambiguity).

The short answer is "because there's nothing illegal about it". It's just using a in main that is wrong. If you use ::a it will give you the global one (without the namespace).

And you can use a inside the namespace itself, e.g. we could have a function:

namespace {
   int a;

   int work_with_a()
   {
      a += 2;
      return a;
   }

}


int a;

int main()
{
   ::a++;

   int b = work_with_a();

   cout << ::a + b; 
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top