including header files from different directories?

我只是一个虾纸丫 提交于 2020-04-29 10:37:30

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/8621507/including-header-files-from-different-directories

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!