简体   繁体   English

extern 在 C++ 中如何工作?

[英]How does extern work in c++?

This is from the <iostream> :这是来自<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?似乎通过使用extern定义在其他命名空间中的数据类型将可用?

extern means "these variables are defined in some other compilation unit (.cpp or .lib file)" extern表示“这些变量是在其他一些编译单元(.cpp 或 .lib 文件)中定义的”

In this case, you #include <iostream> into your .cpp file, and because cin and cout are declared as extern , the compiler will let you use them without complaining.在这种情况下,您将#include <iostream>放入您的 .cpp 文件中,并且因为cincout被声明为extern ,编译器会让您毫无怨言地使用它们。 Then, when the linker runs, it looks up all of the extern variables and sorts it all out.然后,当链接器运行时,它会查找所有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). extern用于引用在不同编译单元中定义的变量(目前,您可以将编译单元视为 .cpp 文件)。 The statements in your example declare rather than define cin and cout .您示例中的语句声明而不是定义cincout It is telling the compiler that the definition of these objects is found in another compilation unit (where they are not declared as extern ).它告诉编译器这些对象的定义是在另一个编译单元中找到的(它们没有被声明为extern )。

不,这是声明cincout而不实际定义它们的明确方式。

The extern keyword tells the compiler that a variable is declared in another source(ie outside the current scope). extern关键字告诉编译器在另一个源中(即在当前作用域之外)声明了一个变量。 The linker then finds this actual declaration and sets up the extern variable to point to the correct location.然后链接器找到这个实际声明并设置extern变量以指向正确的位置。

variables declared by extern statements will not have any space allocated for them, as they should be properly defined elsewhere.extern语句声明的变量不会为它们分配任何空间,因为它们应该在别处正确定义。 If a variable is declared extern , and the linker finds no actual declaration of it, it will show error.如果变量被声明为extern ,并且链接器没有发现它的实际声明,它将显示错误。

Eg.例如。 extern int i;外部内部我;

//this declares that there is a variable named i of type int, defined somewhere in the program. //这声明有一个名为 i 的 int 类型变量,在程序中的某处定义。

Some answers say here that extern means that variable is defined in other compilation unit.有些答案在这里说 extern 意味着变量是在其他编译单元中定义的。 Then, following should not compile as no other compilation unit or file is provided to compiler.然后,以下不应编译,因为没有其他编译单元或文件提供给编译器。

extern int a;
int main(){
    std::cout<<a<<std::endl;    //Prints 3
}
int a=3;

So, I think extern is explicitly used to separate the declaration and definition in case of variable as stated in one of answer.因此,我认为 extern 明确用于将声明和定义分开,如答案之一所述。 I think it is useless in case of functions.我认为在函数的情况下它是无用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM