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?
- 195,986
- 40
- 382
- 396
- 22,610
- 41
- 119
- 191
-
1What this question could use is a good dose of [sample code](http://sscce.org/), some that's complete & concise. – outis Nov 25 '11 at 11:57
-
It's explicit, no sample code needed. – Cartesius00 Nov 25 '11 at 11:59
-
@James: it's not explicit enough. You haven't specified if you compiled the two C files separately or as a single compilation unit. – Mat Nov 25 '11 at 12:00
-
@Mat, really? Common sense says he's not concatenating two C files. It's a straightforward question. – Brett Hale Nov 25 '11 at 12:06
-
1@BrettHale: common sense answers the question once you've learnt a bit of C and thought about it. – Mat Nov 25 '11 at 12:08
-
1Mostly, I can't quite understand the English. Sample code should clear up exactly what James is asking about. – outis Nov 25 '11 at 12:12
5 Answers
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.cincludes some header which includesinc.h, then yes,INC_His already defined forfile2.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!
- 341,464
- 111
- 648
- 831
-
It contradicts another answers claiming, that two compilations of distinct `*.c` files don't share any new definitions. – Cartesius00 Nov 25 '11 at 11:57
-
1
-
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.
- 464,258
- 100
- 912
- 987
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.)
- 194,726
- 35
- 326
- 406
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.
- 33,450
- 19
- 69
- 93