What is header file?

The file with .h extension is called a header file in C. These header files generally contain function declarations. For example to use scanf() in our main function, we include <stdio.h> header file.


How to create your own header file?

Yes. It is possible. You can create your own header file and use it in the main program.

Here are some steps to create header file

  • Create a Header file.
  • Create definitions to the functions defined.
  • Including the header file.
  • Using the Header file created.
  • Compiling the program.

Create a Header file

Write the code in an empty notepad as shown below and save it as Myfirstheader.h. You can give any meaningful name and save it with .h extension.

Usually, header files contain function declaration and variable declarations.

//Myfirstheader.h
void substract(int a,int b);

Create definitions to the functions defined

Create a c file which has .c extension and then complete the definitions for the functions where declarations are made in header file. Lets name it as definition.c .

//definition.c 
void substract(int a,int b)
{
  printf("Substracted value is %d \n",a-b);
}

Including the header file

Now, include Myfirstheader.h as #include "Myfirstheader.h" in your program. It is the same as including stdio.h header file to use scanf() in the program. The ” ” here means that you have saved the header file you created in the same folder where you have saved the C file.

We name this as main.c

//main.c
#include<stdio.h>
#include "Myfirstheader.h"
int main()
{
  substract(100,45);
  printf("This is an example for header file creation \n");
  return 0;
}

Compiling the Program

Now you have to compile the program and link the object files.

Compile main.c program.

gcc main.c -o main

Compile definition.c program.

gcc definition.c -o definition

Link object files.

gcc main definition -o output

Now execute it.

./output

-o specifies the output file name.

Output

Header file creation

Note

  • In a header file do not use other header files.
  • Don’t put function definitions in a header.
  • Only put what is necessary.

People also ask for

What are the types of header files?

There are two types of header files. The programmer created one and the header file come with the compiler.