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:
- Right-click your project
- Select Properties
- Navigate to C/C++ General
- 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