Review:
Nested include files can lead to
recursion !!!
-
Warning
- The nested
include mechanism can
lead to recursive inclusion
|
- Example of a
recusive
file inclusion
chain:
recurse.h
|
include-r.c
|
#include "recurse.h" // Recursive
// include chain
#define MAX 99999
|
#include "header2.h" //Header file
int main( int argc, char* argv[] )
{
int x;
x = MAX;
}
|
- I will now
show you
how to break a
recursive include chain
in this set of slides
|
DEMO:
/home/cs255001/demo/C/1-C-pre/include-r.c
How to make sure that
a header file in
include only once
by the C pre-processor
- Consider
the
header file
named
recurse.h
(or any
header file):
#include "recurse.h" // Recursive include chain
#define MAX 99999
|
- We will use the associated
macro name
recurse_h
to
break
the recursive include chain
- Fact:
- When the C pre-processor
reads a
header file
for the first time,
the name
recurse_h
is not #defined
|
|
DEMO:
/home/cs255001/demo/C/1-C-pre/include-r.c
How to make sure that
a header file in
include only once
by the C pre-processor
- Therefore,
the following
condition directive
will allow the
C pre-processor
the process the
header file
for the first time:
#ifndef recurse_h
#include "recurse.h" // Recursive include chain
#define MAX 99999
#endif
|
- Next, we
need to prevent the
C pre-processor from
processing the
same
include file
again
- Trick:
- If
the name
recurse_h
is #defined,
the #ifndef
conditional directive
will skip the
entire
header file !!
|
|
DEMO:
/home/cs255001/demo/C/1-C-pre/include-r.c
How to make sure that
a header file in
include only once
by the C pre-processor
- Here is the trick:
insert a
#define recurse_h
line into the
header file:
#ifndef recurse_h
#define recurse_h
#include "recurse.h" // Recursive include chain
#define MAX 99999
#endif
|
- When the C pre-processor
read this header file
for
the 2nd time,
it will detect that
recurse_h
has been #defined !
- Result:
- The header file will
not be processed
in the
2nd reading of the
same
header file !!!
|
|
DEMO:
/home/cs255001/demo/C/1-C-pre/include-r.c
❮
❯