extern用法
extern的目的
在大型项目里面,很多变量,类分散定义在很多单元里面,这时候就需要一个extern来防止重复定义变量造成资源浪费
修饰全局变量
比如:
//a.c
extern int i; //i定义在其他单元里面
int j=10 //默认就可以拥有外部链接,即其他单元可以直接调用这个j
修饰全局常量
//b.h
extern const int i=10; //可以有外部链接,加上extern之后就可以被其他文件访问了
const int j=20; //默认不可以有外部链接
修饰局部变量
修饰局部变量的时候,extern的意思是:这个局部变量的具体定义在其他文件之中。
void func(){
extern int i; //表明,这个i被定义在其他文件当中,它会去找一个全局变量出来(而不是局部)
extern int j=10;//这个行为是不允许的,因为这里实在定义一个extern,而局部变量生命周期在函数结束后就结束了,因此不允许建立
}
修饰局部常量
和局部变量一样
Test:
//b.h
extern const int i=10;
int j=20;
//a1.c
#include<stdio.h>
#include"1.h"
extern const int i;
int main(void){
printf("extern const int i=%d\n
int j=%d",i,j);
}
//运行结果:
extern const int i=10
int j=20
//a2.c
#include<stdio.h>
#include"1.h"
void func(){
extern int j;
printf("%d",j);
}
int main(void){
func();
}
//结果:
20
//a3.c
#include<stdio.h>
#include"1.h"
void func(){
extern int k=10; //报错:不允许对外部变量的局部声明使用初始值设定项
}
int main(void){
func();
}