#ifndef 有什么用?

pg1979 2004-08-11 06:28:52
在如下程序中,#ifndef 有何用?不解:prevent multiple inclusions of header file(防止包含多个头文件)

// TIME1.H
// Declaration of the Time class.
// Member functions are defined in TIME.CPP

// prevent multiple inclusions of header file
#ifndef TIME1_H
#define TIME1_H

// Time abstract data type definition
class Time {
public:
Time(); // default constructor
void setTime(int, int, int); // set hour, minute and second
void printMilitary(); // print military time format
void printStandard(); // print standard time format
private:
int hour; // 0 - 23
int minute; // 0 - 59
int second; // 0 - 59
};

#endif
...全文
214 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
aspvbjava 2004-08-11
  • 打赏
  • 举报
回复
如果你的myhead.h文件中有如下代码
#ifndef _myhead_h
#define _myhead_h

……

#endif

当你在mysource1.cpp和mysource2.cpp中同时包含了myhead.h的时候
当编译mysource1.cpp的时候会编译myhead.h就会执行#define _myhead_h
当编译mysource2.cpp的时候编译myhead.h的时候碰到#ifndef _myhead_h的时候,因为刚才已经定义了_myhead_h,就会跳过本文件的编译,这就是防止头文件重复编译
npvsp 2004-08-11
  • 打赏
  • 举报
回复
a.h include time1.h
b.h include time1.h
c.h include a.h and b.h

编译c.h 时,其中 time1.h 只会编译成一段代码,不会重复编译
pg1979 2004-08-11
  • 打赏
  • 举报
回复
举个具体例子,何为其他文件?
waini12 2004-08-11
  • 打赏
  • 举报
回复
这是为了防止 其他程序已经用到了这个头文件在重复使用 所以要用
#ifndef XX_H
#define XX_H

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧