Search code examples
c++ifndef

Can/should I type whatever I want after #ifndef?


Example:

#ifndef HEADER_h
#define HEADER_h

#endif

Instead of HEADER_h, can I do the following?

#ifndef HEADER

or

#ifndef LIBRARY

or

#ifndef SOMETHING

or

#ifndef ANOTHERTHING

etc.


Solution

  • Yes, you can name the include guard symbol whatever you want, but bear in mind that they are supposed to be unique across headers. You definitely don't want a header

    // first.h
    #ifndef NON_UNIQUE_H
    #define NON_UNIQUE_H
    
    void foo();
    
    #endif
    

    and another one

    // second.h
    #ifndef NON_UNIQUE_H
    #define NON_UNIQUE_H
    
    void bar();
    
    #endif
    

    When you include both in one translation unit, one will "win" and its declarations will be visible, e.g.

    // main.cpp
    
    #include "first.h" // now, NON_UNIQUE_H is defined
    #include "second.h" // NON_UNIQUE_H already there, doesn't do anything
    
    int main(int, char**)
    {
        bar(); // error, won't compile, bar() isn't declared
    }
    

    Besides the necessity to circumvent such scenarios, it's best to stick to some convention throughout your project. One classical way of doing it is to convert the header file base name to upper case and append _H. If you have header files with the same base name in different directories, you can include the directory name, e.g. SUBDIR_FOO_H and OTHERSUBDIR_FOO_H. But this is up to you.