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; }