内容摘自stack overflow
1. 定义
extern可用在变量和函数前,用以表示变量或者函数定义在别的文件中(或者本文件其它位置),提示编译器遇到该变量或者函数的时候去别的文件中去寻找定义
2. 使用方法
最合适的声明和定义一个全局变量的方法是在一个头文件(file3.h)中声明一个extern变量,某一个源文件引用头文件并定义这个变量,其他的源文件就可以直接引用这个变量。简单说,在一个工程中,应该在某个头文件声明一个extern变量,在某个源文件中定义它,剩下所有源文件只引用这个变量。下面是列子
file3.h 中声明了全局变量global_variable
prog1.h中声明了两个全局函数use_it();increment();
file1.c定义了全局变量global_variable实现了全局函数increment(当然要引用file3.h和prog.h)
file2.c实现了全局函数use_it(同样要引用file3.h和prog.h)
prog.c直接引用了全局变量和两个全局函数.
file3.h
extern int global_variable;/*declaration of the variable*/
file1.c
#include "file3.h" /*declaration made available here*/
#include "prog1.h" /*function declarations*/
/*variable defined here*/
int gloable_variable=37;/*definition checked against declaration*/
int increment(void){return golable_variable++;}
file2.c
#include "file3.h"
#include "prog1.h"
#include <stdio.h>
void use_it(void)
{
printf("Global variable: %d\n", global_variable++);
}
prog1.h
extern void use_it(void);
extern int increment(void);
prog1.c
#include "file3.h"
#include "prog1.h"
#include <stdio.h>
int main(void)
{
use_it();
global_variable += 19;
use_it();
printf("Increment: %d\n", increment());
return 0;
}
需要注意的几点:
- 头文件只能包含extern类型的变量声明,不能包含static类型的变量声明,static声明在header中,意味着各自source文件引用header后,都要定义一个对应变量,也就是每个source中的变量时独立的。
- 对于任何变量,只能在一个头文件中声明
- source文件不能包含任何extern类型的变量声明,只能包含相应的头文件
- 对任何给定的变量,最好能顺带初始化
- source文件在定义变量的时候要引用声明这个变量的头文件,以确保声明和定义的一致性
- function内部不要用extern声明一个变量..........
- 全局变量要尽量少用,能用function就用function代替
在一些C编译器里面,会采用一种类似fortran中的common块的方式去定义变量,这种方式就是在多个source中多次定义同一个变量。在大多数情况下,这样子是非常危险的!所以不推荐在任何情况下使用这种方法。
头文件和变量的一些总结:
- 头文件用于声明一些函数和变量,既然是声明,就不能有定义
- 如果要声明全局变量,请使用extern关键字,并在且仅在一个source中定义它
- 杜绝在header中出现任何不带extern关键字的声明,更不建议直接定义并实例化变量