extern 在 c++ 中如何工作?
这是来自
:
namespace std
{
extern istream cin; ///< Linked to standard input
extern ostream cout;
...
似乎通过使用 extern
在其他命名空间中定义的数据类型将可用?
This is from the <iostream>
:
namespace std
{
extern istream cin; ///< Linked to standard input
extern ostream cout;
...
It seems by using extern
the data types defined in other namespaces will just be available?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
extern
表示“这些变量在其他编译单元(.cpp 或 .lib 文件)中定义”。在这种情况下,您将
#include
放入 .cpp 中文件,并且由于cin
和cout
被声明为extern
,编译器将允许您使用它们而不会抱怨。然后,当链接器运行时,它会查找所有extern
变量并将其全部排序。extern
means "these variables are defined in some other compilation unit (.cpp or .lib file)"In this case, you
#include <iostream>
into your .cpp file, and becausecin
andcout
are declared asextern
, the compiler will let you use them without complaining. Then, when the linker runs, it looks up all of theextern
variables and sorts it all out.extern
用于引用在不同编译单元中定义的变量(目前,您可以将编译单元视为 .cpp 文件)。示例中的语句声明而不是定义cin
和cout
。它告诉编译器这些对象的定义可以在另一个编译单元中找到(它们未声明为extern
)。extern
is used to refer to a variable defined in a different compilation unit (for now, you can think of a compilation unit as a .cpp file). The statements in your example declare rather than definecin
andcout
. It is telling the compiler that the definition of these objects is found in another compilation unit (where they are not declared asextern
).不,这是一种明确的方式来声明
cin
和cout
是在没有实际定义的情况下声明的。No, this is an explicit way to say
cin
andcout
are declared without actually defining them.extern 关键字告诉编译器变量是在另一个源中声明的(即在当前作用域之外)。然后链接器找到这个实际的声明并设置 extern 变量以指向正确的位置。
extern 语句声明的变量不会为其分配任何空间,因为它们应该在其他地方正确定义。如果一个变量被声明为extern,并且链接器发现没有实际声明它,则会显示错误。
例如。 外部 int i;
//这声明有一个名为 i 的 int 类型变量,在程序中的某处定义。
The extern keyword tells the compiler that a variable is declared in another source(i.e outside the current scope). The linker then finds this actual declaration and sets up the extern variable to point to the correct location.
variables declared by extern statements will not have any space allocated for them, as they should be properly defined elsewhere. If a variable is declared extern, and the linker finds no actual declaration of it, it will show error.
Eg. extern int i;
//this declares that there is a variable named i of type int, defined somewhere in the program.
有些答案在这里说 extern 意味着变量是在其他编译单元中定义的。然后,以下不应编译,因为没有向编译器提供其他编译单元或文件。
因此,我认为 extern 被明确用于在变量的情况下分隔声明和定义,如答案之一所述。我认为对于函数来说它是没有用的。
Some answers say here that extern means that variable is defined in other compilation unit. Then, following should not compile as no other compilation unit or file is provided to compiler.
So, I think extern is explicitly used to separate the declaration and definition in case of variable as stated in one of answer. I think it is useless in case of functions.