Understanding #pragma once

Why do we need #pragma once? What does it do exactly?

#pragma once prevents a header file from being included multiple times in the same translation unit. This is important because multiple inclusions can cause compilation errors and slow down compilation.

The Problem

Without #pragma once, this situation can happen:

// Weapon.h
class Weapon {
  int Damage{10};
};
// Character.h
#include "Weapon.h"

class Character {
  Weapon* MainWeapon;
};
// Game.cpp
#include "Weapon.h"
#include "Character.h"

int main() {
  Weapon Sword;
}

The Game.cpp file ends up with two copies of the Weapon class definition:

  1. Directly from #include "Weapon.h"
  2. Indirectly when Character.h includes Weapon.h

This creates a compiler error:

error: redefinition of 'class Weapon'

The Solution

Adding #pragma once fixes this:

// Weapon.h
#pragma once

class Weapon {
  int Damage{10};
};

Now the compiler only includes the file once, no matter how many times it appears in include statements.

The Alternative

Before #pragma once, we used include guards:

// Weapon.h
#ifndef WEAPON_H
#define WEAPON_H

class Weapon {
  int Damage{10};
};

#endif

Both approaches work, but #pragma once is:

  • Shorter and cleaner
  • Less prone to naming conflicts
  • Often faster for the compiler

That's why #pragma once is now the preferred choice in modern C++, even though include guards are still common in older code and some cross-platform projects.

Header Files

Explore how header files and linkers streamline C++ programming, learning to organize and link our code effectively

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Header File Syntax: <> vs ""
Why do some header files use angle brackets (<>) while others use quotes ("")?
Including Headers in CPP Files
Why do we need to include the header file in its own cpp file? The cpp file already has all the class code!
Circular Dependencies
Can I have circular dependencies if I use pointers? I noticed the lesson showed a Character with a Sword pointer, and a Sword with a Character pointer. How does that work?
Header File Locations
How does the compiler know where to find my header files? What if they are in different folders?
Multiple Classes Per Header
Can I declare multiple classes in one header file? When should I do this?
Separating Declarations
Should I always move function definitions to cpp files? The lesson mentioned small functions can stay in the header - how do I decide?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant