嵌入式 模块划分程序设计注意事项

来源:互联网 发布:软件测试加班图片 编辑:程序博客网 时间:2024/06/06 08:26

C语言模块化程序设计需理解如下概念:
(1) 模块即是一个.c文件和一个.h文件的结合, 头文件(.h)中是对于该模块接口的声明;
(2) 某模块提供给其它模块调用的外部函数及数据需在.h中文件中冠以extern关键字
声明;
(3) 模块内的函数和全局变量需在.c文件开头冠以static关键字声明;
(4) 永远不要在.h文件中定义变量!定义变量和声明变量的区别在于定义会产生内存
分配的操作, 是汇编阶段的概念; 而声明则只是告诉包含该声明的模块在连接阶段从其它模
块寻找外部函数和变量。如:
/*module1.h*/

int a = 5; /* 在模块 1 的.h文件中定义int a */


/*module1 .c*/

# include "module1.h" /* 在模块 1 中包含模块 1 的.h文件 */


/*module2 .c*/

#include "module1.h" /* 在模块 2 中包含模块 1 的.h文件 */


/*module3 .c*/

#include "module1.h" /* 在模块 3 中包含模块 1 的.h文件 */

以上程序的结果是在模块 1、2、3 中都定义了整型变量 a,a 在不同的模块中对应不同

的地址单元,这个世界上从来不需要这样的程序。正确的做法是:


/*module1.h*/

extern int a; /* 在模块 1 的.h 文件中声明 int a */


/*module1 .c*/
#include "module1.h" /* 在模块 1 中包含模块 1 的.h 文件 */

int a = 5; /* 在模块 1 的.c 文件中定义 int a */


/*module2 .c*/

#include "module1.h" /* 在模块 2 中包含模块 1 的.h 文件 */


/*module3 .c*/

#include "module1.h" /* 在模块 3 中包含模块 1 的.h 文件 */


这样如果模块 1、2、3 操作a的话,对应的是同一片内存单元。
0 0
原创粉丝点击