Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent header from being included in some files, in compilation time?

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?

like image 222
Max Shifrin Avatar asked Sep 16 '13 09:09

Max Shifrin


People also ask

How can you make a header file not to include multiple times?

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.

Can you define which header file to include at compile time?

Yes. This can be done by using the #if, #else, and #endif preprocessor directives.

How do you check if a header file is included?

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.

Can you include header files in header files?

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.


1 Answers

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
like image 93
David Schwartz Avatar answered Sep 20 '22 23:09

David Schwartz