C++ 中 "extern" 语句的确切含义是什么?
What is the exact meaning of the "extern" statement in c++?
我只想知道"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
声明某些内容会告诉编译器它在解决方案中的其他地方声明,因此它不会抱怨它是未定义的或多次定义的。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- C++避免重复声明的语法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- C++中名称篡改的目的是什么
- 在 c++ 中拥有一组结构的正确方法是什么?
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 派生类销毁的最佳实践是什么
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 通过JNI传递数据数组的最快方法是什么
- "using namespace std;"在C++的作用是什么?
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 文件系统:复制功能的速度秘诀是什么
- 视觉 "extern __forceinline "是什么 c++ 习语?
- CppUTest中extern关键字的替代方案是什么
- C++ 中 "extern" 语句的确切含义是什么?
- "extern PACKAGE TMyForm * MyForm"的含义是什么