专家
公告
财富商城
电子网
旗下网站
首页
问题库
专栏
标签库
话题
专家
NEW
门户
发布
提问题
发文章
TI
模块化编程时,#include到底要放在哪里?
2019-07-18 14:40
发布
×
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮
站内问答
/
TI MCU
14372
1
1334
结合我自己的经验,谈一谈模块化编程时#include应该出现的位置。总结起来大体有二条规则:
一、规则1:只包含必要的头文件
看下面这个模块:
===foo.c====#include
<stdio.h>
#include
<foo.h>
#include
<uart.h>
void
foo (){ printf (
"
hello world!
"
);}
===foo.h====
#ifndef __foo_h__
#define
__foo_h__
extern
void
foo();
#endif
在foo()函数中也只有简单的一行打印语句。由于printf()函数的原型声明来源于stdio.h,因此foo.c中包含了stdio.h无可厚非,否则根本无法使用。但foo.c文件中除了包含stdio.h外还包含了另外一个多余的头文件 ——uart.h,这不会导致编译的出错,但我们并不需要使用uart.h中声明的接口,因此这种行为会导致编译效率的降低。如果此时uart.h中还包含了其它文件,那么全部都会在预处理时展开到foo.c中。当一个项目的代码量很大时,由于效率地下而多占用的时间就无法忽视了。
二、规则2:使#include出现在它被需要的地方
为了使用printf()函数,可以把#include<stdio.h>放在foo.h文件中,编译也可以正常通过,如下:
===foo.h====
#ifndef __foo_h__
#define
__foo_h__
#include <stdio.h>
extern
void
foo();
#endif
===foo.c====
#include
<foo.h>
void
foo (){ printf (
"
hello world!
"
);}
但这样会产生一个问题,stdio.h对于我们的头文件foo.h来说,是必须的么?当然不是!那么会导致什么样的问题呢?我们已经直到.h文件的作用相当于模块的使用说明书,如果其它模块要使用foo模块时,需要通过#include<foo.h>来添加接口函数,此时就会间接的包含了stdio.h,同样的会导编译致速度下降的问题。因此,正确的做法是将#include<stdio.h>放在foo.c中,如下:
===foo.h====
#ifndef __foo_h__
#define
__foo_h__
extern
void
foo();
#endif
===foo.c====
#include <stdio.h>
#include
<foo.h>
void
foo (){ printf (
"
hello world!
"
);}
理解了上面的例子,则看下面一条实例:
在system.h中,定义了如下结构体定义:
=====system.h=====
#ifndef __system_h__#def __system_h__typedef
struct
stuTAG{
char
*
name; u8 age;}stu_st;
#endif
同样在一个foo.c模块中,定义了一个函数:
===foo.h====
#ifndef __foo_h__
#define
__foo_h__
#include "system.h"
extern
void
print_info(stu_st *
student);
#endif
=====foo.c=====
#include
"
foo.h
"
#include
<stdio.h>
void
print_info(stu_st *
student){ printf(
"
name:%s
"
,student->
name); printf(
"
age :%d
"
,student->
age); }
从这个foo模块的实现代码来看,foo.h和foo.c都需要了解stu_st结构体的内容,也就是stu_st是被foo.c和foo.h同时需要的,因此它必须被放置在foo.h中,否则编译时会出现stu_st未定义的错误,此时将#include放置在.h文件中是必须的!
用一句话概括:只在必要的地方包含必要的头文件!
友情提示:
此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
该问题目前已经被作者或者管理员关闭, 无法添加新回复
1条回答
dirtwillfly
1楼-- · 2019-07-18 20:03
部分图片挂了
加载中...
一周热门
更多
>
相关问题
CPLD的方波输出
4 个回答
11个版本Quartus II 软件下载,安装包网盘合集,附教程,47G!
20 个回答
请大家帮忙到21IC发展大家谈支持我申请新版面
20 个回答
【通知】21ic中国电子网服务条款 (所有人员必读)
1 个回答
满载而归乙亥年,大展鸿途庚子年---集签赢好礼
20 个回答
携手ADI,踏上电子工程师之巅—车辆电气化视频,答题领奖!
1 个回答
如何提升论坛质量,看你了!
20 个回答
【最终名单】二姨家喊你来拿100份新年大礼啦~
20 个回答
相关文章
×
关闭
采纳回答
向帮助了您的网友说句感谢的话吧!
非常感谢!
确 认
×
关闭
编辑标签
最多设置5个标签!
TI
保存
关闭
×
关闭
举报内容
检举类型
检举内容
检举用户
检举原因
广告推广
恶意灌水
回答内容与提问无关
抄袭答案
其他
检举说明(必填)
提交
关闭
×
关闭
您已邀请
15
人回答
查看邀请
擅长该话题的人
回答过该话题的人
我关注的人
一周热门 更多>