How does one prevent an inclusion cycle in C? ie. You shouldn’t have a.h #include ‘b.h’, which #include’s ‘c.h’ which #include’s ‘a.h’. I’m looking for a way of preventing this from happening using some sort of C directive.
I had originally thought this would’ve prevented this from happening:
Contents of a.h:
#ifndef __A_H #define __A_H #include 'b.h' #endif // __A_H
Contents of b.h:
#ifndef __B_H #define __B_H #include 'c.h' #endif // __B_H
Contents of c.h:
#ifndef __C_H #define __C_H #include 'a.h' #endif // __C_H
But it doesn’t seem to work.
It does work allright: the files are repeatedly included, but the sections protected by #ifdndef/#define/#endif are not repeated, and that breaks the cycle.
Use your compiler to produce the preprocessed output and look at it for yourself. With GNU CC, you need to use ‘-E’ option on the .c[pp] file, like this: