我只想知道“extern”语句在 c++ 中的用途,以及何时/为什么使用它?
谢谢。
问问题
1525 次
4 回答
1
这是一个很好的解释: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
于 2013-09-20T11:02:20.283 回答
1
这意味着该变量在此编译单元之外,即它已在不同的编译单元中声明。
于 2013-09-20T11:04:09.237 回答
0
它将搜索该变量的已经初始化。
如果全局声明了一个外部变量或函数,那么它的可见性将整个程序可能包含一个文件或多个文件。例如,考虑 ac 程序,它写入了两个名为 one.c 和 two.c 的文件:
//一个.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();
}
//两个.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
于 2013-09-20T11:05:38.523 回答
-1
声明某事extern
告诉编译器它是在解决方案的其他地方声明的,因此它不会抱怨它未定义或多次定义。
于 2013-09-20T10:56:02.367 回答