How to make g++ search for header files in a specific directory?

A/code.cpp

#include <B/file.hpp>

A/a/code2.cpp

#include <B/file.hpp>

Compile using:

g++ -I /your/source/root /your/source/root/A/code.cpp
g++ -I /your/source/root /your/source/root/A/a/code2.cpp

Edit:

You can use environment variables to change the path g++ looks for header files. From man page:

Some additional environments variables affect the behavior of the
preprocessor.

   CPATH
   C_INCLUDE_PATH
   CPLUS_INCLUDE_PATH
   OBJC_INCLUDE_PATH

Each variable’s value is a list of directories separated by a special character, much like PATH, in which to look for header
files. The special character, “PATH_SEPARATOR”, is target-dependent and determined at GCC build time. For Microsoft Windows-based targets it
is a semicolon, and for almost all other targets it is a colon.

CPATH specifies a list of directories to be searched as if specified with -I, but after any paths given with -I options on the
command line. This
environment variable is used regardless of which language is being preprocessed.

The remaining environment variables apply only when preprocessing the particular language indicated. Each specifies a
list of directories to be
searched as if specified with -isystem, but after any paths given with -isystem options on the command line.

In all these variables, an empty element instructs the compiler to search its current working directory. Empty elements can
appear at the beginning
or end of a path. For instance, if the value of CPATH is “:/special/include”, that has the same effect as -I.
-I/special/include.

There are many ways you can change an environment variable. On bash prompt you can do this:

$ export CPATH=/your/source/root
$ g++ /your/source/root/A/code.cpp
$ g++ /your/source/root/A/a/code2.cpp

You can of course add this in your Makefile etc.

Leave a Comment