User Defined Header Files in C
User-defined header files
User-defined header files are created by the programmer and are used to share commonly used code between different parts of a program or between different programs.
They contains declarations for functions, variables, and other code elements.
Header files are used to avoid code repetition, which can save time and reduce errors.
Using User-defined header files
Creating Header File
- Open a text editor or an integrated development environment (IDE).
- Write the declarations for functions, variables, and other code elements that you want to include in the header file.
- Save the file with a
.h
extension. - Example: "filename.h"
Using Header File
- In the C program where you want to include header file, add the following line at the beginning:
#include "filename.h"
- Use the functions or variables declared in the header file in your C program as needed.
Example - Using User-defined header files
Following example illustrates how to create and use a header file:
- Create a new file called "myheader.h" and add the following declaration to it:
int add(int x, int y);
- Save the file.
- Create a new file called "main.c" and add the following code to it
#include "myheader.h"
#include <stdio.h>
int main() {
int a = 5, b = 10, sum;
sum = add(a, b);
printf("The sum of %d and %d is %d\n", a, b, sum);
return 0;
}
- Save the file and compile it using a C compiler.
- Run the program. It should output "The sum of 5 and 10 is 15".
Naming conventions for User-defined header files
Following are some suggested naming conventions for User-defined header files:
Use all lowercase letters: Example "myheader.h"
Use underscores to separate words: Example "my_library.h"
Use a unique prefix: Good practice for large projects
Use a descriptive name: Avoid using generic names like "header.h" or "file.h" and instead use names that describe the contents of the file.