We can avoid this multiple
inclusion problem in two different ways. First we will look at the conditional
inclusion of pre-processor statements. To do this we should use the #define
in combination with #ifndef.
This is shown below. The #define statement informs the compiler that
mark a macro called TAG and know that it is defined or set for use. So the
header file content is placed in between the #ifndef and #endif
with a very first statement that defines the macro tested by the #ifndef.
![Pic03.JPG]()
First think that compiler comes
to header file when it is referred by the source file(.cpp). Keeping that in
mind, now follow the description given below for the above illustration:
1) Compiler first checks that the
TAG is not already defined.
2) When it is already defined
none of the header file content is included in the referring source file
3) When it is not defined, it
first defines the preprocessor tag TAG. The scope of this TAG is till the
generation of object file for a referring (#include ‘ing source file)
Now look at the change for SimpleMath.h
header file as well as the ExtendedMath.h header file.
#ifndef
_SIMPLEMATH_H__
#define
_SIMPLEMATH_H__
int
Add_Numbers(int, int);
int
Mult_Numbers(int, int);
int
Add_Numbers(int a, int b)
{
return
(a + b);
}
int
Mult_Numbers(int a, int b)
{
return
(a * b);
}
#endif
==
#ifndef
_EXTMATH_H_
#define
_EXTMATH_H_
#include
"SimpleMath.h"
int
Add_three_numbers(int, int, int);
int
Add_three_numbers(int a, int b, int c)
{
return
( Add_Numbers(a, b) * c );
}
#endif
Now
the compilation goes successful as the #include SimpleMath.h inside the
ExtendedMath.h is skipped by the compiler when it is referred from the CppTest.Cpp