【C++】防止头文件循环展开

说明问题
1 创建头文件hello1.h
//引用hello2.h
#include  "hello2.h"
int fun();
2 创建头文件hello2.h
//引用hello1.h
#include  "hello1.h"
int fun1();
3 main.cpp
#include <iostream>
//引用了hello1.h
#include "hello1.h"
using namespace std;
int main()
{
    cout << "Hello, world!" << "\n";
    return 0;
}

明显上面的 main.cpp 中调用了hello1.h,但是在hello1.h中又调用了hello2.h,在hello2.h中又调用了hello1.h,这样循环往复, 导致了递归式的调用头文件,这样的程序往往编译不通过,但是在编程过程中,有些头文件需要互相引用,这样的情况,怎么解决呢?

解决方法1 使用 #ifdef
1 hello1.h
#ifndef  hello1 // hello1 可以自定义
#define hello1
#include  "hello2.h"
int fun();
#endif
2 hello2.h
#ifndef  hello2 // hello2 可以自定义
#define hello2
#include  "hello1.h"
int fun1();
#endif
3 main.cpp 不变,这样就可以直接编译通过,得到结果了。

在这里插入图片描述
这样的执行结果是在 main.cpp 程序中,编译时候调用过程为下面的顺序:

#include <iostream>
//引用了hello1.h
#include "hello1.h"
//解析为:
#ifndef  hello1 // hello1 可以自定义
#define hello1
#include  "hello2.h"
//解析 hello2.h
#ifndef  hello2 // hello1 可以自定义
#define hello2
#include  "hello1.h"
//当再次解析hello1.h时,发现 ifndef 不成立了,则该部分不再解析,即停止
#ifndef  hello1 // hello1 可以自定义
#elif
int fun1();
int fun();

using namespace std;
int main()
{
    cout << "Hello, world!" << "\n";
    return 0;
}
解决方法2 使用 #pragma once
1 hello1.h
#pragma once
#include  "hello2.h"
int fun();
2 hello2.h
#pragma once
#include  "hello1.h"
int fun1();

这样子也可以达到效果,前提是您的编译器支持。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值