错误:"i"的外部声明在没有链接的声明之后 [英] error: extern declaration of 'i' follows declaration with no linkage
问题描述
在以下程序中,我认为 extern int i;
会将以下 i
更改为引用 i之外定义的
: i
>主要
#include< stdio.h>extern int i = 1;//警告:"i"已初始化并声明为"extern"int main(){int i = 2;printf(%d \ n",i);外部诠释//错误:外部声明"i"跟随声明而没有链接printf(%d \ n",i);返回0;}
错误:'i'的外部声明跟随没有链接的声明"的原因是什么,其中没有链接的声明"是指 int i = 2;
?>
在删除 main
中的 int i = 2
后,
- 错误消失了,
-
extern int i = 1;
上的警告警告:'i'已初始化并声明为'extern'" 也消失了.为什么会这样?
谢谢您的解释!
一旦您在 main
函数中将一个名为 i
的变量定义为 i 文件范围内的code>被屏蔽,无法访问(除非您具有其地址).
当您以后添加声明 extern int i
时,这与在相同范围内名为 i
的局部变量冲突,因为局部变量无法具有外部链接.它没有不授予您访问全局 i
的权限.
当删除本地 i
时, extern int i
声明与文件范围内的定义匹配,因此没有错误.至于 extern int i = 1;
上的警告,在gcc 4.1.2上对我来说 not 并没有消失,所以这取决于编译器.
In the following program, I thought that extern int i;
will change the following i
to refer to the i
defined outside main
:
#include <stdio.h>
extern int i=1; // warning: 'i' initialized and declared 'extern'
int main()
{
int i=2;
printf("%d\n", i);
extern int i; // error: extern declaration of 'i' follows declaration with no linkage
printf("%d\n", i);
return 0;
}
What is the reason of the "error: extern declaration of 'i' follows declaration with no linkage", where "declaration with no linkage" refers to int i=2;
?
After I remove int i=2
in main
,
- the error is gone,
- the warning "warning: 'i' initialized and declared 'extern'" on
extern int i=1;
also disappear . Why is that?
Thank you for explanations!
Once you define a variable named i
inside your main
function, the i
at file scope is masked and cannot be accessed (unless you have its address).
When you later add the declaration extern int i
, this conflicts with the local variable named i
at the same scope since locals can't have external linkage. It does not give you access to the global i
.
When you remove the local i
, the extern int i
declaration matches up with the definition at file scope, so there is no error. As for the warning on extern int i=1;
, that did not go away for me on gcc 4.1.2, so that depends on the compiler.
这篇关于错误:"i"的外部声明在没有链接的声明之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!