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:
- Directly from
#include "Weapon.h"
- Indirectly when
Character.h
includesWeapon.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