DECLARATION OF FUNCTIONS IN HEADER FILES

In complex programs the source code is usually broken in more different files called modules. The basic motive for that is faster execution and connectivity of the program. If we change a code of some functions, it would be necessary to translate only module in which the changed function is defined. By translating the program creates new object code of altered module and after translation the new module is linked with existing object code of other modules.
In these kind of programs that consist of many modules it can easily happen that some functions are called from different modules so it is necessary to make declarations of called functions from every program module. Therefore the declared functions are placed in separate header files and these files are called using preprocessor command #include.
Now let’s take a closer look at following example.
#include "stdafx.h"
#include "iostream"
using namespace std;
void function1(); /*declaration of funcion 1*/
void function2(); /*declaration of function 2*/
int _tmain(int argc, _TCHAR* argv[])
{
       function1();
       function2();
       return 0;
}
void function1(){
       //Definition of function1
}
void funcion2(){
       //Defintion of function2
       void function1();
}
The previous code gives us the classic way of writing function inside the .cpp where function main is. Now we will try to break down this code in smaller pieces. So let’s start with creating the function1.cpp. In this file we write the following code.
#include "stdafx.h"
void function1(){
       //Definition of function 1
}

Now we need to create the function1.h which is the header file. The code for header files is:
extern void function1(); //Declaration of function 1
The next step is to create the function2.cpp and function2.h. The code for function2.cpp is:
#include "function1.h"
#include "stdafx.h"
void function2(){
       //
       void function1();
}
and the code for function2.h is:
extern void function2(); //Declaration of function 2

Now the code of main program should look like this:
#include "stdafx.h"
#include "iostream"
#include "function1.h"
#include "function2.h" //Included declaration of functions
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
       function1();
       function2();
       return 0;
}


Share on Google Plus