C++ 中 "extern" 语句的确切含义是什么?

What is the exact meaning of the "extern" statement in c++?

本文关键字:是什么 extern 语句 C++      更新时间:2023-10-16

我只想知道"extern"语句在c ++中的用途,以及何时/为什么使用它?
谢谢。

是一个很好的解释: http://msdn.microsoft.com/en-us/library/0603949d.aspx

基本上它指定存储 - 带有"extern"关键字的声明指定变量具有外部链接 - 它在当前上下文中不需要存储空间,并且将在没有extern修饰符的某个或其他单元中定义,如果不这样做,将变成关于缺少引用的链接器错误, 因为已经被告知有一个变量不存在。例如,库和多个客户端之间的共享项目,在标头中声明extern,以便客户端知道它,但存储实际上在库中,以便在访问它时,它们使用正确的值,而不是在包含声明文件的单元内分配存储空间的值。例如

Some header:
...
extern int dummy; // tells the unit that there is an integer dummy with storage speace somewhere else
...
dummy = 5; // actually changes the value defined in some other cpp file in the library
Some cpp file in the library:
...
int i; // references to i if not shadowed by other declarations reference this value

这意味着变量是这个编译单元的外部,即它已经在不同的编译单元中声明。

它将搜索该变量的已初始化。

如果全局声明了 extern 变量或函数,那么它的可见性将贯穿整个程序,其中可能包含一个文件或多个文件。例如,考虑一个c程序,它写入了两个名为one.c和two.c的文件:

/

/one.c

#include<conio.h>
int i=25; //By default extern variable
int j=5;  //By default extern variable
/**
Above two line is initialization of variable i and j.
*/
void main(){
    clrscr();
    sum();
    getch();
}
/

/two.c

#include<stdio.h>
extern int i; //Declaration of variable i.
extern int j; //Declaration of variable j.
/**
Above two lines will search the initialization statement of variable i and j either in two.c (if initialized variable is static or extern) or one.c (if initialized variable is extern) 
*/
void sum(){
    int s;
    s=i+j;
    printf("%d",s);
}

同时编译并执行上述两个文件 one.c 和 two.c

extern声明某些内容会告诉编译器它在解决方案中的其他地方声明,因此它不会抱怨它是未定义的或多次定义的。