为什么要用ifndef?

网上说什么头文件防止重复包含,不太明白啊。。
2025-03-04 14:06:17
推荐回答(2个)
回答1:

#include指令的缺陷,导致同一个头文件会被多次引入,使用ifndef可以避免多次引入。
例如一个程序中包含如下文件:dialog.cpp dialog.h network.cpp network.h log.cpp log.h
dialog.cpp中include了network.h和log.h
network.h中也include了log.h
这样dialog.cpp中实际上引入了两次log.h。
在编译的时候,编译器会因为log.h中的函数被定义了两次而报错。
使用ifndef就会避免这个问题。
如果用VC编译器,也可以不使用ifndef,改用#pragma once预编译指令就可以了。

回答2:

使用ifndef的头文件都是这样写的:
xxx.h:
#ifndef XXX_H /*如果没有定义XXX_H*/
#define XXX_H /*定义XXX_H为空字符串*/
class Xxx{
//... ...
};
#endif /*结束判断*/

如果这样的话,多次引入xxx.h会像下面这样:

#include "xxx.h" /*1次引入*/
#include "xxx.h" /*2次引入*/
#include "xxx.h" /*3次引入*/

展开为:

#ifndef XXX_H /* 没有定义XXX_H,条件成立 */
#define XXX_H /*定义XXX_H为空字符串*/
class Xxx{ /*引入class Xxx*/
//... ...
};
#endif /*结束判断*/
#ifndef XXX_H /* 已经定义XXX_H,条件不成立 */
#define XXX_H /*跳过*/
class Xxx{
//... ...
};
#endif
#ifndef XXX_H /* 已经定义XXX_H,条件不成立 */
#define XXX_H /*跳过*/
class Xxx{
//... ...
};
#endif