Header Files

Understanding #pragma once

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

3D art showing a character in a bar

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

Answers to questions are automatically generated and may not have been reviewed.

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved