Including header files from different directories?

I am working on a project and I am constantly worried about how I should import files from another directory. Here's how some of my files are organized:

-stdafx.h -core/ -->renderer.cpp -shapes/ -->sphere.h -->sphere.cpp 

how can i access stdafx.h and shapes/sphere.h from core/renderer.cpp ?

+8
c ++ include
source share
3 answers

There are many ways. For example, you can #include "../stdafx.h" . Most often, add the root of your project to the inclusion path and use #include "shapes/sphere.h" . Or have a separate directory with headers in the include path.

+7
source share

You can use relative paths:

 #include "../stdafx.h" #include "../shapes/sphere.h" 

or add the project directory to your compiler, include the path and refer to them as usual:

 #include "stdafx.h" #include "shapes/sphere.h" 

You can use the /I command line option to add a path or specify a path in your project settings.

+1
source share

One (bad) way to do this is to include the relative path to the header file that you want to include as part of the #include line. For example:

include "headers / myHeader.h"

include "../moreHeaders/myOtherHeader.h"

The disadvantage of this approach is that it requires you to reflect the structure of your directory in your code. If you ever update your directory structure, your code will no longer work.

The best way is to tell your compiler or IDE that you have a bunch of header files elsewhere so that it looks there when it cannot find them in the current directory. This can usually be done by setting "include path" or "search directory" in the IDE project settings.

In Visual Studio, you can right-click on a project in Solution Explorer and select "Properties" and then the "VC ++ Directories" tab. From here you will see a line called "Include Directories". Add inclusion directories there.

In the Code :: Blocks field, go to the "Project" menu and select "Build Options", then the "Directory Search" tab. Add inclusion directories there.

Using g ++, you can use the -I option to specify an alternative include directory.

g ++ -o main -I / source / includes main.cpp

The best part about this approach is that if you ever change the directory structure, you only need to change one compiler or IDE parameter instead of each code file.

0
source share

All Articles