Matthew D. Scholefield
Matthew D. Scholefield

Reputation: 3336

C++ need to include headers many directories up

I have the following folder structure in a 2D terraria/Minecraft style game:

src/
- Backend/
- - Vector.hpp
- World/
- - Elements/
- - - Mobs/
- - - - BaseMob.cpp

As you would guess, there are plenty more source files within each directory. Inside BaseMob.cpp I need to access src/Backend/Vector.hpp. Is there either a cleaner way to write #include "../../../Backend/Vector.hpp" (ie. #include "/Backend/Vector.hpp") or a better way to organize the files in my source folder?

Here's some more info on the actual content in the source folders (most .cpp files are excluded):

Backend/ # Anything specific to a particular platform
- Vector.hpp
- Graphics.hpp
World/ # Anything about the whole game's world
- Elements/
- - Mobs/
- - - BaseMob.hpp # Polymorphic base class
- - - MobHandler.hpp # Manages all mobs in world
- - - PlayerMob.hpp
- - - WaterMob.hpp
- - Block.hpp # Defines all possible blocks
- - Inventory.hpp
- - Furnace.hpp
- World.hpp
- WorldRenderer.hpp # Makes calls to Backend/graphics.hpp
main.cpp

Upvotes: 0

Views: 965

Answers (2)

jpo38
jpo38

Reputation: 21514

You could consider reorganizing your include folders. This is a possible solution but may not be enough: You won't be able to do that when you'll start using 3rd party libraries...so you need a better way to fix that.

Clean way is to add needed folders (the one where the header files you need are stored) to your "includes path" used by the compiler, so that it can find them.

Then, instead of #include "World/Elements/Mobs/BaseMob.hpp", you add World/Elements/Mobs to the include paths and then simply do #include "BaseMob.hpp"

If you use a different compiler/IDE, it must provide an option to do that.

Upvotes: 4

Thomas Matthews
Thomas Matthews

Reputation: 57678

I recommend refraining from placing paths in #include statements. If the file moves, you'll have to change all the sources.

IMO, a better method is to tell the compiler where to look for the include files. A common command line compiler option is "-I" (capital letter i). In IDEs there may be a setting where you can list all the paths to search.

By telling the compiler where to search, you include files can be anywhere and can move and you don't have to change the source code.

Upvotes: 0

Related Questions