How to write my own header file in C?

Creating your own header file in C allows you to organize and reuse code across multiple programs. A header file typically contains function declarations, constants, and macros that can be included in other C files.

Syntax

#include "your_header_file.h"

Steps to Create a Custom Header File

  1. Create the header file: Write your functions and save with .h extension
  2. Include in main program: Use #include "filename.h" (quotes, not angle brackets)
  3. Ensure same directory: Both files must be in the same folder
  4. Call functions: Use the functions directly in your main program

Header File: sub.h

int sub(int m, int n) {
    return (m - n);
}

Main Program: subtraction.c

#include <stdio.h>

/* Simulating the custom header file content */
int sub(int m, int n) {
    return (m - n);
}

int main() {
    int a = 7, b = 6, res;
    res = sub(a, b);
    printf("Subtraction of two numbers is: %d
", res); return 0; }
Subtraction of two numbers is: 1

Better Practice: Function Declaration in Header

A better approach is to put only function declarations in the header file and definitions in a separate .c file −

math_ops.h

#ifndef MATH_OPS_H
#define MATH_OPS_H

int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);

#endif

Complete Example with Multiple Functions

#include <stdio.h>

/* Function declarations (normally in header file) */
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);

/* Function definitions (normally in separate .c file) */
int add(int a, int b) {
    return a + b;
}

int subtract(int a, int b) {
    return a - b;
}

int multiply(int a, int b) {
    return a * b;
}

int main() {
    int x = 10, y = 5;
    
    printf("Addition: %d + %d = %d
", x, y, add(x, y)); printf("Subtraction: %d - %d = %d
", x, y, subtract(x, y)); printf("Multiplication: %d * %d = %d
", x, y, multiply(x, y)); return 0; }
Addition: 10 + 5 = 15
Subtraction: 10 - 5 = 5
Multiplication: 10 * 5 = 50

Key Points

  • Use "filename.h" for custom headers, <filename.h> for system headers
  • Include header guards (#ifndef, #define, #endif) to prevent multiple inclusions
  • Keep function declarations in .h files and definitions in .c files for larger projects
  • Both header and source files must be in the same directory or specify the correct path

Conclusion

Custom header files promote code reusability and better organization. Always use header guards and separate declarations from definitions for professional C development.

Updated on: 2026-03-15T10:44:18+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements