Sunday, November 24, 2019

How to Create Your own Header Files and Use it to your Program?


Header files are the containers which contains function declarations and definitions. Each header file contains some functions and for using that function we have to include the header file. As for example: for using scanf() and printf() function into our program, we have to include stdio.h header file.
Note: If you have written a function into a program and its header file is missing, then it will show you an error message: "Function should have a prototype". That means you have declared the function, but is definition is missing.
Now let us discuss about creating a header file. As I have told that each header file contains some function definition, so for using that function we have to include the header file first.

CREATING HEADER FILE <soumya.h>
STEP 1: Open any Text Editor such as Notepad(for windows), gedit or featherpad(for linux).
STEP 2: Write down the function definition into it.
STEP 3: Save the file with .h extention. Here I am going to save the file named as Soumya.h.
STEP 4: Copy the header file default location for your C/C++ compiler. In Turbo C/C++ compiler, the default location is: C:\TC\INCLUDE. "Include" folder contains all the header files. You can also view any header file code by opening the header file through the text editor(Notepad/Featherpad/gedit).

ADDING THE HEADER FILE INTO THE PROGRAM
Now as we need to include stdio.h as #include in order to use printf() function. We will also need to include the above header file Soumya.h as #include ”Soumya.h”. The ” ” here are used to instructs the preprocessor to look into the present folder and into the standard folder of all header files if not found in present folder. So, if you wish to use angular brackets instead of ” ” to include your header file you can save it in the standard folder of header files otherwise. If you are using ” ” you need to ensure that the header file you created is saved in the same folder in which you will save the C file using this header file.

Program:
#include <stdio.h>
#include "Soumya.h"
int main()
{
add(12, 10);
/*This calls add function written in Soumya.h
and therefore no compilation error.*/
multiply(5, 6);
// Same for the multiply function in Soumya.h
printf("Thanks for using the App");
return 0;
}

1 comment: