extern 关键字
我们知道,C语言代码是由上到下依次执行的,不管是变量还是函数,原则上都要先定义再使用,否则就会报错。但在实际开发中,经常会在函数或变量定义之前就使用它们,这个时候就需要提前声明。
所谓声明(Declaration),就是告诉编译器我要使用这个变量或函数,你现在没有找到它的定义不要紧,请不要报错,稍后我会把定义补上。
我们知道使用 printf()、puts()、scanf()、getchar() 等函数要引入 stdio.h 这个头文件,很多初学者认为 stdio.h 中包含了函数定义(也就是函数体),只要有了头文件程序就能运行。其实不然,头文件中包含的都是函数声明,而不是函数定义,函数定义都在系统库中,只有头文件没有系统库在链接时就会报错,程序根本不能运行。
变量和函数不同,编译器只能根据 extern 来区分,有 extern 才是声明,没有 extern 就是定义。
变量的声明只有一种形式,就是使用 extern 关键字:
extern datatype name;
变量也可以在声明的同时初始化,格式为:
extern datatype name = value;
这种似是而非的方式是不被推荐的,有的编译器也会给出警告。
extern 是用来声明的,不管具体的定义是在当前文件内部还是外部,都是正确的。(经过验证,这个说法是正确的)
代码示例:
两个程序:
main.c
#include <stdio.h>
extern void func();
extern int m;
int n = 200;
int main(){
func();
printf("m = %d, n = %d\n", m, n);
return 0;
}
module.c
#include <stdio.h>
int m = 100;
void func(){
printf("Multiple file programming!\n");
}