702

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?

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
Asad Khan
  • 11,469
  • 13
  • 44
  • 59
  • 52
    +1 - I too had same doubt, and got much more good answer here, may be useful for future visitors : http://stackoverflow.com/q/3246803/1134940 – Abid Rahman K Dec 11 '12 at 05:27
  • 7
    I want to add to this that you can also use **#pragma once**, that's all you have to do and it serves the same purpose as ifndef. For comparison of the two, see: http://stackoverflow.com/questions/1143936/pragma-once-vs-include-guards – Dimension Jun 01 '13 at 16:12
  • 4
    Best to mention what a `#pragma` is: it activates a compiler-specific feature. Although `#pragma once` is *very* widely supported, it's nonstandard. – Potatoswatter Jun 01 '13 at 16:41
  • 3
    @Dimension: GNU's own documentation (`info cpp` or [look here](http://gcc.gnu.org/onlinedocs/gcc-4.8.1/cpp/)) says "it is not recognized by all preprocessors, so you cannot rely on it in a portable program.". And GNU cpp optimizes the common and portable `#ifndef` idiom so it's as efficient as `#pragma once`. – Keith Thompson Aug 24 '13 at 19:44
  • 4
    Some things to consider: Don't use a macro name starting with an underscore; such identifiers are reserved to the implementation. More subtly, `#ifndef HEADERFILE_H` can violate the implementation's namespace of the header name happens to start with `E`; identifiers starting with `E` and a digit or uppercase letter are reserved to ``. I suggest `#ifndef H_HEADERFILE`. – Keith Thompson Aug 24 '13 at 20:26
  • Here is the simplest description of these pre-definitions. [check it](http://www.fredosaurus.com/notes-cpp/preprocessor/ifdef.html) – Iqra. Jul 11 '17 at 04:04
  • 1
    Does this answer your question? [Why use #ifndef CLASS\_H and #define CLASS\_H in .h file but not in .cpp?](https://stackoverflow.com/questions/3246803/why-use-ifndef-class-h-and-define-class-h-in-h-file-but-not-in-cpp) –  Mar 17 '21 at 14:05

5 Answers5

711

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
LiraNuna
  • 64,916
  • 15
  • 117
  • 140
  • 4
    Koning Baard XIV: VC even has a `#pragma once` which does the same :-) – Joey Oct 31 '09 at 10:23
  • 157
    Also it prevents recursive inclusions... Imagine "alice.h" includes "bob.h" and "bob.h" includes "alice.h" and they don't have include guards... – Kevin Dungs Oct 31 '09 at 10:39
  • @Kevin: that is what I mean. I wanted to manipulate a form which was opened by the form to manipulate. It gaveme lots of errors and I didn't know what to do. I gave up =) –  Oct 31 '09 at 10:58
  • 12
    @Јοеу: `#pragma once` is not portable; the common `#ifndef` idiom is recommended. – Keith Thompson Aug 24 '13 at 19:45
  • What is the problem of including headers multiple times? assuming no recursive inclusion... Is it a problem of same name variables, or maybe just a problem of a larger exe file? – CIsForCookies Jan 03 '16 at 12:34
  • 2
    @CIsForCookies Punch "one definition rule" into your favorite search engine. – David Schwartz Jul 25 '19 at 01:57
  • Does this mean that having both `#pragma once` and `#define HEADERFILE_H` at the top of the file is redundant? – JasonArg123 Jun 10 '20 at 16:30
  • 1
    @JasonArg123: Yes, but that's not always a bad thing. `#pragma once` is explicit; it says "once I've been `#include`d in a given translation unit, don't open this file again". Include guards say "If I'm included again, skip my contents" (but the file is still logically opened, read from end to end, and the guard drops the contents). I haven't checked on recent compilers, but for a while, GCC recognized the include guard idiom and implicitly did what `#pragma once` does, while MSVC didn't, so if you didn't `#pragma once` too, you'd open and process the file repeatedly, adding syscall overhead. – ShadowRanger Apr 20 '22 at 14:59
  • 2
    The cost of opening a file, discarding all its contents, and closing it over and over might not sound like much, but for a large header included transitively by hundreds of other headers (e.g. `windows.h`, the low-level stuff providing simple type definitions like `stdint.h`, `types.h`, etc.), the difference between opening it exactly once per source file and opening it a hundred times (where only the first time does anything productive), especially in a parallel build (where even the tiny amount of contention added can hurt a lot on spinning disk storage), adds up in large builds. – ShadowRanger Apr 20 '22 at 15:03
  • 1
    I believe that MSVC's lack of support for recognizing include guards specially is part of why they were quicker (the first?) to use precompiled headers (avoiding the problem by reducing all those common headers with transitive includes that end up getting included many times down to a single precompiled header); MSVC added PCH around '98. By contrast, [GCC already supported once-only includes](https://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC8) at that point, and didn't add PCH support until '04 (PCH has benefits, they're just less critical with good include guard support). – ShadowRanger Apr 20 '22 at 15:14
59
#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
QuantumFool
  • 609
  • 3
  • 10
  • 29
iampranabroy
  • 1,716
  • 1
  • 15
  • 11
  • 8
    Identifiers starting with an underscore are reserved; you shouldn't define them yourself. Use something like `#ifndef H_HEADER_NAME`. – Keith Thompson Aug 24 '13 at 19:46
  • 5
    I know this is an old comment, but actually the underscore restriction only applies to "external identifiers" - identifiers that could end up in the compiled object's symbol table, i.e. global variables and function names. It does not apply to macro names. – Stu May 15 '14 at 13:05
  • 1
    Is Stu's comment true? I just read https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier and now I am not so sure. – Will Jun 28 '17 at 08:23
  • 1
    No, despite the fact that it is common practice, it is undefined behavior for a user to define any symbol starting with underscore FOLLOWED by an uppercase letter in any scope in C++. In practice such symbols may be used to define macros in the standard libraries, which could collide with user-defined symbols of the same form (I look forward to a response in 2023; greetings, from the age of the rat plague!) Exception: user-defined literals. – David Zhao Akeley Dec 11 '20 at 08:18
  • 1
    @DavidZhaoAkeley No rat plague here. Underscores followed by uppercase letters are still off-limits, and COVID has dramatically improved around the world :P – NoseKnowsAll Mar 28 '23 at 21:53
20

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.

Sandeep_black
  • 1,352
  • 17
  • 18
7

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...

Mohit Jain
  • 270
  • 2
  • 6
2

#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 ABOUTSCREEN_H
#define ABOUTSCREEN_H

#include <fcntl.h>
#include <unistd.h>

#define CHARGING_STATUS_FILE "/cable.2/state"

#define LED_ON "255"
#define LED_OFF "0"

namespace Ui
{
    class aboutScreen;
}

class aboutScreen : public QWidget
{
    Q_OBJECT

public:
    enum LedColors
    {
        OFF,
        RED,
        BLUE,
        GREEN,
        WHITE
    };

    explicit aboutScreen(QWidget *parent = 0, Ui::mainStackWidget *uiMainStackWidget = 0);
    ~aboutScreen();
    void init(void);
    void writeLedStatus(QString, QString);

public slots:
    void updateBatteryAndStorageStatus(void);

private slots:
    void on_backButton_pressed();
    void on_backButton_released();

private:
    Ui::mainStackWidget *uiMainStackWidget;
};

#endif // ABOUTSCREEN_H
nadimnadaf
  • 31
  • 6