Header File
Header file in c is a separate file with .h extension. Header file contains functions used by different source file commonly. Its advantage is re-usability of common code and modular programming approach.
Types of header file
There are two types of header file.
User created header file
You can create header file with extension .h and write different common functions shared by many source files. A header file is included in source file by C preprocessing directive “#include” appended with header file name surrounded by double quotes (“headerfilename.h”) with extension. Example is below
#include "myheaderfile.h"
Build in Header files
These header files comes with C compiler. Most useful header file included in almost all main source files is iostream.h. These header files are included in source file by C processing directive “#include” appended with header file name surrounded by angle brackets <iostream.h> with .h for C and <iostream> without .h for C++.
//for C++
#include <iostream>
Lets write a C++ program to create a header file named myheaderfile.h and define a function which receive Radius of circle as parameter, calculate area of a circle and return it.
myheaderfile.h
float getArea(int rad)
{
const float pi = 3.14;
float area = 2*pi*rad;
return area;
}
Create main source file named main.cpp and include created header file in it as below.
main.cpp
#include <iostream>
#include "myheaderfile.h"
using namespace std;
int main()
{
int radius;
cout<<"Enter radius : ";
cin>>radius;
float area = getArea(radius);
cout<<"Area of circle is:";
cout<<area;
}
C++ program in Dev-C++ editor is below
myheaderfile.h |
main.cpp |
Program Output |
Post a Comment