栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【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 
//引用了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 
//引用了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();

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1025572.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号