extern定义的变量必须是全局的,这样才可能在其他文件中使用,所以,不能在语句块里定义;(可以声明)
extern一般用在访问其他源文件中定义的变量和调用同一文件中下面定义的变量。比如a.cpp文件里定义了int a; b.cpp文件里就可以extern int a;来声明 这样b文件里的a变量就是a文件里的a变量。
全局变量的使用
变量在某一个源文件中声明后,如果在其他源文件中使用,需要在此源文件中加extern关键字重新声明一下。通常做法是这样的,在某源文件中不加extern定义及初始化此变量,用extern显示声明此变量放到头文件中,其他源文件要使用时包含此头文件。
情况一:在test.c中定义并赋值,在main.c中声明并使用
test.c
int j=9;
main.c
#include<stdio.h>
int main()
{
extern int j;
printf("\n%d add:%d\n",j,&j);
return 0;
}
情况二:在test.c中定义并赋值,在test.h中声明,在main.c中#include<test.h> 后使用
test.c
int j=9;
test.h
extern int j;
main.c
#include <stdio.h>
#include <test.h>
int main()
{
printf("\n%d add:%d\n",j,&j);
return 0;
}