Let's say you have a header file, File1.h. You created File1.h with:
#ifndef FILE_1_H
#define FILE_1_H
// Contents of File1.h
#endif
There is nothing in the language to prevent other header files from using the same macro, FILE_1_H
, as include guards.
- A header file in a library you use could have defined that.
- You could use the same header guards in File2.h in your own code base due to copy and paste error.
When that happens, only one of the .h files can be #include
d in a .cpp file. In the best of cases, you will get compiler errors that will allow to fix the problem. In the worst of cases, you will end up using the wrong type or function and the problem will manifest itself at run time.
For these reason, the include guards are not robust and subject to user error.
However, if your compiler supports it and you use
#pragma once
in all your header files, such errors will be avoided.
Please note that use of
#pragma once
has its own set of downsides. See the following for more on that:
Is #pragma once a safe include guard?
What are the dangers of using #pragma once?