If you keep writing all the code in a single file, it will make clutter. It is very difficult to maintain especially if you are working on a big project.
In this tutorial, you will learn how to create header file in c and how to call a function defined in another file by including the header file in your program.
If you have worked on any standard project, there is a high possibility that you might have seen projects having program file util.C
. It is not a standard but mostly used practice to store all the essential utility functions and variables in a single file and then call it from any of the project files.
How to do that?
Here is the quick tutorial I am sharing to let you understand. You need to create three program files.
Here is a step-by-step procedure with complete code and a detailed explanation with examples.
Write a program and define any function that needs to be called from other files.
int sumOfTwoNumbers(int num1, int num2) { return num1 + num2; }
Save it (says util.C
).
Note: You don’t need to define the function main()
as you are not running this code explicitly. You only need to call the function defined in this program file.
Create a header file in C Program and declare all the functions defined in the above util.C
program file.
int sumOfTwoNumbers(int num1, int num2);
Save the file with the same name but the extension .h
(for you util.h
).
Write a program to call the function defined in util.C
file.
With all the basic header files required, you have to include util.h
.
#include <stdio.h> #include "util.h" int main() { printf("Sum of two numbers: %d", sumOfTwoNumbers(10, 30)); return 0; }
Save this file (says testProg.C
)
You have added stdio.h
file to use printf()
function.
You might have noticed as I have included util.h
file with "---"
mark. While compiling code, the header file is searched in the current directory/folder rather than the C program installed repository.
Just like util.h
header file we have created, there is stdio.h
file already present in the GCC directory. You can use the command to find all header file locations included in your program.
So basically both the functions printf()
and sumOfTwoNumbers()
are defined in the remote file. To use these functions, you need to add respective header files.
Note: Store all the above three program files in the same directory.
The syntax for Compiling multiple files into one output file:
gcc <list_of_program_files_to_be_compiled> -0 <output_file>
In your case,
gcc util.c testProg.c -0 pro
Note: You don’t need to mention the header file while compiling the code.
Run it.
pro
You may need executable permission to execute the output file.
chmod 777 pro
Learn more about Linux file permission.
Now execute,
./pro
Output:
Sum of two numbers: 40
I tried my best to make it simple. Hope you understand this tutorial to create a header file in the C program. If you have any doubts regarding the header file, let’s have a discussion in the comment section below.