January 04, 2019

Custom Header Files in C

Not long back I wrote an article about Header Files in C. But you mustn't be shocked to know you can design a custom header file in C. Wanna know how? Let's find out.

Custom Header Files in C
Custom Header Files in C

Overview:


What is a Custom Header File?

By now we know that files with .h extension are called header files in C. Such files usually contain function declarations which we use in our main C program as per necessity. For example to use printf() function in a program then we first have to include stdio.h header file. Likewise can we make a custom header file and have self made functions in them?

We very much can. How? Let's find out.



How to create a Custom Header File?

We now observe the following program carefully:

#include<stdio.h>
#include"reversify.h"
void main()
{
    int a=45,b;
    b=reversify(a);
    printf("Reverse=%d\n",b);
}

Method required for reversing digits is written under reversify.h header file. Now you will ask, hey Sukalyan, where and when did you create that header file?
Its right here:

  1. Navigate to the directory where you are saving the above program. I'm naming it as example.c.
  2. Create a new file with extension .h and open it using any text editor.
  3. Inside the header file define what the task of reversify function will be.
  4. Save the file and come back to compiler and execute it to see the results.

Were you wondering what did I write in the custom header file? See below:

int reversify(int &x)
{
     while (x != 0)
     { 
          int y;
          y = y * 10; 
          y = y + n%10; 
          x = x/10; 
      }
      return x;
}

Clearly a variable is accepted and its reverse is given as output.



Finally, after execution of the above program, we get the expected output as below:

Output:

Custom Header File Reversify Output
Custom Header File Reversify Output


All programs written in this post are compiled on Turbo C for PC.

Books I Prefer:



  

I hope this article was helpful to understand custom header files in C! Comment below, if you've got any question. Head back soon for another interesting article on C Programming.