The Wayback Machine - https://web.archive.org/web/20241109112334/https://www.geeksforgeeks.org/write-header-file-c/
Open In App

How to write your own header file in C?

Last Updated : 24 Oct, 2017
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

As we all know that files with .h extension are called header files in C. These header files generally contain function declarations which we can be used in our main C program, like for e.g. there is need to include stdio.h in our C program to use function printf() in the program. So the question arises, is it possible to create your own header file?

The answer to the above is yes. header files are simply files in which you can declare your own functions that you can use in your main program or these can be used while writing large C programs.
NOTE:Header files generally contain definitions of data types, function prototypes and C preprocessor commands.

Below is the short example of creating your own header file and using it accordingly.

  1. Creating myhead.h : Write the below code and then save the file as myhead.h or you can give any name but the extension should be .h indicating its a header file.




    // It is not recommended to put function definitions 
    // in a header file. Ideally there should be only
    // function declarations. Purpose of this code is
    // to only demonstrate working of header files.
    void add(int a, int b)
    {
        printf("Added value=%d\n", a + b);
    }
    void multiply(int a, int b)
    {
        printf("Multiplied value=%d\n", a * b);
    }

    
    

  2. Including the .h file in other program : Now as we need to include stdio.h as #include in order to use printf() function. We will also need to include the above header file myhead.h as #include”myhead.h”. The ” ” here are used to instructs the preprocessor to look into the present folder and into the standard folder of all header files if not found in present folder. So, if you wish to use angular brackets instead of ” ” to include your header file you can save it in the standard folder of header files otherwise. If you are using ” ” you need to ensure that the header file you created is saved in the same folder in which you will save the C file using this header file.
  3. Using the created header file :




    // C program to use the above created header file
    #include <stdio.h>
    #include "myhead.h"
    int main()
    {
        add(4, 6);
      
        /*This calls add function written in myhead.h  
          and therefore no compilation error.*/
        multiply(5, 5);
      
        // Same for the multiply function in myhead.h
        printf("BYE!See you Soon");
        return 0;
    }

    
    

    Output:

    Added value:10
    Multiplied value:25
    BYE!See you Soon
    

    NOTE : The above code compiles successfully and prints the above output only if you have created the header file and saved it in the same folder the above c file is saved.

Important Points:
The creation of header files are needed generally while writing large C programs so that the modules can share the function definitions, prototypes etc.

  • Function and type declarations, global variables, structure declarations and in some cases, inline functions; definitions which need to be centralized in one file.
  • In a header file, do not use redundant or other header files; only minimal set of statements.
  • Don’t put function definitions in a header. Put these things in a separate .c file.
  • Include Declarations for functions and variables whose definitions will be visible to the linker. Also, definitions of data structures and enumerations that are shared among multiple source files.
  • In short, Put only what is necessary and keep the header file concised.

This article is merely to give you idea about the creation of header files and using the same but this is not what actually happens when you write a large C program. The creation of header files are needed generally while writing large C programs so that the modules can share the function definitions, prototypes etc.



Previous Article
Next Article

Similar Reads

How to Write Your Own printf() in C?
In this article, we will learn how to implement your own custom printf() function in C language. The printf() function is present in <stdio.h> header and uses a const char* and variable length arguments as its parameters. Hence we would be using <stdarg.h> header file which provides operations available on variable arguments passed to a
4 min read
Write your own strlen() for a long string padded with '\0's
Given a big character array that represents a string such that all trailing non-string characters are filled with '\0' at the end, i.e, all leading characters are string characters, all trailing are '\0' and no garbage characters. Write an efficient function to find length of such a string. Examples: Input: str[] = {'g', 'e', 'e', 'k', '\0', '\0',
3 min read
Write your own memcpy() and memmove()
The memcpy function is used to copy a block of data from a source address to a destination address. Below is its prototype. void * memcpy(void * destination, const void * source, size_t num);The idea is to simply typecast given addresses to char *(char takes 1 byte). Then one by one copy data from source to destination. Below is implementation of t
4 min read
Implement your own tail (Read last n lines of a huge file)
Given a huge file having dynamic data, write a program to read last n lines from the file at any point without reading the entire file. The problem is similar to tail command in linux which displays the last few lines of a file. It is mostly used for viewing log file updates as these updates are appended to the log files. Source : Microsoft Intervi
4 min read
When should we write our own assignment operator in C++?
The answer is same as Copy Constructor. If a class doesn't contain pointers, then there is no need to write assignment operator and copy constructor. The compiler creates a default copy constructor and assignment operators for every class. The compiler created copy constructor and assignment operator may not be sufficient when we have pointers or a
3 min read
Implement Your Own sizeof
Here is an implementation. #include<stdio.h> #define my_sizeof(type) (char *)(&type+1)-(char*)(&type) int main() { double x; printf("%ld", my_sizeof(x)); getchar(); return 0; } Type is like a local variable to the macro. &type gives the address of the variable (double x) declared in the program and incrementing it with 1
2 min read
How to Create Your Own scanf() in C?
The scanf() function is used to take input from the console. It is defined in <stdio.h> header file and takes const char* and variable argument list as parameters. In this article, we will learn how to implement your own custom scanf() function in C language. For this, we need to have a firm grasp of the following concepts: Prerequisites: Var
3 min read
Implement Your Own itoa()
The itoa function converts an integer into a null-terminated string. It can convert negative numbers too. It is a standard library function that is defined inside stdlib.h header file. Syntax of itoa in Cchar* itoa(int num, char* buffer, int base);In this article, we create a C Program to implement a custom function that will be able to convert the
4 min read
Making your own Linux Shell in C
To know more about what a shell is, click here. We all use the built in terminal window in Linux distributions like Ubuntu, Fedora, etc. But how do they actually work? In this article, We are going to handle some under the hood features and algorithms what actually work inside a shell. All Linux operating systems have a terminal window to write in
7 min read
Difference between Header file and Library
Header Files: The files that tell the compiler how to call some functionality (without knowing how the functionality actually works) are called header files. They contain the function prototypes. They also contain Data types and constants used with the libraries. We use #include to use these header files in programs. These files end with .h extensi
3 min read
Comment in header file name?
What happens if there is a comment in header file name? Parsing of `#include' is slightly special because comments are not recognized within the ''. Thus, in `#include ' the `/*' does not start a comment and the directive specifies inclusion of a system header file named `x/*y'. Of course, a header file with such a name is unlikely to exist on Unix
1 min read
Print "Hello World" in C/C++ without using any header file
Write a C/C++ program that prints Hello World without including any header file. Conceptually it's seems impractical to write a C/C++ program that print Hello World without using a header file of "stdio.h". Since the declaration of printf() function contains in the "stdio.h" header file. But we can easily achieve this by taking the advantage of C p
2 min read
cJSON - JSON File Write/Read/Modify in C
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and machines alike. JSON is widely used for data exchange between applications and web services. In this article, we will discuss how to read and write JSON data in the C programming language. JSON in C JSON in C can be handled using
6 min read
fopen() for an existing file in write mode
In C, fopen() is used to open a file in different modes. To open a file in write mode, "w" is specified. When mode "w" is specified, it creates an empty file for output operations. What if the file already exists? If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. For example, in the
2 min read
Write a C program that displays contents of a given file like 'more' utility in Linux
Write a C program that displays contents of given line page by page. Given number of lines to show as 'n' at a time and a file name, the program should first show n lines, then wait for user to hit a key before showing next n lines and so on. We strongly recommend to minimize the browser and try this yourself first. We can open the given file and p
2 min read
lseek() in C/C++ to read the alternate nth byte and write it in another file
From a given file (e.g. input.txt) read the alternate nth byte and write it on another file with the help of “lseek”. lseek (C System Call): lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms. Function Definition off_t lseek(int fild
2 min read
Read/Write Structure From/to a File in C
For writing in the file, it is easy to write string or int to file using fprintf and putc, but you might have faced difficulty when writing contents of the struct. fwrite and fread make tasks easier when you want to write and read blocks of data. Writing Structure to a File using fwriteWe can use fwrite() function to easily write a structure in a f
3 min read
What’s difference between header files "stdio.h" and "stdlib.h" ?
These are two important header files used in C programming. While “<stdio.h>” is header file for Standard Input Output, “<stdlib.h>” is header file for Standard Library. One easy way to differentiate these two header files is that “<stdio.h>” contains declaration of printf() and scanf() while “<stdlib.h>” contains declaratio
2 min read
numeric header in C++ STL | Set 2 (adjacent_difference(), inner_product() and iota())
The numeric header is part of the numeric library in C++ STL. This library consists of basic mathematical functions and types, as well as optimized numeric arrays and support for random number generation. Some of the functions in the numeric header: iotaaccumulatereduceinner_productpartial_sum etc. See this article for more reference: accumulate()
4 min read
Header Files in C
In C language, header files contain a set of predefined standard library functions. The .h is the extension of the header files in C and we request to use a header file in our program by including it with the C preprocessing directive "#include". C Header files offer the features like library functions, data types, macros, etc by importing them int
7 min read
C program to copy contents of one file to another file
[GFGTABS] C #include <stdio.h> #include <stdlib.h> // For exit() int main() { FILE *fptr1, *fptr2; char filename[100]; int c; printf("Enter the filename to open for reading: "); scanf("%s", filename); // Open one file for reading fptr1 = fopen(filename, "r"); if (fptr1 == NULL) { printf("Cannot open fi
1 min read
Write a one line C function to round floating point numbers
Algorithm: roundNo(num) 1. If num is positive then add 0.5. 2. Else subtract 0.5. 3. Type cast the result to int and return. Example: num = 1.67, (int) num + 0.5 = (int)2.17 = 2 num = -1.67, (int) num - 0.5 = -(int)2.17 = -2 Implementation: /* Program for rounding floating point numbers */ # include<stdio.h> int roundNo(float num) { return nu
1 min read
Write a C macro PRINT(x) which prints x
At the first look, it seems that writing a C macro which prints its argument is child's play. Following program should work i.e. it should print x C/C++ Code #define PRINT(x) (x) int main() { printf("%s", PRINT(x)); return 0; } But it would issue compile error because the data type of x, which is taken as variable by the compiler, is unkn
1 min read
Write one line functions for strcat() and strcmp()
Recursion can be used to do both tasks in one line. Below are one line implementations for stracat() and strcmp(). /* my_strcat(dest, src) copies data of src to dest. To do so, it first reaches end of the string dest using recursive calls my_strcat(++dest, src). Once end of dest is reached, data is copied using (*dest++ = *src++)? my_strcat(dest, s
2 min read
Write a C program to print "Geeks for Geeks" without using a semicolon
First of all we have to understand how printf() function works. Prototype of printf() function is: int printf( const char *format , ...) Parameter format: This is a string that contains a text to be written to stdout.Additional arguments: ... (Three dots are called ellipses) which indicates the variable number of arguments depending upon the format
2 min read
Write a C program that does not terminate when Ctrl+C is pressed
Write a C program that doesn't terminate when Ctrl+C is pressed. It prints a message "Cannot be terminated using Ctrl+c" and continues execution. We can use signal handling in C for this. When Ctrl+C is pressed, SIGINT signal is generated, we can catch this signal and run our defined signal handler. C standard defines following 6 signals in signal.
2 min read
Write a C program that won't compile in C++
Although C++ is designed to have backward compatibility with C, there can be many C programs that would produce compiler errors when compiled with a C++ compiler. Following is the list of the C programs that won’t compile in C++: Calling a function before the declarationUsing normal pointer with const variableUsing typecasted pointersDeclaring cons
4 min read
Write a program that produces different results in C and C++
Write a program that compiles and runs both in C and C++, but produces different results when compiled by C and C++ compilers. There can be many such programs, following are some of them. 1) Character literals are treated differently in C and C++. In C character literals like 'a', 'b', ..etc are treated as integers, while as characters in C++. (See
2 min read
How to write a running C code without main()?
Write a C language code that prints GeeksforGeeks without any main function. Logically it's seems impossible to write a C program without using a main() function. Since every program must have a main() function because:- It's an entry point of every C/C++ program.All Predefined and User-defined Functions are called directly or indirectly through th
2 min read
How to write long strings in Multi-lines C/C++?
Image a situation where we want to use or print a long long string in C or C++, how to do this? In C/C++, we can break a string at any point in the middle using two double quotes in the middle. Below is a simple example to demonstrate the same. C/C++ Code #include<stdio.h> int main() { // We can put two double quotes anywhere in a string char
2 min read
Article Tags :
three90RightbarBannerImg