Search code examples
c++cmultiple-inclusions

What kinds of header files should not be protected against multiple inclusion?


I read the dcmtk source code, and found a comment in ofstdinc.h:

// this file is not and should not be protected against multiple inclusion

And what kinds of header files SHOULD NOT be protected against multiple inclusion?


Solution

  • Preprocessor metaprogramming. That is, using the included file as a sort of compile-time function that performs some task. The arguments to the function are macros. For example, the file you linked has a section that looks like this:

    // define INCLUDE_STACK to include "ofstack.h"
    #ifdef INCLUDE_STACK
    #include "dcmtk/ofstd/ofstack.h"
    #endif
    

    So if I wanted to include "ofstack.h", I would do so like this:

    #define INCLUDE_STACK
    #include "ofstdinc.h"
    #undef INCLUDE_STACK
    

    Now, imagine later down the line, someone wants to use this particular section of the header:

    // define INCLUDE_STRING to include "ofstring.h"
    #ifdef INCLUDE_STRING
    #include "dcmtk/ofstd/ofstring.h"
    #endif
    

    So they do the following:

    #define INCLUDE_STRING
    #include "ofstdinc.h"
    #undef INCLUDE_STRING
    

    If "ofstdinc.h" had include guards, it wouldn't be included.