Is there a preprocessor macro to prevent others include a private header in C++?

Viewed 149

I have a private.hpp header that should be used only for 2 classes, this header performs some operations that those classes use, however, other software engineers of my team started to use it in the same module, I had to fix those includes and add more methods to those classes. I want to know if there is a way to throw an error from the preprocessor or maybe linker to stop the usage of that header out of those 2 classes.

1 Answers

As @S.M. mentionned, you can define a preprocessor variable in the files where you need your secret.hpp :

#define INTERNAL_OPERATIONS_ALLOWED // top of file
#include "secret.hpp"

// ...

#undef INTERNAL_OPERATIONS_ALLOWED // end of file

and add a condition on top of your private.hpp :

#if !defined(INTERNAL_OPERATIONS_ALLOWED)
    #error "DO NOT USE THIS HEADER"
#endif

// ...

or define your macros individually :

#ifdef INTERNAL_OPERATIONS_ALLOWED
    #define OPERATION(X) X
#else
    #error "DO NOT USE THIS OPERATION"
#endif

This will not prevent other developers to use your operations, but they will have to define the INTERNAL_OPERATIONS_ALLOWED on purpose, meaning that they are aware that they shouldn't.

Related