**C语言中extern、结构体数组与模块化编程的应用
模块化编程
什么是模块化编程呢?顾名思义就是把整个项目分块进行编程,方便后期维护。也就是说把一个项目分成多个.c文件和.h文件。
我的编译环境是DEV C++ 5.9.2 模块化编程的方法都是一样的,包括在keil5上对单片机编程,亦或在Linux上用gedit编程,都是一样的。我们以两个c文件为例子,测试模块化编程。
- 创建两个.c文件和两个.h文件。分别取名为main.c main.h和dayin.c dayin.h ;
- 在dayin.c文件里写打印函数 用于测试,在main.c文件里调用打印函数;
- 在.h文件里分别写上防止重复编译的判断语句 #infndef #define #endif;
- 需要注意的是,这些文件需要添加到同一个工程里面,这样编译器才能找到他们;
下面是源码:
main.c:
#include"main.h"
int main()
{
dayin();
return 0;
}
main.h:
#ifndef __main_
#define __main_
#include"stdio.h"
#include"dayin.h"
#endif
dayin.c:
#include"dayin.h"
void dayin(void)
{
printf("nihao\n");
}
dayin.h:
#ifndef __DAYIN_H
#define __DAYIN_H
#include"stdio.h"
#include"main.h"
void dayin(void);
#endif
模块化编程总结:
1.每一个模块都建立一个.c和一个.h文件,
想使用该模块时,包含对应的.h文件就可以了
2…c文件写函数、变量的定义
3…h文件写库的引用、函数的声明、类型的定义,如果有外部变量还要写外部变量的引用等
4…h文件要写防止重复编译的预处理命令
全局变量、结构体在模块化编程里的使用方法
关键字:extern
外部声明,声明变量。将变量定义在源文件中。生命在头文件中。
注意:使用extern时 不能初始化
使用例子:
extern struct Student stu[50];
extern int count;
下面再写一个例子 方便大家理解
main.c
#include"main.h"
struct Student stu[50];
int count;//全局变量
int main()
{
dayin();
return 0;
}
main.h
#ifndef __main_
#define __main_
#include"stdio.h"
#include"dayin.h"
struct Student{
int id;
char name[20];
float score;
};
extern struct Student stu[50];
extern int count;//已经增加的学生数目
#endif
dayin.c
#include"dayin.h"
void dayin(void)
{
printf("nihao\n");
stu[1].id=2;
count =1 ;
printf("%d\n",count);
printf("%d\n",stu[1].id);
}
dayin.h
#ifndef __DAYIN_H
#define __DAYIN_H
#include"stdio.h"
#include"dayin.h"
void dayin(void);
#endif
运行结果: