考虑以下 C++11 程序:
翻译单元#1:
int x = 3;
int main() {}
翻译单元#2:
int x = 4;
这个程序格式错误吗?为什么/为什么不?
gcc 提示说:
error: multiple definition of `x'
我能看到的唯一相关规则是在 3.2.4 中:
Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program
但是 x
没有在程序中使用 odr。 (或者是吗?)
这是 gcc 错误吗?还是我遗漏了标准中的某些内容?
这不是 gcc 错误,而是标准行为。
实际上,int x;
定义了一个符号,如果定义了两次或更多次,该符号会导致链接器错误。
Two names that are the same (Clause 3) and that are declared in different scopes shall denote the same variable, function, type, enumerator, template or namespace if
——两个名字都有外部链接,或者两个名字都有内部链接,并且在同一个翻译单元中声明;和
——两个名称都指代同一命名空间的成员或指代同一类的成员,而不是通过继承;和
——当两个名字都表示函数时,函数的parameter-type-lists(8.3.5)相同;和
—当两个名称都表示函数模板时,签名 (14.5.6.1) 相同。