gpt4 book ai didi

c++ - 如何实现头文件互斥包含?

转载 作者:太空狗 更新时间:2023-10-29 20:08:14 24 4
gpt4 key购买 nike

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

#include<a.h> // Ok

#include<b.h> // OK

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

最佳答案

If both a.h and b.h are included in a source file, a compile error is expected to occur.
What shall I add in the headers to achieve this?

你可以用预处理器引用你的头部保护来做这样的事情:

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

关于c++ - 如何实现头文件互斥包含?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55827537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com