包含包含标头的目录时出现编译错误

compilation error when including directory containing headers

本文关键字:编译 错误 包含包      更新时间:2023-10-16

我有一个目录maths它是一个仅由头文件组成的库。我正在尝试通过在主目录中运行以下命令来编译我的程序:

g++ -I ../maths prog1.cpp prog2.cpp test.cpp -o et -lboost_date_time -lgsl -lgslcblas

但是我收到以下编译错误:

prog1.cpp:4:23: fatal error: maths/Dense: No such file or directory
compilation terminated.
prog2.cpp:6:23: fatal error: maths/Dense: No such file or directory
compilation terminated.

maths 与.cpp文件位于同一目录(即我的主目录)中,我也在我家运行编译行。

程序 1.cpp 和程序 2.cpp 具有以下标头 分别在第 4 行和第 6 行#include<maths/Dense>,因此我收到错误。

我该如何解决它。

您可以将

包含路径更改为-I..或将包含更改为#include <Dense>

等等,如果maths与源文件位于同一目录中,并且是当前目录,则可以将包含路径更改为-I.或将包含更改为#include "Dense"

maths 与.cpp文件位于同一目录(即我的主目录)中

您的包含路径为 -I ../maths 。您需要-I ./maths - 或者更简单,-I maths因为maths当前目录的子目录,而不是父目录的子目录。右?

然后在C++文件中,使用 #include <Dense> .如果要使用#include <maths/Dense>则需要调整包含路径。但是,使用-I.可能会导致大量问题1,我强烈建议不要这样做。

相反,通常的做法是包含一个包含include子目录。因此,您的文件夹结构最好如下所示:

./
+ include/
| + maths/
|   + Dense
|
+ your_file.cpp

然后使用 -I include ,并在C++文件中#include <maths/Dense>


1)考虑如果你有一个文件./map.cpp,从中生成一个名为./map的可执行文件会发生什么。一旦您在代码中的任何位置使用 #include <map>,这将尝试包含 ./map 而不是map标准标头。