c++include-guards

#ifndef syntax for include guards in C++


I'm currently studying for a CS course's final exam and I've run into a minor (maybe major?) issue regarding the syntax of C++ #ifndef.

I've looked at the syntax for #infndef when using it as an #include guard, and most on the web seem to say:

#ifndef HEADER_H
#define "header.h"
...
#endif

But my class's tutorial slides show examples as:

#ifndef __HEADER_H__
#define "header.h"
...
#endif

I was wondering what (if any) the difference was between the two. The exam will most likely ask me to write an #include guard, and I know conventional wisdom is to just go with what the prof / tutor says, but if there's a difference during compilation I'd like to know.


Solution

  • The usual practice is to do neither, and put the include guard inside the header file, as it reduces repetition. e.g.:

    header.h

    #ifndef HEADER_H
    #define HEADER_H
    
    // Rest of header file contents go here
    
    #endif
    

    Precisely what you use as the macro name is down to your particular coding standard. However, there are various subtle rules in the C and C++ standards that prevent you from using identifiers beginning with underscores,1 so you should avoid __HEADER_H__, just to be on the safe side.

    It's also worth mentioning that you should pick something that's unlikely to clash with anything else in your codebase. For example, if you happened to have a variable called HEADER_H elsewhere (unlikely, I realise), then you'd end up with some infuriating errors.


    1. See e.g. section 7.1.3 of the C99 standard.