Do you know how to protect a header file from being included multiple times?
sobes.tech AI
Answer from AI
Yes, I know.
There are two main ways:
-
Using preprocessor directives (
#ifndef,#define,#endif):// filename.h #ifndef FILENAME_H #define FILENAME_H // Contents of the header file #endif // FILENAME_HWhen the file
FILENAME_His included for the first time, the macroFILENAME_His not yet defined, so the code block between#ifndef FILENAME_Hand#endifis processed by the preprocessor. Inside this block, the macroFILENAME_His defined. On subsequent includes of this file within the same translation unit,FILENAME_His already defined, and the code block is ignored. -
Using
#pragma once:// filename.h #pragma once // Contents of the header fileThis directive is non-standard (though supported by most modern compilers) and tells the compiler to include this file only once per translation unit. The compiler tracks this automatically and prevents multiple inclusions.
Comparison:
| Feature | #ifndef/#define |
#pragma once |
|---|---|---|
| Standardization | Part of C/C++ standard | Not part of C/C++ standard |
| Compiler support | Wide (all standard compilers) | Wide (most modern) |
| Ease of use | Requires unique macro name | Simpler, no need for unique macros |
| Portability | More portable | Less portable (but widely supported) |
Both approaches effectively prevent multiple inclusions, which is necessary for correct compilation and avoiding errors related to multiple entity definitions (classes, functions, variables).