C++ Include Guard
When you’re looking at C++ code, you often come across code like this in the header part
1
2
3
4
5
6
7
#ifndef MYHEADER_H
#define MYHEADER_H
// Contents of the header file go here
#endif // MYHEADER_H
What’s the deal with this? Does it have anything to do with conditional compilation? Honestly, one of the reasons C++ feels so challenging to learn is because of its myriad details, which are easy to confuse. Just grasping concepts like references &
, pointers *
, and then there are pointer-to-pointers **
…
Anyway, back to the point, this has nothing to do with conditional compilation. Its purpose is to prevent a header from being included multiple times.
In this example, MYHEADER_H is a custom macro name used to identify the include guard. When a file includes this header for the first time, MYHEADER_H is undefined, so the #ifndef condition is true, and then #define MYHEADER_H defines this macro. When the same header is included again, MYHEADER_H is already defined, so the #ifndef condition fails, and the contents of the header are ignored.
Using an include guard ensures that a header is included only once, thereby avoiding duplicate definitions and conflicts. This is crucial for ensuring correctness and portability of the program. Therefore, it’s recommended to use include guard techniques in all headers, including those for DLL exports.
#pragma once
#pragma once
works exactly like the three lines of include guard written above.
Later, compilers also noticed this issue, so they support #pragma once
to make the syntax more concise.
Most mainstream C++ compilers support #pragma once, including but not limited to:
- GCC (GNU Compiler Collection)
- Clang (LLVM Compiler Infrastructure)
- Microsoft Visual C++
- Intel C++ Compiler
However, there are a few compilers that may not support #pragma once or have limited support. Therefore, if you need to ensure portability of your code, it’s still advisable to use traditional include guards.
Alright, I hope it was helpful to you.