c++11 多个定义未使用 odr?

标签 c++ gcc c++11

<分区>

考虑以下 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; 定义了一个符号,如果定义了两次或更多次,该符号会导致链接器错误。

C++ standard 3.5 (9)

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) 相同。

关于c++11 多个定义未使用 odr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18547537/

相关文章:

gcc - 错误 : bad value for -march= switch

c++ - 模板推导失败,参数包后有参数

python - 在python中使用 "using std::vector"时SWIG参数错误

c++ - C语言编译堆栈程序时出现错误信息

c++ - Visual Studio C++ 异常......怪异

c - 优化时,在现代编译器中使用 `register` 关键字是否无用?

c - 如何在 gcc linux 中编译多个 .c 和 .h 文件?

c++ - C++11 中的静态局部变量?

Linux 中的 C++ 线程

c++ - 如何区分这两个插入函数