The #include is the
pre-processor and the statement is replaced by the file content before the
actual compilation takes place. This leads to situation of getting declaration
or definition twice in a file say ab.cpp when is includes a
header file that includes the one more header file which used by the file
ab.cpp already.
To explain this, let us go with a
simple example.
4.1
SimpleMath.h
Below is the content of the file
and no explanation is required her as it is a two simple function declaration
and its implementation.
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);
}
4.2
ExtendedMath.h
In this header file the basic
mathematic function to add two numbers is extended to support adding three
numbers. In this file, the function to add three numbers is implemented by
making use of the function that adds two numbers, which is already defined in
the SimpleMath.h. So ExtendedMath.h header file
includes the simplemath.h header file. This file content is shown
below:
#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 );
}
Explanation
When the pre-processing (before
the compilation) takes place, the #include is replaced with file content by the
compiler. Also note that the compiler will not generate any object code for the
header file say SimpleMath.obj, extendedmath.obj
4.3
CppTest.cpp
Do you got confused in previous
section when I said compiler will not generate any object code for the header
file say SimpleMath.obj, extendedmath.obj? And you may have question that each
header file provided some processing that computes multiplication as well as
addition. Where is the object code? And How do the linker will create the exe
for those functions?
Right! Compiler will generate
object code for the CPP files. When the CPP file includes the header files,
then file has the replaced content of the header and that replaced content will
go into object file and linker will generate the exe. Look at the code for the
CPP file:
// CPPTST.cpp : Defines the entry point for the
console application.
#include
"stdafx.h"
#include
"SimpleMath.h"
#include
"ExtendedMath.h"
#include
<conio.h>
int
_tmain(int argc, _TCHAR* argv[])
{
return
0;
}
When you compile the above file
or the project, which has this cpp file, you will get the error shown below:

Why?
We will see that reason in the next blog.