如何实现头文件相互互斥包含

how can I achieve header files mutual exclusive include?

本文关键字:文件 包含 何实现 实现      更新时间:2023-10-16

假设我有两个标题:a.hb.h
我想在我的项目中做的是只允许包含其中一个。
如果源文件中同时包含a.hb.h,则预计会发生编译错误。
我应该在标题中添加什么来实现这一点?

#include<a.h> // Ok

#include<b.h> // OK

#include<a.h>
#include<b.h> // compile error 

如果源文件中同时包含a.hb.h,则预计会发生编译错误。
我应该在标题中添加什么来实现这一点?

你可以对引用标头保护的预处理器执行以下操作:

a.h

 #ifndef A_H
 #define A_H
 #ifdef B_H
 #error "You cannot use a.h in combination with b.h"
 #endif
 // ...
 #endif

b.h

 #ifndef B_H
 #define B_H
 #ifdef A_H
 #error "You cannot use b.h in combination with a.h"
 #endif
 // ...
 #endif