我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上?

2022-01-25 00:00:00 relative-path include convention c++

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?

解决方案

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:

namespace foo { namespace bar { struct Baz; } }

It is convenient and intuitive to include it like:

#include "foo/bar/Baz.h"

相关文章