我知道C中的全局变量有时有extern关键字。什么是extern变量?申报是什么样的?它的范围是什么?

这与跨源文件共享变量有关,但这究竟是如何工作的呢?我在哪里使用extern?


当前回答

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>

其他回答

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,符号将由链接器解析。

如果不将其声明为extern,则会得到两个名称相同但完全不相关的变量,并且变量的多个定义存在错误。

走读生 允许程序的一个模块访问程序的另一个模块中声明的全局变量或函数。 通常在头文件中声明extern变量。

如果你不想让一个程序访问你的变量或函数,你可以使用static,它告诉编译器这个变量或函数不能在这个模块之外使用。

Extern关键字与变量一起使用,以将其标识为全局变量。

它还表示可以使用使用extern声明的变量 关键字在任何文件中,尽管它在其他文件中声明/定义。

Extern的使用使得一个first.c文件可以完全访问另一个secondc文件中的全局参数。

extern可以在first.c文件中声明,也可以在first.c包含的任何头文件中声明。