C语言关键字(2)——extern

在一个project中,会有多个源文件,就会存在一个文件调用另外一个文件中的变量或者函数,下面以自己在实际过程中所用到的加以说明。

1、引用外部全局变量(无”.h”文件)

如有stu.c和main.c两个源文件,现在要在main.c文件中使用stu.c中一个全局变量”num”,

//stu.c
#include "stdio.h"  
int num = 2; //extern可以省略  

//main.c
#include "stdio.h"
int main()
{
     extern int num; //声明要使用的外部变量,前面一定要加上extern
     printf("%d\n",num);
     return 0;
}

程序运行结果为:2

当一个文件要定义或使用外部文件中的变量时,需要在定义或使用前用extern关键字声明其为外部变量。

2、引用外部全局变量(使用“.h”文件)

一般情况下,模块化程序文件,提供一个.c文件和对应的一个.h文件,如stu.c和stu.h
在stu.h文件中声明变量num

//stu.h
int num;

在stu.c文件中赋值,同时包含stu.h

//stu.c
#include "stdio.h"
#include"stu.h"  //包含stu.h
num = 2;  

现在要在main.c文件中使用num的值,则只需在其头文件中包含stu.h

//main.c  
#include "stdio.h"  
#include "stu.h" //包含stu.h  
int main()  
{  
      printf("%d\n",num);  
      return 0;  
}  

程序运行结果为:2
该方法只需增加一个.h文件,在该文件中声明所要使用的变量,然后在.c文件中的头文件中包含即可,不需要在使用前加以特别声明。

以上两种方法都可以在一个文件中使用外部变量,该方法同样适用于结构体和函数。

一般情况下,在实际工程中使用第二种方法,尤其对于结构体和函数。如在stu.h文件中声明,在stu.c文件中定义,如果main.c文件需要使用,只需在其头文件中包含对应的stu.h文件即可。_

以上对于VC环境验证无误,但是在CCS3.3中,存在部分不同点,具体有待验证。