Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ include with full path

I find #include "../app/thing.h" very ugly and I would like to be able to import from the main root of my project, like this:

#include <project/app/submodule/thing.h>

(I know <> is generally used for external but I find it very cleaner)

How can I do that, from anywhere in my project?

like image 837
valentin Avatar asked Mar 30 '14 00:03

valentin


3 Answers

You simply need to ensure that your build process sets an option to specify the starting point of the search.

For example, if your header is in:

/work/username/src/project/app/submodule/thing.h

then you need to include (assuming a POSIX-compliant compiler; AFAICR, even MSVC uses /I as the analogue of -I):

-I/work/username/src

as one of the compiler options. You can use that path from anywhere in your project since it is absolute. You just need a defined way for your build system to know what the setting should be, so that when it is moved to /home/someone/src/, you have only one setting to change.

like image 85
Jonathan Leffler Avatar answered Nov 15 '22 02:11

Jonathan Leffler


See this answer for a more complete explanation about how the differences between the two formats work. Honestly, though, I think you might want to consider restructuring your folder hierarchy if you need to jump up a folder then jump into another folder to get something. Generally speaking, it's pretty common practice to keep all files local to your program local to each other in the folder structure (i.e. in the same folder), and all files that aren't local, but may be needed (such as header files for libraries used) in a sub-folder within the main program folder, or to include them at compile time.

It is important to note that in the answer I linked above, it explains that "<>" includes are IMPLEMENTATION DEPENDENT, so we'd really need to know what compiler you're using to tell you if you could or couldn't do that.

like image 26
Gurgadurgen Avatar answered Nov 15 '22 02:11

Gurgadurgen


You can simply use the include directories option of your current compiler (-I usually) to achieve this.

Also note using the "" double quotes will just add to fallback for the compiler standard headers. Files included using the <>, are only guaranteed to search files from the compiler standard headers.

like image 28
πάντα ῥεῖ Avatar answered Nov 15 '22 02:11

πάντα ῥεῖ