为什么编译器接受模棱两可的变量定义

Why does the compiler accept an ambiguous variables definitions?

本文关键字:变量 定义 模棱两可 编译器 为什么      更新时间:2023-10-16

我有这么一小段代码:

//example1
namespace 
{
    int a;
}
int a;
main()
{
    a++;
    return 0;
}

当然,g++ 4.6.1编译器不能编译它并输出一个错误:

./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

没关系!

但是当我在main函数中删除对变量"a"的引用时,程序被编译得很好:

//example2
namespace 
{
    int a;
}
int a;
main()
{
    return 0;
}

1)为什么g++编译器允许定义变量"a",而在这种情况下它不允许引用它?

2)这只是g++编译器的特性,没有其他编译器能够编译这样的代码(example2)?

3) g++编译器是否有相应的标志来解释这些代码(example2)为错误?

非常感谢大家!

第二个例子是有效的,因为您仍然可以从翻译单元外部访问全局a

匿名命名空间中的a提供了具有内部链接的变量的定义。全局命名空间作用域中的a是具有外部链接的变量的定义。您可以在不同的翻译单元中声明extern int a;并使用它。

不能从main引用匿名命名空间中的a并不意味着代码无效。

匿名命名空间中的a仍然可以在匿名命名空间中被引用。

全局a可以从任何地方引用(您必须在main中使用::a来消除歧义)。

简短的回答是"因为这没有什么违法的"。它只是使用a在主要是错误的。如果您使用::a,它将为您提供全局名称(没有名称空间)。

你可以在命名空间本身使用a,例如我们可以有一个函数:

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

int a;
int main()
{
   ::a++;
   int b = work_with_a();
   cout << ::a + b; 
}