我知道C中的全局变量有时有extern关键字。什么是extern变量?申报是什么样的?它的范围是什么?
这与跨源文件共享变量有关,但这究竟是如何工作的呢?我在哪里使用extern?
我知道C中的全局变量有时有extern关键字。什么是extern变量?申报是什么样的?它的范围是什么?
这与跨源文件共享变量有关,但这究竟是如何工作的呢?我在哪里使用extern?
当前回答
Extern关键字与变量一起使用,以将其标识为全局变量。
它还表示可以使用使用extern声明的变量 关键字在任何文件中,尽管它在其他文件中声明/定义。
其他回答
Extern关键字与变量一起使用,以将其标识为全局变量。
它还表示可以使用使用extern声明的变量 关键字在任何文件中,尽管它在其他文件中声明/定义。
Extern是用于声明变量本身驻留在另一个翻译单元中的关键字。
因此,您可以决定在一个转换单元中使用一个变量,然后从另一个转换单元访问它,然后在第二个转换单元中将其声明为extern,符号将由链接器解析。
如果不将其声明为extern,则会得到两个名称相同但完全不相关的变量,并且变量的多个定义存在错误。
Extern的使用使得一个first.c文件可以完全访问另一个secondc文件中的全局参数。
extern可以在first.c文件中声明,也可以在first.c包含的任何头文件中声明。
In C a variable inside a file say example.c is given local scope. The compiler expects that the variable would have its definition inside the same file example.c and when it does not find the same , it would throw an error.A function on the other hand has by default global scope . Thus you do not have to explicitly mention to the compiler "look dude...you might find the definition of this function here". For a function including the file which contains its declaration is enough.(The file which you actually call a header file). For example consider the following 2 files : example.c
#include<stdio.h>
extern int a;
main(){
printf("The value of a is <%d>\n",a);
}
example1.c
int a = 5;
现在,当你一起编译这两个文件时,使用以下命令:
步骤1)cc -o ex example.c 步骤2)。/交货
输出结果如下:a的值<5>
我喜欢把extern变量看作是你对编译器做出的承诺。
当遇到一个extern时,编译器只能找出它的类型,而不能找出它“居住”的位置,因此它不能解析引用。
你告诉它:“相信我。在链接时,这个引用将是可解析的。”