Computer Science Canada

having trouble understanding include guards

Author:  HyperFlexed [ Mon Aug 16, 2010 12:57 pm ]
Post subject:  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
code:
#include <stdio.h>
#include "something-else.h"

// code here...


something-else.c
code:
#include "something-else.h"

// code here...


something-else.h
code:
#ifndef SOMETHING_ELSE_H
#define SOMETHING_ELSE_H
#include <stdio.h>

// code here...

#endif


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.

Author:  TheGuardian001 [ Mon Aug 16, 2010 1:18 pm ]
Post subject:  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


stdio.h will have something along the lines of
code:

#ifndef _STDIO_H
#define _STDIO_H

...

#endif

Author:  chrisbrown [ Mon Aug 16, 2010 1:24 pm ]
Post subject:  RE:having trouble understanding include guards

Include guards are to prevent duplicate <b>definitions</b>, 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.

Author:  HyperFlexed [ Mon Aug 16, 2010 9:41 pm ]
Post subject:  Re: having trouble understanding include guards

had a feeling it was simple. Thanks.


: