Header Files in C
Every C program you have written starts with #include <stdio.h>. That line pastes a header file into your program, so the compiler knows what printf looks like. Header files are how C shares declarations between files.
In this lesson you will learn what goes into a header file, the most useful standard headers, how to create your own header file, how include guards stop double inclusion, and how to compile a program made of several files.
What You Will Learn
- What a header file is and what it should contain.
- The difference between
<file.h>and"file.h". - The most important standard header files.
- How to create and use your own header file.
- Include guards and
#pragma once. - How to compile several .c files together.
Header Files in C Explained
Exam definition: A header file is a file with the extension .h that contains C declarations (function prototypes, macros, type definitions, structure declarations and extern variable declarations) to be shared between source files. It is inserted into a source file with the #include directive. Header files are of two types: standard (system) header files, supplied with the compiler, and user-defined header files, written by the programmer.
Memory trick: A header file is the menu card of a restaurant: it lists what dishes exist (function names and their ingredients/parameters). The kitchen (the .c file) actually cooks them. You read the menu to order; you never need to see the kitchen.
What goes in a header file (and what doesn't)
| Put in the .h file | Keep in the .c file |
|---|---|
Function prototypes: int add(int a, int b); | Function bodies (definitions) |
Macros: #define PI 3.14159 | Global variable definitions: int count = 0; |
Structure, union and enum declarations, typedefs | main() |
extern declarations: extern int count; | Helper functions used only in that file (static) |
Syntax of #include
#include <stdio.h> /* standard header: searched in the system include folders */
#include "student.h" /* your header: searched in the current folder first,
then in the system folders */
Common standard header files
| Header | Gives you |
|---|---|
<stdio.h> | Input/output: printf, scanf, fopen, fgets |
<stdlib.h> | malloc, free, atoi, rand, exit, qsort |
<string.h> | strlen, strcpy, strcmp, strcat, memset |
<math.h> | sqrt, pow, sin, cos, floor, ceil (link with -lm) |
<ctype.h> | isdigit, isalpha, toupper, tolower |
<time.h> | time, clock, difftime |
<stdbool.h> | bool, true, false |
<limits.h> | INT_MAX, INT_MIN, CHAR_BIT |
Example 1: Creating Your Own Header File
The project has three files. Save them in the same folder.
mathutil.h: the declarations (the "menu")
#ifndef MATHUTIL_H
#define MATHUTIL_H
#define PI 3.14159
int add(int a, int b);
int factorial(int n);
double circle_area(double r);
#endif
mathutil.c: the definitions (the "kitchen")
#include "mathutil.h"
int add(int a, int b)
{
return a + b;
}
int factorial(int n)
{
int f = 1, i;
for (i = 2; i <= n; i++)
f *= i;
return f;
}
double circle_area(double r)
{
return PI * r * r;
}
main.c: the program that uses them
#include <stdio.h>
#include "mathutil.h"
#include "mathutil.h" /* included twice on purpose: the guard makes it safe */
int main(void)
{
printf("add(7, 5) = %d\n", add(7, 5));
printf("factorial(5) = %d\n", factorial(5));
printf("circle_area(3) = %.2f\n", circle_area(3));
printf("PI from header = %.5f\n", PI);
return 0;
}
Compile both .c files together (never compile the .h file itself):
gcc main.c mathutil.c -o app
./app
Output
add(7, 5) = 12 factorial(5) = 120 circle_area(3) = 28.27 PI from header = 3.14159
Code Explanation
- mathutil.h contains only prototypes and a macro. It tells any file that includes it: "these functions exist, and this is how to call them".
- mathutil.c includes its own header (a good habit: the compiler then checks that the definitions match the prototypes) and defines the functions.
- main.c includes the header, so the compiler knows
add,factorial,circle_areaandPIwhile compiling main.c. - The linker joins main.o and mathutil.o, connecting each call in main.c with the real function in mathutil.c.
- The header is included twice, yet there is no error, thanks to the include guard explained next.
How #include and Include Guards Work
#include simply copies the whole file into that place. If a header is included twice, its contents appear twice. Prototypes and macros can repeat, but a struct definition can't, so double inclusion causes "redefinition" errors. An include guard prevents this:
First #include "mathutil.h"
#ifndef MATHUTIL_H -> not defined yet, so ENTER
#define MATHUTIL_H -> now it is defined
...declarations are kept...
#endif
Second #include "mathutil.h"
#ifndef MATHUTIL_H -> already defined, so SKIP everything
#endif
Most compilers also support a shorter form at the top of the header: #pragma once. It does the same job, but it is not part of the C standard, so include guards are the safest choice for exams.
Name the guard after the file in capitals: student.h → STUDENT_H.
Example 2: A Header with a Structure
Structures shared between files also belong in a header. This header needs its guard, because a structure can't be defined twice.
#ifndef STUDENT_H
#define STUDENT_H
#define MAX_NAME 30
struct student
{
int roll;
char name[MAX_NAME];
float marks;
};
void print_student(const struct student *s);
char grade_of(float marks);
#endif
#include <stdio.h>
#include "student.h"
char grade_of(float marks)
{
if (marks >= 75) return 'A';
if (marks >= 60) return 'B';
if (marks >= 40) return 'C';
return 'F';
}
void print_student(const struct student *s)
{
printf("%-3d %-8s %6.1f %c\n", s->roll, s->name, s->marks, grade_of(s->marks));
}
#include <stdio.h>
#include "student.h"
int main(void)
{
struct student list[3] = {
{1, "Aarav", 82.5f},
{2, "Diya", 64.0f},
{3, "Kabir", 38.5f}
};
int i;
printf("Roll Name Marks Grade\n");
for (i = 0; i < 3; i++)
print_student(&list[i]);
return 0;
}
gcc report.c student.c -o report
Output
Roll Name Marks Grade 1 Aarav 82.5 A 2 Diya 64.0 B 3 Kabir 38.5 F
- Both student.c and report.c include
student.h, so they agree on the exact layout ofstruct student. - Any change to the structure is made in one place (the header), and every file picks it up.
MAX_NAMEis a macro shared through the header too.
Important Points to Remember
- Header files (.h) hold declarations; .c files hold definitions.
< >for standard headers;" "for your own headers.- Always protect a header with an include guard (or
#pragma once). - Include a module's own header in its .c file so prototypes and definitions are checked against each other.
- Compile all .c files together; never compile or link a .h file directly.
- Don't define variables or function bodies in a header; that causes "multiple definition" errors.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
| No include guard | "redefinition of struct" when included twice | Add #ifndef X_H / #define X_H / #endif |
| Function body in the header | "multiple definition" at link time | Keep only the prototype in the .h file |
#include <mathutil.h> | "file not found" | Use quotes for your own headers |
| Compiling only main.c | "undefined reference to add" | gcc main.c mathutil.c |
| Including a .c file | Duplicate functions, slow builds | Include only .h files |
Header Files Practice Questions
- What is a header file? Name its two types.
- What should and shouldn't be written in a header file?
- What is an include guard, and why is it needed?
- Name the header files for
strlen,sqrtandmalloc. - How do you compile a program made of main.c and calc.c?
Show answers
- A .h file containing declarations shared between source files; standard (system) and user-defined header files.
- Should: prototypes, macros, types, structures, extern declarations. Shouldn't: function bodies and variable definitions.
- An
#ifndef/#define/#endifwrapper that makes the header's contents appear only once even if it is included several times, avoiding redefinition errors. <string.h>,<math.h>,<stdlib.h>.gcc main.c calc.c -o app.
Coding Exercise
Create temperature.h with an include guard and prototypes for double c_to_f(double c) and double f_to_c(double f), define them in temperature.c, and write convert.c that prints 37°C in Fahrenheit and 212°F in Celsius.
Show solution
#ifndef TEMPERATURE_H
#define TEMPERATURE_H
double c_to_f(double c);
double f_to_c(double f);
#endif
#include "temperature.h"
double c_to_f(double c)
{
return c * 9.0 / 5.0 + 32.0;
}
double f_to_c(double f)
{
return (f - 32.0) * 5.0 / 9.0;
}
#include <stdio.h>
#include "temperature.h"
int main(void)
{
printf("37 C = %.1f F\n", c_to_f(37));
printf("212 F = %.1f C\n", f_to_c(212));
return 0;
}
37 C = 98.6 F 212 F = 100.0 C
Compile with gcc convert.c temperature.c -o convert.
Quick Quiz: Header Files (MCQ)
-
The extension of a header file is:
A) .c B) .h C) .hd D) .o
-
Which is the correct way to include your own header?
A)
#include <my.h>B)#include "my.h"C)#import my.hD)include my.h; -
Which should NOT be placed in a header file?
A) A prototype B) A macro C) A function body D) A struct declaration
-
An include guard uses:
A)
#if 0B)#ifndef,#define,#endifC)#errorD)#undefonly -
sqrt()is declared in:A) stdio.h B) stdlib.h C) math.h D) string.h
Show answers
- B: .h.
- B:
#include "my.h". - C: a function body.
- B:
#ifndef,#define,#endif. - C: math.h.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Header file | .h file with shared declarations |
|---|---|
| Two types | Standard and user-defined |
| <file.h> | Searches system folders |
| "file.h" | Searches the current folder first |
| Include guard | #ifndef / #define / #endif: include only once |
| #pragma once | Short, non-standard alternative |
| Compile | gcc main.c util.c (not the .h) |
Frequently asked questions
- What is a header file in C?
- A .h file containing declarations (prototypes, macros, types) that is pasted into source files with #include.
- How do you create your own header file?
- Write the prototypes in a .h file with an include guard, define the functions in a .c file, include the header with quotes and compile the .c files together.
- Why are include guards used?
- To stop a header's contents from being included twice, which would cause redefinition errors.
Remember
- Header = menu card; .c file = kitchen.
- Every header gets an include guard.
Next Topic
Next lesson: Conditional Compilation in C. You will use #if, #ifdef, #ifndef and #error to compile different code for debug builds, versions and operating systems.