patterncppCritical
Why are #ifndef and #define used in C++ header files?
Viewed 0 times
areifndefwhyandusedheaderfilesdefine
Problem
I have been seeing code like this usually in the start of header files:
And at the end of the file is
What is the purpose of this?
#ifndef HEADERFILE_H
#define HEADERFILE_HAnd at the end of the file is
#endifWhat is the purpose of this?
Solution
Those are called #include guards.
Once the header is included, it checks if a unique value (in this case
When the code is included again, the first
That prevents double declaration of any identifiers such as types, enums and static variables.
Once the header is included, it checks if a unique value (in this case
HEADERFILE_H) is defined. Then if it's not defined, it defines it and continues to the rest of the page.When the code is included again, the first
ifndef fails, resulting in a blank file.That prevents double declaration of any identifiers such as types, enums and static variables.
Context
Stack Overflow Q#1653958, score: 757
Revisions (0)
No revisions yet.