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

C++CC Preprocessor

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

#ifndef <token>
/* code */
#else
/* code to include if the token is defined */
#endif

#ifndef checks whether the given token has been #defined earlier in the file or in an included file; if not, it includes the code between it and the closing #else or, if no #else is present, #endif statement. #ifndef is often used to make header files idempotent by defining a token once the file has been included and checking that the token was not set at the top of that file.

#ifndef _INCL_GUARD
#define _INCL_GUARD
#endif

Solution 3 - C++

This prevent from the multiple inclusion of same header file multiple time.

#ifndef __COMMON_H__
#define __COMMON_H__
//header file content
#endif

Suppose you have included this header file in multiple files. So first time _COMMON_H_ is not defined, it will get defined and header file included.

Next time _COMMON_H_ is defined, so it will not include again.

Solution 4 - C++

They are called ifdef or include guards.

If writing a small program it might seems that it is not needed, but as the project grows you could intentionally or unintentionally include one file many times, which can result in compilation warning like variable already declared.

#ifndef checks whether HEADERFILE_H is not declared.
#define will declare HEADERFILE_H once #ifndef generates true.
#endif is to know the scope of #ifndef i.e end of #ifndef

If it is not declared which means #ifndef generates true then only the part between #ifndef and #endif executed otherwise not. This will prevent from again declaring the identifiers, enums, structure, etc...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAsad KhanView Question on Stackoverflow
Solution 1 - C++LiraNunaView Answer on Stackoverflow
Solution 2 - C++iampranabroyView Answer on Stackoverflow
Solution 3 - C++Sandeep_blackView Answer on Stackoverflow
Solution 4 - C++Mohit JainView Answer on Stackoverflow