Include header files - relative to current directory or directory inclusion?

I have the following directory structure:

src +-- lib1 +-- lib1.h +-- lib2 +-- lib2.h 

Both lib1 and lib2 will be distributed (installed). lib2 uses lib1 , so it needs some of them:

 #include "../lib1/lib1.h" // 1 #include "lib1/lib1.h" // 2 #include <lib1/lib1.h> // 3 

(1) is a direct way, but very inflexible. (2) is the way I'm currently using, but the build system should know that src needs to be added to the include path. (3) it seems the best to me in terms of distribution, because then it can be assumed that the headers are in a standard location, but it is not too obvious for me how the build system handles this (in this case, lib1 must be installed before lib2 can be compiled )

What is the recommended way?

+7
source share
2 answers

The only difference between the forms include "" and <> is that "" forms the first search in some places, and then returns to the same places as <> . A set of additional places is implementation dependent, and the only common is the directory of the file containing the include directive. Compiler options that add to the include path are usually added to the <> form, and therefore these directories look for both forms.

So the choice between the two forms is basically style. Using the "" form for the current project and <> for system libraries is common. For things in between, make a choice and stick to it in your project.

+10
source

I will vote for version 2.

 #include "../lib1/lib1.h" // 1 

This assumes that the tree will always remain unchanged. Therefore, when you change your structure, you need to change it everywhere.

 #include "lib1/lib1.h" // 2 

I do not see the problem of adding src to the include path. In fact, you donโ€™t even need to add src to the include path, you can directly add src / lib1 and just have #include "lib1.h"

 #include <lib1/lib1.h> // 3 

This include style is used for system headers. You should avoid this, as most programmers are used to view windows.h or string or vector inside <> . You also tell the compiler to first look for those headers in the default directories, and not your own. I would avoid this.

Side note:

You should think of such a structure:

 src +-- lib1 +-- lib1.h +-- lib2 +-- lib2.h include 

where the include directory contains all the public headers. If lib1.h is public, move it there. If not, the structure you are currently using should be fine.

+2
source

All Articles