matrixit matrixit - 8 days ago 6
C++ Question

How to include C++ header file which is not in the same directory as the current source file without using '..'?

For example:


project/utility/a.cpp


and


project/utility/a.h


are implementation file and header file for a batch of functions that are used everywhere in this project.

Now, imagine


project/component/b.h


would like to include
a.h
. A common solution is to use:

#include "../utility/a.h"


in
b.h
.

But this is not allowed in Google C++ style:


All of a project's header files should be listed as descendants of the project's source directory without use of UNIX directory shortcuts
.
(the current directory) or
..
(the parent directory).


I tried to include it as showed in the document above, but it does not work.


So what should I do to include it without using '.' or '..' ?

Answer

See also What are the benefits of a relative path such as "../include/header.h" for a header? and Should I use #include in headers?

You need to decide on whether to use just the base name of the header file (a.h in your question's abbreviated example), or whether to use a subdirectory plus header name project/a.h). Either is workable as long as the header names are unique; the subdirectory version is often better and requires fewer command line options, in general.

You can write:

#ifndef B_H_INCLUDED
#define B_H_INCLUDED

#include "utility/a.h"

…other material required…

#endif /* B_H_INCLUDED */

and then, on the compiler command line, include an option:

-I ..

This ensures that the compiler will find utility/a.h as ../utility/a.h (unless there's a name conflict somewhere). Or you can specify the absolute path to your project:

-I /path/to/project

which will read /path/to/project/utility/a.h.

Comments