user3395707
user3395707

Reputation: 67

how can I achieve header files mutual exclusive include?

Suppose I have two headers: a.h and b.h.
What I want to do in my project is to allow only one of them included.
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?

#include<a.h> // Ok

#include<b.h> // OK

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

Upvotes: 3

Views: 113

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

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?

You can do something like this with the preprocessor referring to your header guards:

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

Upvotes: 7

Related Questions