****C语言中extern、结构体数组与模块化编程的应用**

**C语言中extern、结构体数组与模块化编程的应用

模块化编程

什么是模块化编程呢?顾名思义就是把整个项目分块进行编程,方便后期维护。也就是说把一个项目分成多个.c文件和.h文件。
我的编译环境是DEV C++ 5.9.2 模块化编程的方法都是一样的,包括在keil5上对单片机编程,亦或在Linux上用gedit编程,都是一样的。我们以两个c文件为例子,测试模块化编程。

  1. 创建两个.c文件和两个.h文件。分别取名为main.c main.h和dayin.c dayin.h ;
  2. 在dayin.c文件里写打印函数 用于测试,在main.c文件里调用打印函数;
  3. 在.h文件里分别写上防止重复编译的判断语句 #infndef #define #endif;
  4. 需要注意的是,这些文件需要添加到同一个工程里面,这样编译器才能找到他们;
    下面是源码:

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

运行结果:

在这里插入图片描述

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值