Site Tools


header-guard

**This is an old revision of the document!**

Table of Contents

Header guard

Header guards are a pattern used in C and C++ programming languages when writing header files. Header files (.h files) are files that are included in source files (.c and .cpp files) using the #include <...> directive. They are used to allow multiple inclusions of the same file but prevent multiple definition errors.

Header guards follow the same general pattern:

#ifndef __HEADER_GUARD_H__
#define __HEADER_GUARD_H__
 
// ...
 
#endif

In C and C++ programming languages, #include is nothing but text substitution. If you include something multiple times

Example

A prototypical example of a header guard is the following.

// hello_world.h
#ifndef __HELLO_WORLD_H__
#define __HELLO_WORLD_H__
 
struct Hello {
    const char *text = "world";
};
 
#endif /* __HELLO_WORLD_H__ */

Why?

// main.c
#include <hello_world.h>
#include <hello_world.h>
 
int main() {
    Hello world;
    return 0;
}
header-guard.1778763568.txt.gz ยท Last modified: by yanevskiv