3

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?

Mat
  • 202,337
  • 40
  • 393
  • 406
Cartesius00
  • 23,584
  • 43
  • 124
  • 195
  • 1
    What 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
  • 1
    Mostly, 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 Answers5

4

The macro definition is not preserved between separate compilations.

Brett Hale
  • 21,653
  • 2
  • 61
  • 90
2

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!

Nawaz
  • 353,942
  • 115
  • 666
  • 851
2

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

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.)

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
0

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.

dmeister
  • 34,704
  • 19
  • 73
  • 95