【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();

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


版权声明:本文为qq_29750461原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。