Include loops in C header files

How do I prevent an include loop in C? i.e. You shouldn't have ah #include "bh" which #include "ch" which #include "ah". I'm looking for a way to prevent this by using some sort of C directive.

I originally thought this would prevent this:

Content ah:

#ifndef __A_H
#define __A_H

#include "b.h"

#endif // __A_H

      

Bh content:

#ifndef __B_H
#define __B_H

#include "c.h"

#endif // __B_H

      

Ch content:

#ifndef __C_H
#define __C_H

#include "a.h"

#endif // __C_H

      

But it doesn't work.

+1


source to share


5 answers


It works fine: files re-enabled, but sections protected by # ifdndef / # define / # endif are not repeated and this breaks the loop.

Use your compiler to get the preprocessed output and look at it for yourself. With GNU CC, you need to use the "-E" option in the .c [pp] file, for example:



gcc -E $(CFLAGS) -o foo.i foo.cpp

      

+7


source


Macros with leading underscores are reserved for the preprocessor / compiler.



Try changing __ * _ H to something more standard.
I am using HAVE __ * _ H.

+1


source


This should work. It is written correctly in your example and compiles fine for me. Have you made a mistake in your actual code, or is this really some other problem you are seeing?

You don't have to run everything with __, though, as is reserved for the compiler and / or system libraries. Try other names for your guards.

+1


source


ya in addition to the above things, if you are working on turbo c and you are making a project with these source files, then don't add the header files that are # included in the source files. And even then, if it doesn't, then try it from the command line, because some compiler options give these errors over and over again. Here, if the content of the header files is between #ifndef and #endif, then there will be no problem even with both files. So try removing the header files from the project, keeping them in the same directory. Bcos u did not specify the environment i specified by turbo C because I ran into this situation once on turbo C with # header files included in the source file and attached to the project file list then there will be a "multiple declarations problem".also after compiling (even with errors) go to external command line and change to the directory where this file is stored and try with filename.exe direct.ok

+1


source


It works.

To be sure, I actually compiled test.c which included ah with your 3 header files.

I have confirmed that this works for multiple versions of MSVC, Digital Mars and GCC.

0


source







All Articles