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

Join the conversation! Your thoughts help the community grow.