-->

为什么声明一个外部变量中的main()的作品,但不能确定它里面的main()呢?(Why does

2019-09-02 08:19发布

这似乎很微不足道,但对于以下行为有点严谨的解释将有助于我的理解extern一个lot.So我会感激你的答案。

在下面的示例程序,我宣布一个extern变量x的一个函数里( main()现在,如果我之后在文件范围内定义变量main()并指定8到它,则程序工作正常, 8如果我定义该变量printed.But x内部main()的后printf() ,期待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存储class.Rest我不understand.Can你告诉我下面的:

1)为什么我们允许申报extern在函数内部变量,没有任何警告或错误?如果有效,究竟是什么意思呢?

2)由于我们宣布xextern在函数内部并没有表现出错误的,为什么后来这个声明不链接到函数内部的变量的定义,但看起来外,当变量定义之外? 相互矛盾的存储类声明auto-vs-extern这样做的原因?

Answer 1:

extern变量声明为编译器会有一个全局变量别的地方的定义的承诺。 局部变量没有资格作为承诺编译器的应验,因为他们是不可见的连接体。 从某种意义上说, extern声明是类似转发的函数的声明:你说的编译器“我知道这个功能是存在的,所以让我现在使用它,并让连接带定位在实际执行的照顾”。



Answer 2:

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

答: - 我们可以在功能层面使用的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?

答:在块范围(即局部变量)声明的变量没有关联,除非明确decalred为extern。



Answer 3:

只记得这个概念,当我们声明一个变量的函数内的extern我们只能把它定义该函数之外。



Answer 4:

没有人使用的extern这个样子。 EXTERN通常用于大项目,很多的.c的,.h文件,需要共享一些变量。 在这种情况下,编译往往无法解决变量声明(也许,这是对一些h文件尚未编译它),然后在“外部”是用来告诉compilar离开它现在并着手编制,这件事情将被处理链接阶段。



文章来源: Why does declaring an extern variable inside main() works,but not defining it inside main() as well?