
-----------------------------------
HyperFlexed
Mon Aug 16, 2010 12:57 pm

having trouble understanding include guards
-----------------------------------
I've gotten include guards to work, but now I'd like to understand why they work. The best way to illustrate is an example.

let's say I had main.c and something-else.c, and they both needed stdio.h

main.c
something-else.c
something-else.h
[code]#ifndef SOMETHING_ELSE_H
#define SOMETHING_ELSE_H
#include 

// code here...

#endif[/code]

if I go "gcc main.c something-else.c -o main", the program will compile fine, but as I understand it, stdio.h will be included twice.

stdio.h is included in main.c, then something-else.h is included in main.c. Since SOMETHING_ELSE_H is not defined at this point, it will be defined, and then stdio.h will be included a second time. Why doesn't this cause an error? Is it because each C file is compiled independently, and then linked afterwards? I'm just guessing, so if anyone has the answer I'd be grateful.

-----------------------------------
TheGuardian001
Mon Aug 16, 2010 1:18 pm

Re: having trouble understanding include guards
-----------------------------------
stdio.h has it's own include guards inside.

Just like your header has
[code]
#ifndef SOMETHING_ELSE_H
#define SOMETHING_ELSE_H

...

#endif
[/code]

stdio.h will have something along the lines of
[code]
#ifndef _STDIO_H
#define _STDIO_H

...

#endif
[/code]

-----------------------------------
chrisbrown
Mon Aug 16, 2010 1:24 pm

RE:having trouble understanding include guards
-----------------------------------
Include guards are to prevent duplicate definitions, not duplicate includes. A properly guarded file can be included as many times as you want, because the definitions in that file will be ignored each time except the first. 

Stdio.h - and all standard libraries - are properly guarded, so you need not and should not place it inside the #ifndef.

-----------------------------------
HyperFlexed
Mon Aug 16, 2010 9:41 pm

Re: having trouble understanding include guards
-----------------------------------
had a feeling it was simple. Thanks.
