且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何让 g++ 搜索特定目录中的头文件?

更新时间:2022-12-23 07:47:47

A/code.cpp

#include <B/file.hpp>

A/a/code2.cpp

A/a/code2.cpp

#include <B/file.hpp>

编译使用:

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

您可以使用环境变量来更改 g++ 查找头文件的路径.来自手册页:

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

每个变量的值是一个由特殊字符分隔的目录列表,很像PATH,在其中查找标题文件.特殊字符PATH_SEPARATOR"取决于目标,并在 GCC 构建时确定.对于基于 Microsoft Windows 的目标,它是一个分号,对于几乎所有其他目标,它是一个冒号.

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 指定要搜索的目录列表,就像使用 -I 指定一样,但在使用 -I 选项指定的任何路径之后命令行.这无论预处理哪种语言,都会使用环境变量.

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.

其余的环境变量仅在预处理指定的特定语言时适用.每个指定一个目录列表如同使用 -isystem 指定一样进行搜索,但在命令行上使用 -isystem 选项指定的任何路径之后进行搜索.

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.

在所有这些变量中,一个空元素指示编译器搜索其当前工作目录.空元素可以出现在开头或路径的尽头.例如,如果 CPATH 的值为:/special/include",则与 -I 的效果相同.-我/特殊/包括.

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.

您可以通过多种方式更改环境变量.在 bash 提示符下,您可以执行以下操作:

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

您当然可以将其添加到 Makefile 等中.

You can of course add this in your Makefile etc.