I have a header file, which I can control its contents.
Additionally I have an interface I1 (defined in some other file) from which various implementations derived. I want to prohibit those implementations from including this header file. So that during compile time if the file is included the compilation will fail, otherwise it will continue as usual.
So I have header file and an interface definition (in some other file). I want to prohibit interface implementations from including the given header file, during compilation.
Any suggestions as to how I can achieve that? Is there some clever templates/preprocessing trick I can use?
To avoid multiple inclusions of the same header file we use the #ifndef, #define and #endif preprocessor directives. Just write the entire program in only file and include headers once only.
Yes. This can be done by using the #if, #else, and #endif preprocessor directives.
To check if an header file has been included or not in a C or C++ code, we need to check if the macro defined in the header file is being defined in the client code. Standard header files like math. h have their own unique macro (like _MATH_H ) which we need to check. Consider this example of checking if math.
Yes, this will work. Note, however, that if you include a lot of headers in this file and don't need all of them in each of your source files, it will likely increase your compilation time.
In the header file:
#ifndef FOO_IMPLEMENTATION_USE_ONLY
#error This file is for inclusion in the FOO implementation only
#endif
In the files that are supposed to include it:
// Define this ONLY in the Foo implementation files
#define FOO_IMPLEMENTATION_USE_ONLY
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With