Runfeng Jin
Runfeng Jin

Reputation: 3

use "-I" to define g++ include path:why it only works when I set ".../include" instead of ".../include/boost"?

My application need boost lib. There is a boost lib in /usr/lib and boost include in /usr/include/boost, but they aren's what I need. So I compile new boost lib in my home , /home/js/anaconda/.../include/boost and /home/js/anaconda/.../lib.

To use boost in home, I use "-I/home/js/anaconda/.../include/boost" to define the include path, however, It complain error because it find boost in the "/usr/..." path. Then I try use "-I/home/js/anaconda/.../include" (the parent directory) and it works fine!

My question is 1)why it works when I specify the parent directory "/home/.../include" instead of "/home/.../include/boost"? what is the right directory I should specify when I use "-I"?

2)when I use "-I" to specify some directory, will these directory always be the one prior to the /usr directory?

Upvotes: 0

Views: 193

Answers (1)

Jorge Bellon
Jorge Bellon

Reputation: 3116

It's a common practice (but not mandatory) to include all the header files of a library into its own directory. This has a few advantages:

  • When you look for a header file, you don't need to look through the header files of other libraries.
  • When you read a file with include directives, you can see all the headers that belong to the same library because they start in the same base directory.

When you use -I preprocessor flag to add a directory to the include search path, that directory can either:

  • Belong to your current project: in the case you have your files organised in directories it may become handy.
  • Be a part of an external dependency: be it a system library or a dependency installed in a directory of your own. These directories' path end in include following the filesystem hierarchy standard.

In the particular case of boost, the intended use is to -I/path-to-boost-install/include flag and then use an include directive such as #include <boost/optional/optional.hpp> to use one of the libraries in that installation.

The best advice is to read the documentation and look for examples before you start using a library. In the case of boost, you can read the getting started on Unix or getting started on Windows pages:

It's important to note the following:

  • The path to the boost root directory (often /usr/local/boost_1_75_0) is sometimes referred to as $BOOST_ROOT in documentation and mailing lists .

  • To compile anything in Boost, you need a directory containing the boost/ subdirectory in your #include path.

  • Since all of Boost's header files have the .hpp extension, and live in the boost/ subdirectory of the boost root, your Boost #include directives will look like:

    #include <boost/whatever.hpp>

or

    #include "boost/whatever.hpp"

depending on your preference regarding the use of angle bracket includes.

Upvotes: 1

Related Questions