避免重复包含应该注意的问题

变量定义不能或者说不应该定义在.h文件中,例如 有 a.h,里面定义了变量 int temp; 如下:
// a.h
#ifndef _a_h_
#define _a_h_
int temp; // define varible
#endif


// 工程包含两个模块 a.c ,b.c


//--------b.c----------
#include"a.h"
...
//显然编译器编译b.c的时候符号_a_h_没有定义,则temp 变量在b.c里定义了一次




// -------a.c ----------
#include "a.h"
//编译器是独立编译b.c和a.c的,甚至编译顺序都是不确定的,所以编译器编译每个.c文件的时候符号定义都是独立的,
//这时候,仍然 没有定义 _a_h_ 这个符号,则文件a.h再次被a.c包含, temp变量再次定义,但编译仍然没有问题.




// 下面链接器link开始工作,链接b.obj和a.obj,结果有两个temp变量 ,link error!


另外:
#ifndef  #define ,else ,... #endif 结构是用来避免以下情况的重复包含的,而不是为上面所说情况准备的


--------------------------------------------------------------
//--- a.h
#ifndef _a_h
#define _a_h
declaration in a
#endif
// end of a.h

------------------------------------------------------------------


//---- b.h
#ifndef _b_h
#define _b_h

#include "a.h" // 注意这里
declaration in b

#endif 
// end of b.h
---------------------------------------------------------

//---a.c
#include "a.h"
#include "b.h"
// end of a.c
展开为以下内容:
------------------------------------------------------------

#ifndef _a_h
#define _a_h
declaration in a   //定义了  符号 _a_h
#endif

#ifndef _b_h
#define _b_h


#ifndef _a_h       // 已经定义了 _a_h
#define _a_h
declaration in a   // 这行才是重复的,失去作用了
#endif


declaration in b   // b.h中的声明
#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值