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.
#ifndef MYHEADER_H
#define MYHEADER_H
// declarations
#endifCreating 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.
// mymath.h
#ifndef MYMATH_H
#define MYMATH_H
int square(int n);
#endif(no output — header file)The header guard prevents this content from being included twice in one translation unit.
// main.c
#include <stdio.h>
#include "mymath.h"
int square(int n) { return n * n; }
int main() {
printf("%d\n", square(4));
return 0;
}16Quotes ("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.
