Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

including header files from different directories?

Tags:

c++

include

I am working on a project and I keep getting stumped on how I am supposed to import files from a different directory. Here is how some of my files are organized:

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

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

like image 789
Stas Jaro Avatar asked Dec 23 '11 23:12

Stas Jaro


3 Answers

There are many ways. You can #include "../stdafx.h", for instance. More common is to add the root of your project to the include path and use #include "shapes/sphere.h". Or have a separate directory with headers in include path.

like image 171
Michael Krelin - hacker Avatar answered Oct 09 '22 07:10

Michael Krelin - hacker


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

#include "headers/myHeader.h"
#include "../moreHeaders/myOtherHeader.h"

The downside of this approach is that it requires you to reflect your directory structure in your code. If you ever update your directory structure, your code won’t work any more.

A better method is to tell your compiler or IDE that you have a bunch of header files in some other location, so that it will look there when it can’t find them in the current directory. This can generally be done by setting an “include path” or “search directory” in your IDE project settings.

For Visual Studio, you can right click on your project in the Solution Explorer, and choose “Properties”, then the “VC++ Directories” tab. From here, you will see a line called “Include Directories”. Add your include directories there.

For Code::Blocks, go to the Project menu and select “Build Options”, then the “Search directories” tab. Add your include directories there.

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

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

The nice thing about this approach is that if you ever change your directory structure, you only have to change a single compiler or IDE setting instead of every code file.

like image 37
Pushpak Sharma Avatar answered Oct 09 '22 09:10

Pushpak Sharma


You can either use relative paths:

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

or add your project directory to your compiler include path and reference them like normal:

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

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

like image 41
Dave Rager Avatar answered Oct 09 '22 09:10

Dave Rager