Header Files

Header File Locations

How does the compiler know where to find my header files? What if they are in different folders?

3D art showing a character in a bar

The compiler follows specific rules to find header files, and we can configure additional search paths. Let's break this down:

Default Search Locations

When looking for headers, the compiler checks several places in this order:

For quoted includes (#include "file.h"):

  • The same directory as the source file
  • The project's include directories
  • The system include directories

For angle bracket includes (#include <file.h>):

  • The system include directories only

Adding Include Directories

Most IDEs let you specify additional include directories. In Visual Studio:

// Project structure:
MyGame/
  Source/
    Player/
      Player.cpp
    Weapons/
      Sword.h

If Player.cpp needs to include Sword.h, we have options:

// Option 1: Relative path (fragile)
#include "../Weapons/Sword.h"

// Option 2: Add include directory
#include "Sword.h" // Better!

Setting Up Include Directories

In Visual Studio:

  1. Right-click your project
  2. Select Properties
  3. Navigate to C/C++ → General
  4. Add your paths to Additional Include Directories

For example, adding $(ProjectDir)Source lets you include files from anywhere in the Source directory.

Example Project Structure

Here's a common way to organize files:

MyGame/
  Include/
    Character.h
    Weapon.h
    Items/
      Potion.h
  Source/
    Character.cpp
    Weapon.cpp
    Items/
      Potion.cpp

With Include added to our include directories, we can write:

// From Include/
#include "Character.h"

// From Include/Items/
#include "Items/Potion.h"

This makes our includes cleaner and more maintainable, and lets us move files around without breaking includes.

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