Header files in C


August 23, 2021, Learn eTutorial
1881

In this tutorial we will learn about header files in C. Mainly focusing on - why we use header files in each and every program, followed by discussing the working of header files and different types of header files in C.

You must have noticed that all the C programs start with a file stdio.h. These types of files with the extension ".h" are called header files. A header file generally includes the definition of all types of frequently used functions, variables, and constants. Apart from these header files contain the macro definitions to be shared between files. Declaring it in the program using #include directive implies that the program can access all the content of the mentioned header file whenever needed. 

For instance, stdio.h is a header file in which stdio stands for standard input and output and .h is the header file extension  This header file basically takes the input given by the user from the keyboard and displays the output on the monitor with the help of some predefined functions like printf(), scanf(), getc(), putc(), gets(), puts() etc. In our last tutorial, we have seen the use of file input-output functions like fprintf(), fscanf(),fgetc(), fputc(), fgets(), fputs() etc. Since all these functions are packaged in stdio.h it is necessary to include stdio.h in a program to achieve the specific task.

Why need header files?

 It is impossible to write every piece of basic code and compile them in each program we write. Also,  there are some common functions we need almost in every program. So it will be customary to write all the required codes in a separate file and keep them ready for use. 

For example,  we need scanf and printf functions very often for access and display purposes. Obviously, there should be a bunch of codes responsible for their proper functioning. These raw source codes are written in the header file "stdio.h" and this is why we have to write "#include <stdio.h>" in almost every program. 

Syntax of Header files

We are now quite familiar with the #include syntax and the functionality of preprocessor directives. Actually, header files are of two types:

  1. Predefined library files  
  2. User-defined header files.  

As the name suggests, predefined library files are files already defined in the system like stdio.h, math.h, etc. Predefined header files are enclosed in angular brackets and the  syntax is like


#include <file_name.h>
 

User-Defined header files contain the files defined by the user which is typically enclosed in double-quotes, the syntax will be :


#include "file_name"  
OR
#include "file_name.h"
 

Here the compiler will look for the mentioned file inside the current directory and import it.

How to create and include user-defined header files in C?

Operation of the #include directive is characterized by just scanning whatever is written in the header file and embedding it in the program. It also works along with maintaining the sequence as defined in the program. Suppose we want to create a header file named "sum.h" which includes the codes for summation of first n natural numbers. To achieve this we first need to write our desired code in an editor and save it with the .h extension because here we are creating a header file. The name of the header file will be the name of the file with .h extension, in our case sum.h.

sum.h


int sum(int num)
{
  int iter,num =0;
  for(iter = 1; iter <= num; iter++)
  {
    sum = sum + iter;
  }
  return sum;
}
 

Here we have used notepad editor and wrote our code in it and saved it as sum.h. Now, we can import this file to our program with #include directive as shown below.


#include
#include "sum.h"

int main()
{
    int number;
    printf("Enter the number:");
    scanf("%d",&number);
    printf("\nSum of first %d numbers is : %d ",number,sum(number));
    return 0;

}
 

The code execution will be performed sequentially and the output will be


Enter the number: 200

Sum of first 200 numbers is : 20100

This way we can enhance code functionality and readability rather than creating a large and complex program.

Note: Both header files and programs should be stored in the same location.

ONCE-ONLY HEADERS IN C

It is a procedure by which we can overcome repetition errors. If we include the same header file twice in a program, the compiler will run the same codes twice. This will definitely result in compilation errors. In large programs, it becomes very hard to check whether a header file has already been included or not. So it will be great if there is a mechanism to protect the program from these mistakes. Such a mechanism is achieved with the help of conditional preprocessor directives like #ifndef ,#define and #endif. These are the commonly used set of codes with conditions, frequently used to get it done and the syntax is as follows.


#ifndef HEADER_FILE_NAME
#define HEADER_FILE_NAME
   Header file content
#endif
 

Example:


#ifndef "test.h"
#define "test.h"
THE CONTENT OF THE HEADER FILE 
#endif
 

So here test. h is the header file and firstly, it will check whether there is a definition of test.h already present in the program or not. If yes, the compiler will exit the 'if' cycle, and control directly shift to closing endif. If the answer is no, then the test.h will be defined and then to the closing endif. This entire mechanism is popularly known as #ifndef wrapper in C programming as it ensures that the code is read-only once by placing the code in between #ifndef and #endif.

MACROS IN C

Till now we have learned how to include header files but without any condition.  But sometimes situations demand the inclusion of multiple files according to the situation or program requirements. In these, we may impose a series of conditions with #include directives, such as :

Definitely, it will be a cumbersome job to write a series of complex codes,  especially when there are lots of conditions that need to be applied. The preprocessor directives of C programming are capable of using a macro in every header file and exploit these features to make programs more compact. It will be a lot easier to put just a macro name after the #include, instead of arguments. This procedure of conditional inclusion of header files is called "computed includes".

Below is a simple example demonstrating the use of macro . 
define FILE1 "file_1.h"
#include FILE1
.....
Here FILE1 is a macro name for header file “file_1.h”. Thus, the macros simplify the inclusion of header files.

Types of Header files in C

Initially, we have seen that header files are classified into two types, ie. the standard header file and user-defined header files. Based on several functionalities these standard header files are further classified and some of the frequently used header files are listed in the table given below. 
 

Sl no Header Files Description Functions ex.
1 stdio.h Standard input output header printf(), scanf(),fread(),fwrite()
2 string.h String header strlen(),strcpy(),strcat(),strcmp()
3 conio.h Console input output header clrscr(),getch()
4 stdlib.h Standard library header calloc(),malloc(),realloc(),free()
5 math.h Math header sqrt(),pow(),exp(),floor()
6 ctype.h Character type header isalpha(),isdigit(),isupper(),islower()
7 assert.h Assertion header assert()
8 time.h Time header getdate(),setdate(),time(),difftime()
9 locale.h Localization header setlocale(),localeconv()
10 signal.h Signal header signal(),raise()
11 stdarg.h Standard argument header va_start(),va_arg()
12 setjmp.h Jump header setjmp(),longjmp()
13 errno.h Error handling header errno()