Header files
- C course
- Beginner
- Lesson 110/116
- 5 min
Learn to create your own header files.
Header files and the include guard
A header file (.h) carries declarations; .c files contain definitions. To prevent double inclusion an include guard is used.
#ifndef CONFIG_H
#define CONFIG_H
#define MAX_USERS 10
#endifHere once CONFIG_H is defined, when the file is included a second time its content is skipped. This prevents the same declaration from being compiled twice in multi-file projects. #pragma once serves a similar purpose but is not standard; the safest way is to use an include guard.
Header vs source file split
A .h file contains declarations; a .c file contains definitions. This split shortens compile times in large projects.
/* math_utils.h */
#ifndef MATH_UTILS_H
#define MATH_UTILS_H
int add(int a, int b);
#endif
/* math_utils.c */
#include "math_utils.h"
int add(int a, int b) { return a + b; }Here the .h file only gives the signature of add; the .c writes the body. This way other files can include math_utils.h and use add; math_utils.c is compiled only once.
Practice Print MAX_USERS with the CONFIG_H guard
Write an include guard block with #ifndef CONFIG_H, #define CONFIG_H, #define MAX_USERS 10, #endif. In main print the value of MAX_USERS with printf.
Starter code
#include <stdio.h>
// Define MAX_USERS 10 with the CONFIG_H include guard
int main(void) {
// Print the MAX_USERS value with printf
return 0;
}Sample solution
#ifndef CONFIG_H
#define CONFIG_H
#define MAX_USERS 10
#endif
printf("%d\n", MAX_USERS);Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does an include guard (#ifndef/#define/#endif) do?
- Speeds up the program
- Prevents a header from being included twice Correct answer
- Hides the code
- Resets compilation time
Explanation: An include guard prevents a header from being included twice.
2 Match file type to content
| Term | Meaning |
|---|---|
.h file |
Declarations |
.c file |
Definitions |
include guard |
Prevents double inclusion |
#endif |
Ends the block |
3 Fill in the blank: include guard
____ CONFIG_H
#define CONFIG_H
#define MAX_USERS 10
#endif
#ifndef CONFIG_H
#define CONFIG_H
#define MAX_USERS 10
#endif
Explanation: A block starting with #ifndef forms an include guard.