Header Files in C

Header files in C contain **function declarations**, **macros**, **constants**, and **definitions** that can be reused across multiple C programs. They allow modular, clean, and maintainable code by separating declarations from implementation.

What is a Header File?

A header file is a file with the extension .h that contains:

Header files are included in a C program using:

#include <filename.h>

Types of Header Files

1. Standard Header Files

These are built-in and already available with your C compiler:

Example: Using a Standard Header File

#include <stdio.h>

int main() {

    printf("Using stdio.h for input/output");

    return 0;
}

2. User Defined Header Files

You can create your own header files to separate reusable code. Example: myfunc.h + myfunc.c

Step 1 — Create the Header File (myfunc.h)

void greet();

Step 2 — Create the Function File (myfunc.c)

#include <stdio.h>
#include "myfunc.h"

void greet() {
    printf("Hello from user-defined header!");
}

Step 3 — Include in Main Program

#include <stdio.h>
#include "myfunc.h"

int main() {

    greet();

    return 0;
}
Note: User-defined headers are included using quotes "filename.h" instead of angle brackets.

How Header Files Work Internally?

The line:

#include <stdio.h>

is expanded by the **preprocessor**, which literally copies the contents of stdio.h into your program before compilation.

Common Mistakes with Header Files

Header Guards (#ifndef / #define)

Used to prevent multiple inclusions.

#ifndef MYFUNC_H
#define MYFUNC_H

void greet();

#endif

Real Life Uses of Header Files

Practice Questions

  1. What is a header file? Explain with example.
  2. Difference between standard and user-defined headers?
  3. Why do we use header guards?
  4. List five commonly used header files and their purpose.
  5. Explain how #include works internally.

Practice Task

Create your own header file mathutils.h with functions for: ✔ addition ✔ subtraction ✔ multiplication ✔ division Use the header in a separate main.c file and test all functions.

5 Complete Examples

/* Example 1 – Using stdio.h */
#include <stdio.h>
int main() {
    printf("Hello Header Files");
    return 0;
}
/* Example 2 – Using math.h */
#include <stdio.h>
#include <math.h>

int main() {
    printf("%.2f", sqrt(25));
    return 0;
}
/* Example 3 – Using string.h */
#include <stdio.h>
#include <string.h>

int main() {
    printf("%lu", strlen("Header"));
    return 0;
}
/* Example 4 – User-defined header */
#include <stdio.h>
#include "myfunc.h"
int main() {
    greet();
    return 0;
}
/* Example 5 – Header guard demonstration */
#ifndef TEMP_H
#define TEMP_H
void hello();
#endif