#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.
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:
#include "Weapon.h"
Character.h
includes Weapon.h
This creates a compiler error:
error: redefinition of 'class Weapon'
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.
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:
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.
Answers to questions are automatically generated and may not have been reviewed.
Explore how header files and linkers streamline C++ programming, learning to organize and link our code effectively