Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inclusion of header files -- relative to current directory or to include directories?

I have the following direcory stucture:

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

Both lib1 and lib2 are gonna be distributed (installed). lib2 makes use of lib1, so it needs some includes:

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

(1) is the straight forward way, but is very unflexible. (2) is the way I use at the moment, but the build system needs to know that src needs to be added to the include path. (3) seems the best for me under the distribution aspect because then it can be assumed that the headers reside in a standard location, but it's not too obvious for me how a build system handles that (in this case, lib1 needs to be installed before lib2 can be compiled).

What's the recommended way?

like image 611
wal-o-mat Avatar asked Jan 08 '12 19:01

wal-o-mat


People also ask

What should header files include?

Header files ( . h ) are designed to provide the information that will be needed in multiple files. Things like class declarations, function prototypes, and enumerations typically go in header files. In a word, "definitions".

Should you include header files in header files?

A TL;DR definition: A header file must include the header files that directly define each of the types directly used in or that directly declare each of the functions used in the header file in question, but must not include anything else.

How do you include a header file which is placed in different folders?

You can find this option under Project Properties->Configuration Properties->C/C++->General->Additional Include Directories. and having it find it even in lib\headers. You can give the absolute or relative path to the header file in the #include statement.

Why header files inclusion is must?

Including Multiple Header Files: You can use various header files in a program. When a header file is included twice within a program, the compiler processes the contents of that header file twice. This leads to an error in the program. To eliminate this error, conditional preprocessor directives are used.


1 Answers

The only difference between "" and <> forms of include is that the "" forms first search in some places and then fallback to the same places as <>. The set of additional places is implementation dependent and the only common one is the directory of the file containing the include directive. The compiler options which add to the include path usually add for the <> form and so those directories get searched for both form.

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

like image 160
AProgrammer Avatar answered Sep 21 '22 14:09

AProgrammer