0
0
CHow-ToBeginner · 4 min read

How to Create a Header File in C: Simple Guide

To create a header file in C, write function declarations, macros, or constants in a file with a .h extension. Include this header in your .c files using #include "filename.h" to share code between files.
📐

Syntax

A header file in C usually has a .h extension and contains declarations like function prototypes, macros, and constants. Use #ifndef, #define, and #endif to prevent multiple inclusions.

  • #ifndef HEADER_NAME_H: Checks if the header is not defined yet.
  • #define HEADER_NAME_H: Defines the header to avoid re-inclusion.
  • Function prototypes or macro definitions go here.
  • #endif: Ends the conditional inclusion.
c
#ifndef HEADER_FILE_H
#define HEADER_FILE_H

// Function prototype
void greet();

#endif
💻

Example

This example shows how to create a header file with a function prototype and use it in a C program.

c
// greet.h
#ifndef GREET_H
#define GREET_H

void greet();

#endif


// greet.c
#include <stdio.h>
#include "greet.h"

void greet() {
    printf("Hello from the header file!\n");
}


// main.c
#include "greet.h"

int main() {
    greet();
    return 0;
}
Output
Hello from the header file!
⚠️

Common Pitfalls

Common mistakes when creating header files include:

  • Not using include guards, which causes multiple definition errors.
  • Putting function definitions instead of only declarations in header files.
  • Forgetting to include the header file in the source files.
c
// Wrong: Function defined in header (causes multiple definitions)
#ifndef BAD_H
#define BAD_H

#include <stdio.h>

void greet() {
    printf("Hi!\n");
}

#endif

// Right: Only declare in header
#ifndef GOOD_H
#define GOOD_H

void greet();

#endif
📊

Quick Reference

  • Use .h extension for header files.
  • Always add include guards to prevent multiple inclusions.
  • Put only declarations, macros, and constants in headers.
  • Include headers in .c files with #include "filename.h".

Key Takeaways

Create header files with a .h extension containing declarations and include guards.
Use #include "filename.h" in your .c files to access header contents.
Never put function definitions in header files to avoid multiple definition errors.
Include guards (#ifndef, #define, #endif) prevent repeated inclusion problems.
Keep header files focused on declarations, macros, and constants only.