A header file is a file with extension .h which contains declarations and macro definitions to be shared between several source files. There are two types of header files:
1. User/Programmer header files
2. System header files
Purpose :
1. To supply the definition of functions, variables, constants and enums.
Both user and system header files are included in the source file using preprocessing directives #include.
There are two ways :
#include <file>
The above form is used for system header files. It searches for a file named "file" in your standard list of system directories.
#include "file"
The above form is used for header file of your own programs. It searches for a file named "file" in the directory containing the current file.
Advantages :
1. Function Ordering not matters
Eliminates the problem of ordering function definition, when no prototype/function declaration was there at the top.
When C compiler runs through your code, every time it sees a function, it looks to see if the function is defined yet.
Eg :
h_file.c
#include<stdio.h> int addition(int j, int k) { int l = 0; float m; l = j + k; m = subtraction(l, j); return l; } main() { int result = 0; result = addition(5, 7); return; } float subtraction(int l, int j) { int k; k = l - j; return k; }
Output :
root@shirley:~/Documents$ cc -o h h_file.c h_file.c:23:8: error: conflicting types for ‘subtraction’
float subtraction(int l, int j)
^
h_file.c:12:9: note: previous implicit declaration of ‘subtraction’ was here
m = subtraction(l, j);
^
The above problem will be resolved, if we include the following header file in the above source file.
h_file.h
#ifndef _H_FILE_H_ // Once-only included file #define _H_FILE_H_ float subtraction(int l, int k); int addition(int j, int k); #endif
Still, we can eliminate the problem with function declaration in the same h_file.c at the top. But including .h file is recommended.
2. Readability
Anyone can read from .h and understand easily, what are all the functions defined.
3. Re usability
In future, if someone wants to use the same function, they can just include .h file in their source file.
4. Easy Error detection
If file1.h and file2.h has same enum definition, it would be easily found during compilation.If file1.c and file2.h has same enum definition, it wouldn't be easily found unless we find it manually. Hence, having .h file is always recommended for a good programming.
Comments
Post a Comment