gpt4 book ai didi

c++ - 如何告诉 g++ 编译器在哪里搜索包含文件?

转载 作者:太空宇宙 更新时间:2023-11-04 12:17:09 25 4
gpt4 key购买 nike

在“工作目录”中,我有很多 *.cpp 和 *.h 文件,它们#include 彼此以及子目录中的文件。

例如:

#include "first.h"
#include "second.h"
#include "dir1/third.h"
#include "dir2/fourth.h"

在我自己的目录(与“工作”目录不同)中,我想创建一个新的 *.cpp 和 *.h 文件,其中包含来自“工作”目录的文件之一。例如:

#include "/root/workingdirectory/first.h"

但是,它不起作用。因为“first.h”可能包含“second.h”,而“second.h”不在我的目录中。有没有办法告诉编译器它需要搜索不在当前目录中而是在工作目录中的包含文件:/root/workingdirectory/

更复杂的是,dir1dir2 不在我的工作目录中。它们位于 /root/workingdirectory2/。所以,我的第二个问题是,是否可以通过让编译器知道子目录位于其他地方来解决这个问题?

我还需要补充一点,我不使用任何环境进行开发和从命令行编译(使用g++)。

最佳答案

如您所知,它对 read the manual 很有用- 特别是 this chapter - 更具体地说 right here .

具体来说,你想要

g++ -I/root/workingdirectory -I/root/workingdirectory2

另请注意 #include 上的文档指令语法,描述 here作为:

2.1 Include Syntax

Both user and system header files are included using the preprocessing directive #include. It has two variants:

#include <file>

This variant is used for system header files. It searches for a file named file in a standard list of system directories. You can prepend directories to this list with the -I option (see Invocation).

#include "file"

This variant is used for header files of your own program. It searches for a file named file first in the directory containing the current file, then in the quote directories and then the same directories used for <file>. You can prepend directories to the list of quote directories with the -iquote option. The argument of #include, whether delimited with quote marks or angle brackets, behaves like a string constant in that comments are not recognized, and macro names are not expanded. Thus,#include <x/*y> specifies inclusion of a system header file named x/*y.

However, if backslashes occur within file, they are considered ordinary text characters, not escape characters. None of the character escape sequences appropriate to string constants in C are processed. Thus, #include "x\n\\y" specifies a filename containing three backslashes. (Some systems interpret \ as a pathname separator. All of these also interpret / the same way. It is most portable to use only /.)

It is an error if there is anything (other than comments) on the line after the file name.

比如

#include "first.h"

开始在与包含此指令的 .cpp 文件相同的目录中查找(或采用相对于此目录的相对路径)。

如果你想使用包含路径(由 -I 指定)你应该使用

#include <dir1/third.h>

通常的做法是使用 #include "local.h"库/包/模块中 header 的形式(无论您选择如何组织),以及 #include <external.h>来自外部/第 3 方或系统库的标题的表单。

关于c++ - 如何告诉 g++ 编译器在哪里搜索包含文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47126860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com