int main()
{
extern int i;
i=20;
printf("%d",i);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器给出一个错误,即'i'未定义
什么原因?
通过说extern你告诉编译器i在不同的翻译单元中定义,我猜你没有.C中的声明和定义之间存在差异.简而言之,前者告诉编译器变量的类型,后者告诉它为它分配存储.
extern现在就放弃它.
区别 :
1.int i; // i is defined to be an integer type in the current function/file
2.extern int i; // i is defined in some other file and only a proto-type is present here.
Run Code Online (Sandbox Code Playgroud)
因此,在编译时,编译器(LDD)将查找变量的原始定义,如果它没有找到,它将向'i'抛出错误'未定义的引用.