Using include guards, wrapping around the entire content of a header file, is a best practice ensuring that no matter how many times the header is
included in a translation unit, its content will only be seen once.
The include guard pattern is made up of four parts:
-
#ifndef
at the top of the file, with a unique macro name (usually, the name relates to the file’s name to ensure uniqueness).
-
#define
with the same macro name.
- The content of the file
-
#endif
at the end of the file
The rule raises an issue when the name in the second part differs from the first (usually because of a typo or a copy/paste issue).
Because the include guard pattern is cumbersome, virtually every compiler provides a non-standard alternative: #pragma once
. This
directive prevents multiple inclusions of the file that contains it without needing to invent a unique macro name for each file. Note that it relies
on the notion of same file, which can be tricky to determine. Additionally, it will not work with build systems that copy headers in
different places.
Noncompliant code example
#ifndef MYFILE_H
#define MY_FILE_H // Noncompliant
//...
#endif
Compliant solution
The most straightforward way is to make both macro names match:
#ifndef MYFILE_H
#define MYFILE_H
//...
#endif
An alternative is to use #pragma once
instead:
#pragma once
//...