Question

When file1.c includes inc.h (containing the include guard #ifndef INC_H) for the first time, the #define INC_H is performed. But now, when another file2.c includes the same inc.h, is the macro INC_H already defined, all it's the same story and previous definition is not propagated here?

Was it helpful?

Solution

But now, when another file2.c includes the same inc.h, is the macro INC_H already defined,

Yes and No. It depends.

  • If file2.c includes some header which includes inc.h, then yes, INC_H is already defined for file2.c. This is true for any level of inclusion.

  • Else, no it is not already defined.

Guards prevent header from being included in a file, indirectly or directly, more than once!

OTHER TIPS

The macro definition is not preserved between separate compilations.

When you complile file2.c, the compiler starts afresh. Whatever preprocessor symbols got defined when file1.c got compiled play no part during the compilation of file2.c.

Definitions are not propagated between *.c files. If they were, you would not need *.h files in the first place. (However, you can #include a *.c file, but that is another story.)

No, think a moment what "#include" does. It essentially copies the contents of the header file to the place where it is included.

So INC_H will be defined the first time inc.h is included in a .c file. However, this changes nothing for another .c file.

Include guards are useful when include files have other include into it. In these cases you can avoid trouble using the guards.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top