使用“-I”来定义 g++ include path:why 它仅在我设置“.../include”而不是“.../include/boost”时有效?

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

我的应用程序需要 boost 库。 /usr/lib 中有一个 boost 库,/usr/include/boost 中有一个 boost include,但它们不是我所需要的。所以我在家里编译了新的 boost lib,/home/js/anaconda/.../include/boost 和 /home/js/anaconda/.../lib.

为了在家里使用boost,我使用“-I/home/js/anaconda/.../include/boost”来定义包含路径,但是,它报错,因为它在“/ usr/...”路径。然后我尝试使用“-I/home/js/anaconda/.../include”(父目录),它工作正常!

我的问题是 1) 为什么当我指定父目录“/home/.../include”而不是“/home/.../include/boost”时它有效?使用“-I”时我应该指定的正确目录是什么?

2)当我使用“-I”指定某个目录时,这些目录是否总是在/usr 目录之前的目录?

将一个库的所有 header 文件包含到它自己的目录中是一种常见的做法(但不是强制性的)。这有几个优点:

  • 当您查找header文件时,不需要翻阅其他库的header文件。
  • 当您使用 include 指令读取文件时,您可以看到属于同一个库的所有 header,因为它们从同一个基目录开始。

当您使用 -I 预处理器标志将目录添加到包含搜索路径时,该目录可以:

  • 属于您当前的项目:如果您将文件组织在目录中,它可能会很方便。
  • 成为外部依赖项的一部分:无论是系统库还是安装在您自己的目录中的依赖项。这些目录的路径在 filesystem hierarchy standard.
  • 之后以 include 结尾

在 boost 的特定情况下,预期用途是 -I/path-to-boost-install/include 标记,然后使用包含指令(例如 #include <boost/optional/optional.hpp> 以使用该安装中的库之一。

最好的建议是在开始使用库之前阅读文档并查找示例。在boost的情况下,你可以阅读getting started on Unix or getting started on Windows页:

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.