What is the purpose of header guards (#ifndef) versus #pragma once?
Last updated
Both prevent a header's contents from being included more than once in a single translation unit, which would cause redefinition errors. Header guards use standard preprocessor macros; #pragma once is a non-standard but widely supported compiler directive that does the same thing more conveniently.
Header guards (
#ifndef):Wrap the file in
#ifndef X / #define X / #endifso the body compiles only once.Fully portable (standard C++), but you must pick a unique macro name or risk collisions.
#pragma once:One line, no macro to invent, and the compiler tracks files by identity.
Non-standard (though supported by all major compilers) and can misbehave with odd filesystems, symlinks, or copied files.
Rule of thumb: Use
#pragma oncefor convenience; prefer (or combine with) guards when strict portability matters.
[lang:cpp]
#ifndef MY_WIDGET_H
#define MY_WIDGET_H
// ... declarations ...
#endif
// equivalent, simpler:
#pragma once
// ... declarations ...