理解 c++ 中的 extern
namespace std
{
extern istream cin;
...
}
通过使用 extern
我们声明 cin
在其他单元中定义为 答案
但是如果istream
在std
中定义/未定义,应该会有一些区别,对吧?
编译器有什么区别?
namespace std
{
extern istream cin;
...
}
By using extern
we declare that cin
is defined in some other unit as the answer
But what if istream
is defined/undefined in std
,there should be some difference,right?
What is the difference for the compilor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译器不关心。如果未定义,链接器将无法将外部对象“链接”到真实对象。
The compiler does not care. The linker will fail to "link" the externed object to the real object if it is undefined.
编译器通常会给出一个错误,发现您正在使用 cin,但至少没有声明它。
使用 extern,您可以告诉编译器“简单,简单,相信我,在其他地方还有 istream 类 cin 的声明和定义。
然后链接器开始执行操作,并在调用与 cin 的使用之间建立链接并且对象本身是特别“待定”的,链接器必须将所有这些调用与其目的地结合起来,现在是 cin 是否存在(是否已编译)这一事实具有其重要性的时候。链接器提供的错误比编译器提供的错误要神秘得多,但探索它们很有趣,因为这是一种很好的学习方法,
例如,下面的代码片段不# 。 include cstdio 而不是 stdio.h,但我们知道 printf 会在那里,因为标准库总是与我们的程序链接的,它可以工作。
The compiler would normally give an error finding that you're using cin without having, at least, declaring it.
With extern, you can tell the compiler "easy, easy, trust me, there is somewhere else a declaration and a definition for a cin of class istream.
Then the linker jumps into action, and the link between the call to the uses of cin and the object itself are specially "pending". The linker has to unite all these calls with their destination, and now is when the fact of cin existing or not (has been compiled or not) has its importance. If not, then the linker fails. The errors provided by the linker are far more cryptic than the ones given by the compiler, but they are interesting to explore, because are a very good way to learn.
For example, the following piece of code does not #include cstdio not stdio.h, but we know that printf will be there, because the standard library is always linked with our program. Yes, it works.
编译器必须知道
istream
是一种类型,并且使用extern
关键字告诉它std::cin
存在并且属于该类型类型。如果编译器看到该行时 istream 尚未声明为类型,它会抱怨告诉您它不是类型。The compiler must know that
istream
is a type, and with theextern
keyword you are telling it thatstd::cin
exists and is of that type. ifistream
has not been declared as a type by the time the compiler sees the line, it will complain telling you that it is not a type.