Header File Locations

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

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.

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?
Understanding #pragma once
Why do we need #pragma once? What does it do exactly?
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