Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are #ifndef and #define used in C++ header files?

I have been seeing code like this usually in the start of header files:

#ifndef HEADERFILE_H #define HEADERFILE_H 

And at the end of the file is

#endif 

What is the purpose of this?

like image 506
Asad Khan Avatar asked Oct 31 '09 10:10

Asad Khan


1 Answers

Those are called #include guards.

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.

like image 179
LiraNuna Avatar answered Sep 29 '22 06:09

LiraNuna