Header Files in C Programming

A header file in C programming language is a file with .h extension which contains a set of common function declarations and macro definitions which can be shared across multiple program files. C language provides a set of in build header files which contains commonly used utility functions and macros.

For Example:
  • stdio.h header file contains standard Input and Output functions.
  • string.h header file contains string handling functions.

Types of Header Files in C

  • User defined header files.
  • In-built header files.
#inclide Preprocessor Directives is used to include both system header files and user defined header files in C Program.

Syntax to Include Header File in C Program
#include <Header_file_name>

Above mentioned #include syntax is used to include in-built system header files. It searches given header file in a standard list of directories where all in-built header files are stored. To include in-built header file we use triangular bracket.

#include "Header_file_name"

Above mentioned #include syntax is used to include user-defined system header files. It searches given user defined header file in a current directories where current c program exists. To include user-defined header file we use double quotes.

For Example:
#include <math.h>          // Standard Header File
#include "myHeaderFile.h"    // User Defined Header File
Including a header file in a c program is equivalent to copying the content of the header file in your program. Above statement tells the preprocessor to replace this line with content of math.h header file.

Create Your Own Header File in C

Steps to create your own header file
  1. Open a text editor and type a function definition, like we define a new function in C program.
    int getSquare(int num){
       return num*num;
    }
    

  2. Save this file with .h extension. Lets assume we saved this file as myMath.h.

  3. Copy myMath.h header file to the same directory where other inbuilt header files are stored.

  4. Compile this file.

  5. To Include your new header file in a c program used #include preprocessor directive.
    #include "myMath.h" 
    

  6. Now you can directly call any function define inside myMath.h header file.

#include <stdio.h>
#include "myMath.c" 

int main(){
    int number;
    
    printf("Enter an Integer\n");
    scanf("%d", number);
    printf("Square of %d is %d\n", number, getSquare(number));
    
    return 0;
}
Conditionally Including a Header File in C Program

Sometimes, we may want to include some header file or select one out of many header if some condition is true. This is useful, when we have system dependent functions and macros defined in separate header files.

#if Condition_One
   # include "headerFile_One.h"
#elif Condition_Two
   # include "headerFile_Two.h"
#elif Condition_Three
   # include "headerFile_Three.h"
  .
  .
#endif