In my project, I currently use relative paths to include my files, which admittedly doesn't change often. However, it yields pretty weird include patterns, because I usually nest my files in alot of folders.
For example, in my current project I have network/server/myfile.hpp
. It needs to include common/log.hpp
. Current I use #include "../../common/log.hpp"
which is pretty verbose, but works.
If i instead add my main include directory on the path, I could simply include "common/log.hpp"
.
I know this question might be more about preference than anything else, but is there any objective pros and cons concerning cross platform applications and what about C++ conventions?
I always strive to make my projects independent of location. If I work on a new computer/platform, I want to be able to compile and keep working with a minimum of required setup. As you're asking a subjective question, my subjective answer would be that I definitely prefer using relative paths.
By having
#include <common/log.hpp>
in your source file and having path tocommon/log.hpp
in your project settings (compiler options) you are protecting your source code from changes in casecommon/log.hpp
moves to some other place so I would recommend this approach. Note using angle brackets in this case - compiler should search for the header in directories which paths are specified by the/I
compiler option.No CONVENTIONS as such, you may do it either way, the way you prefer.
And moreover relative paths provide you freedom to port you application, So just do it :)
Relative includes paths with
..
in it look a bit ugly and expect a certain filesystem structure, that is,"../../common/log.hpp"
is two folders up. It makes sense to avoid unnecessary dependencies in general and on filesystem structure in particular, so that moving a header file from one directory to another does not force you to update all source files that include that header.It is also elegant to have your includes correspond to namespaces and classes. If, for example, you have:
It is convenient and intuitive to include it like:
I have a rule that each individual component may not use more than one directory, and that component have dependent components' directories in the include path.
Thus, each component uses its own include files with the
""
syntax, and other components' includes using<>
, which nicely avoids unpleasant surprises with one component using the header that the last deployed version installed into the system include directory rather than the one from the source tree; it also has the nice effect of forcing me to componentize my projects early on.