课堂有外部联系吗? [英] Do classes have external linkage?

查看:111
本文介绍了课堂有外部联系吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个文件A.cpp和B.cpp,它们看起来像

I have 2 files A.cpp and B.cpp which look something like

A.cpp
----------
class w
{
public:
    w();
};


B.cpp
-----------
class w
{
public:
    w();
};

现在我在某处阅读(

Now I read somewhere (http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr082.htm) that classes have external linkage. So while building I was expecting a multiple definition error but on the contrary it worked like charm. However when I defined class w in A.cpp, I got the redefinition error which makes me believe that classes have internal linkage.

我在这里错过了什么吗?

Am I missing something here?

推荐答案

外部链接 表示在整个程序中都可以访问该符号(函数或全局变量),并且 内部链接 表示只能在一个翻译单元中访问它.您可以使用extern和static关键字显式控制符号的链接,对于非const符号,默认链接为extern;对于const符号,默认链接为static(内部).

External linkage means the symbol (function or global variable) is accessible throughout your program and Internal linkage means that it's only accessible in one translation unit. you explicitly control the linkage of a symbol by using the extern and static keywords and the default linkage is extern for non-const symbols and static (internal) for const symbols.

具有外部链接的名称表示可以通过在同一翻译单位的相同范围内或在其他翻译范围内(与内部链接一样)或在其他翻译单元中另外声明的名称来引用实体.

A name with external linkage denotes an entity that can be referenced via names declared in the same scope or in other scopes of the same translation unit (just as with internal linkage), or additionally in other translation units.

该程序实际上违反了 一个定义规则 ,但实际上编译器很难检测到错误,因为它们位于不同的编译单元中.甚至链接器似乎也无法将其检测为错误.

The program actually violates the One Definition Rule but it is hard for the compiler to detect the error, because they are in different compilation units. And even the linker seems cannot detect it as an error.

C ++允许通过使用 命名空间来绕过一个定义规则.

C++ allows a workaround to bypass the One Definition Rule by making use of namespace.

[UPDATE] 来自C ++ 03 Standard
§3.2一种定义规则,第5节规定:

[UPDATE] From C++03 Standard
§ 3.2 One definition rule, section 5 states:

程序中的类类型定义可以有多个,只要每个定义出现在不同的翻译单元中,并且这些定义满足以下要求.给定一个在多个翻译单元中定义的名为D的实体,则D的每个定义都应包含相同的令牌序列.

这篇关于课堂有外部联系吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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