Search code examples
c++include

Checking whether #include is already declared


I am trying to check whether an #include <file.h> has already been declared using C++ macro.

Example

In file.h I do:

#ifndef FILE.H
#define FILE.H
class A
{
  //do routines 
};
#endif

In a second file called second.h I want to check if file.h has been included already.

Typical psuedo-code:

#ifndef "file.h"
#include "file.h"
#endif

#ifndef SECOND.H
#define SECOND.H
class second
{
  //do routine
};
#endif

I have tried a few #ifndef directives but no joy. Do anyone know how to achieve this?


Solution

  • Everybody else has covered correct inclusion of include guard macros.

    File.h

    #ifndef   FILE_H
    #define   FILE_H
    // Code here
    #endif
    

    But everybody else missed the second part of your question on correct usage:

    This is an example of bad usage:

    #ifndef  FILE_H  
    #include "file.h"
    #endif
    
    #ifndef SECOND_H
    #define SECOND_H
    class second
    {
      //do routine
    };
    #endif
    

    This is not correct (though correct may be too strong).

    The include guards in each file should surround their entire content. So, in the second file, the #include "file.h" should be inside the include guards.

    Also you do not need to test for inclusion that will be done inside the file itself. Thus the file should look like this:

    #ifndef SECOND_H
    #define SECOND_H
    
    #include "file.h"
    
    class second
    {
      //do routine
    };
    #endif
    

    Also your macro guards are way too small. There is a high likelihood that these will be used by somebody else; this will cause all sorts of weird collisions.

    A good way to make the guards unique is to use a prefix, your full name (or nick name), or if you have your own registered website then uses its domain name. I then also add part of the directory hierarchy that includes the file.

    #ifndef    WEBSITE1_NAMESPACE1_NAMESPACE2_FILENAME_H
    #define    WEBSITE1_NAMESPACE1_NAMESPACE2_FILENAME_H
    
    #endif
    

    Another alternative (especially if you are working on Windows) is to generate a GUID. Just generate a new one for each file.

    Final point: only include other files from header files if their content is absolutely necessary. You only need to include "file.h" if this file has a type definition that class second depends on. If your class only uses that class as a pointer or a reference then prefer to use forward declaration rather including the header file.

    The scenarios in which you must #include are:

    • second is a child of first.
    • second has member(s) that are first objects
    • second has method(s) that take first objects as parameters
    • Second has method(s) that return first objects as a result

    Notice that I use the term "objects". If they are references or pointers then this does not count. In these cases you can use forward declaration to solve the problem.