C Header Files
What is a header file?
A header file is a source file that has the .h extension. Header files contain the function prototypes or function declaration, whereas the source code contains the constants, macros, system-wide global variables. Whenever we require the definition of a function, then we simply include that header file in which function is declared.
There are two types of header files defined in a program:
Both the user-defined and system-defined header file can be included in a program with the help of using preprocessing directive (#). These preprocessor directives are used to instruct the compiler to process these files before compilation. There are two forms of including header file:
There is a difference between the header files given above. If the header file is defined within the predefined source path, we can specify the header within the angular brackets. If the header file is not defined within the predefined source path then we can specify the full path of the header file within the double-quotes.
Let's suppose that header.h header file contains the following declaration:
Definition of program.c source file is given below:
Compiler would replace the definition of header.h header file as shown below:
Once only headers
If the header file in a source code is included twice, then it leads to an error, i.e., multiple declarations. To get rid of this problem, there is a standard way of enclosing the real content of the header file in a conditional as follows:
In the above condition, if the header is included, then it will not be included again. If the header file is not included, then the header file will be included. The construct "ifndef" will become false if the header file is included twice and the preprocessor will skip all the contents of the file, and the compiler will ignore the second declaration of the header file.
Let's understand the above scenario through an example.
The following is the source code including the header file:
Create your own header file
Header file is used to avoid writing large and complex code. When we create our own header file then we can simply use wherever we want. It enhances code readability and functionality.
The following are the steps to create our own header file:
Suppose the name of the file is multiply.h.
Some of the header files are given below:
Let's understand the usage of above header files through an example.
In the above code, we have observed the usage of header files like string.h in which strlen() function is defined, and pow() function is defined in math.h header file.