我知道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>

其他回答

extern的正确解释是,你告诉编译器一些东西。你告诉编译器,尽管现在不存在,但声明的变量将以某种方式被链接器找到(通常在另一个对象(文件)中)。链接器将幸运地找到所有内容并将其组合在一起,无论是否有一些外部声明。

添加extern将变量定义转换为变量声明。关于声明和定义之间的区别,请参阅本线程。

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

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

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>