C语言 为什么在main()中声明外部变量可以工作,但不能在main()中定义它?



这看起来很琐碎,但对以下行为进行一些严格的解释将有助于我对extern的理解。所以我很感谢你的回答。

在下面的示例程序中,我在函数(main())中声明了一个extern变量x。现在,如果我在main()之后的文件作用域中定义变量,并将8赋值给它,那么程序就可以正常工作,并且打印出8。但是,如果我在printf()之后的main()中定义变量x,期望extern声明链接到它,那么它会失败并给出以下错误:

test.c||In function 'main':|
test.c|7|error: declaration of 'x' with no linkage follows extern declaration|
test.c|5|note: previous declaration of 'x' was here|
||=== Build finished: 1 errors, 0 warnings ===|

#include<stdio.h>
int main()
{
extern int x;
printf("%d",x);
int x=8;   //This causes error
} 
//int x=8;   //This definition works fine when activated

我在代码中只看到一个错误,语句int x=8意味着我们再次将x声明为具有auto存储类的变量。休息我不明白。你能告诉我以下内容吗?

1)为什么允许在函数中声明extern变量,而没有任何警告或错误?如果有效,它到底意味着什么?

2)既然我们在函数内声明xextern并且它没有显示错误,那么为什么这个声明不链接到函数内变量的定义,而是在外部定义变量时向外看?冲突的存储类声明auto-vs-extern是这个原因吗?

extern变量声明是对编译器的一个承诺,即在其他地方会有全局变量的定义。局部变量不符合对编译器承诺的履行,因为它们对链接器是不可见的。从某种意义上说,extern声明类似于函数的前向声明:你对编译器说"我知道这个函数在那里,所以让我现在使用它,让链接器负责定位实际实现"。

请记住,当我们在函数内部声明一个变量为extern时,我们只能在该函数外部定义它。

Why are we allowed to declare an extern variable inside a function,without any warning or error?If valid,what exactly does it mean?

Ans:-我们可以在函数级使用extern,只在该函数的作用域内公开它。

Since we declared x as extern inside the function and it showed no error,why then this declaration doesn't link to the definition of the variable inside the function,but looks outside,when the variable is defined outside? Is conflicting storage-class declaration auto-vs-extern the reason for this?

Ans:在块作用域中声明的变量(即局部变量)没有链接,除非它们被显式声明为extern。

没有人这样使用extern。Extern通常用于大型项目,需要共享大量。c、。h文件和一些变量。在这种情况下,编译通常无法解析变量声明(也许,它是在一些尚未编译的.h文件上),然后使用"extern"告诉编译器暂时搁置它并继续编译,这件事将在链接阶段处理。

相关内容

最新更新