c ++ 11多个定义不是odr使用? [英] c++11 multiple definitions not odr-used?

查看:245
本文介绍了c ++ 11多个定义不是odr使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的C ++ 11程序:

Consider the following C++11 program:

翻译单元#1:

int x = 3;

int main() {}

翻译单元# p>

translation unit #2:

int x = 4;

这个程序是否错误?为什么/为什么不?

Is this program ill-formed? Why / why not?

gcc抱怨:

error: multiple definition of `x'

我可以看到的唯一相关规则是3.2.4: p>

The only relevant rule I can see is in 3.2.4:


每个程序必须包含每个非内联函数或在该程序中使用odr的变量的一个定义

Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program

但是 x 在程序中不是odr。 (或者是?)

But x isn't odr-used in the program. (or is it?)

这是一个gcc错误吗?

Is this a gcc bug? Or am I missing something in the standard?

推荐答案

这不是一个gcc错误,而是标准的行为。

It is not a gcc bug, but standard behavior.

实际上, int x; 定义了一个符号,如果定义两次或更多,会导致链接器错误。

Practically speaking, int x; defines a symbol which leads to a linker error if defined twice or more.


两个相同的名称(第3条)如果

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

,这两个名称都具有外部链接,或者两个名称都具有内部链接和相同的变量,函数,类型,枚举,模板或命名空间在同一翻译单元中声明;和

— both names have external linkage or else both names have internal linkage and are declared in the same translation unit; and

- 这两个名称是指同一命名空间的成员或同一类的成员而不是继承的成员;和

— both names refer to members of the same namespace or to members, not by inheritance, of the same class; and

- 当两个名称表示函数时,函数的参数类型列表(8.3.5)是相同的;和

— when both names denote functions, the parameter-type-lists of the functions (8.3.5) are identical; and

- 当两个名称都表示函数模板时,签名(14.5.6.1)是相同的。

— when both names denote function templates, the signatures (14.5.6.1) are the same.

这篇关于c ++ 11多个定义不是odr使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆