Search code examples
c++includeheaderinfinity

Is there any situation in which it would be useful or necessary to "double link" header files? (C++)


I use the term "double link" because I don't know what the actual phrase is, or if there is one, but assuming you have two headers, head1.h and head2.h, with these contents:

In head1.h:

#include"head2.h"
//do stuff

In head2.h:

#include"head1.h"
//do stuff

I visualise it as two mirrors placed opposite each other, as it's not really an infinite loop, but some other form of getting infinity into a finite computer (but I digress). The point is, is there any situation where it would be useful or necessary to use this concept, or a variation of this concept? (ie: I suppose goto could be used as an improv break).


Solution

  • That's a "cyclic include" and no, it's not a desirable thing to do. your goto wouldn't help, because gotos are part of the program execution, while the #includes are interpreted during the preprocessing phase of compiling.

    The usual thing is to make your header files have a structure like

    #ifndef FOO_H
    #define FOO_H
    ... rest of the include file here
    #endif
    

    so they don't attempt to define the same stuff twice.

    Should you try it, here's what happens:

    bash $ gcc crecursive.c In file
    included from bh.h:1,

                from ah.h:1,  
                from bh.h:1,  
                from ah.h:1,   
    

    ... many lines omitted

                from ah.h:1,   
                from crecursive.c:2: ah.h:1:16: error: #include nested too deeply    
    

    bash $