在一些场景中,我们可能需要共用同一个变量,例如在一个简单的学生管理系统中,在Student.h文件里定义了变量int count = 0; 来记录学生总人数.。
// Student.h 文件
#define MAXSIZE 100
#define NAME_SIZE 20
typedef struct Student
{
int id;
char name[NAME_SIZE];
int age;
};
Student *stus[MAXSIZE];
int count = 0; // 记录学生人数
当我们在SysService.c文件和Student.c文件中都引用了这个头文件时,运行项目就会报重复定义`count`的错误。
// Student.c 文件
#include "Student.h"
// ...
---------------------------
// SysService.c 文件
#include "Student.h"
// ...
解决此问题的方法在于存储类别说明符extern关键字,我们在Student.c文件中定义它,再在Student.h头文件中的count前加上extern关键字。
// Student.c
int count = 0;
---------------
// Student.h
extern int count;
extern说明符表明声明的变量定义在别处,这样即使SysService.c文件也包含了Student.h头文件,也不会出现重复定义count的错误。