C · Chapter 37 of 45

C Header Files

Header files (with a .h extension) let you share declarations — like function prototypes, structs, and macros — across multiple source files. This promotes modular, organized code.

Header guards (using #ifndef/#define/#endif, or #pragma once) prevent a header's contents from being included more than once in the same file, which would otherwise cause duplicate-declaration errors.

Syntax
#ifndef MYHEADER_H
#define MYHEADER_H
// declarations
#endif

Creating a header file

A header typically contains function prototypes, struct/typedef definitions, and macros — but usually not full function bodies (except for inline or static functions). You #include it in any .c file that needs those declarations.

Header guards

Wrapping a header's content in `#ifndef HEADER_H`, `#define HEADER_H`, ... `#endif` ensures its contents are only processed once, even if the header is included from multiple files.

Example 1 (c)
// mymath.h
#ifndef MYMATH_H
#define MYMATH_H

int square(int n);

#endif
Output
(no output — header file)

The header guard prevents this content from being included twice in one translation unit.

Example 2 (c)
// main.c
#include <stdio.h>
#include "mymath.h"

int square(int n) { return n * n; }

int main() {
  printf("%d\n", square(4));
  return 0;
}
Output
16

Quotes ("mymath.h") tell the compiler to look for the header in the local project directory.

Key points

  • Header files (.h) share declarations across multiple .c files.
  • Angle brackets <> include standard library headers; quotes "" include local headers.
  • Header guards prevent multiple-inclusion errors.
  • Headers typically hold declarations, not full function implementations.
💡 Note: Modern compilers also support `#pragma once` as a simpler alternative to traditional header guards.

📝 Quick Quiz

1. What is the purpose of a header guard?

2. Which include syntax is used for your own project headers?

3. What do header files typically contain?