您的位置:首页 > 其它

C程序设计语言(K&R)学习笔记--5.extern小结

2014-05-23 22:03 323 查看
extern

声明变量在外部定义

例1:外部变量定义在文件开头,在调用它的函数的上面,extern可省略

#include <stdio.h>
int global ; 

void main(){

	printf("%d\n",global);

}


例2:外部变量定义在文件中间,在调用它的函数的下面,必须使用extern声明

#include <stdio.h>
void main(){
	extern int global ;
	printf("%d\n",global); 

}
int global=100;


例3:主文件使用从文件里的外部变量,extern可以省略

主文件为:test01.c

子文件为:test02.c

test01.c

#include <stdio.h>
#include "test02.c" 

void main(){
	printf("%d\n",bbb);// 在test02.c 中定义	
}


test02.c

#include <stdio.h>
int bbb=222;


例4:从文件使用主文件的外部变量,必须使用extern声明

主文件test01.c

#include <stdio.h>
#include "test02.c"
int aaa=111 ;
void main(){
	printf("%d\n",add());
}


从文件test02.c

#include <stdio.h>
int bbb=222;
int add(){
extern int aaa;// 在test01.c中定义
return bbb+aaa;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: