我在项目的App
文件夹中。我运行以下命令来编译character.cpp
g++ -Wall -std=c++11 -I../App -c Character/character.cpp -o Obj/character.o
位于App/Character
目录中。 character.cpp
包含以下内容
#include "Inventory/inventory.hpp"
inventory.cpp
的文件夹为App/Inventory
。
我想因为我正在运行来自g++
的{{1}}命令,默认的包含路径将从App
开始,因此我不需要App
命令的一部分。对我来说,这似乎是说“移动一个级别高于应用程序然后进入应用程序并从那里包括”这似乎是多余的,但没有那条线它不起作用。
任何人都可以解释原因吗?
修改
再看一遍和更多文档,我相信如果没有指定-I路径,g ++将查看其默认目录,然后所有其他包含(就像我引起问题的那个)相对于该文件而言包括他们。所以我必须添加-I../App
部分来说“查看App目录”,因为它不喜欢-I
,我必须使用../App,因为这相当于不一动不动。任何人都可以确认这一点是否准确无误?
答案 0 :(得分:1)
您可以使用-I.
来搜索当前目录中的标题,而不是-I../App
。
这包括预处理器指令
#include "Inventory/inventory.hpp"
强制gcc(g ++或cpp)不是从当前路径(App/
)搜索标题,而是从源文件的目录(App/Character
)搜索:
/root/App# strace -f g++ -c -H ./Character/character.cpp 2>&1 |grep Inven
[pid 31316] read(3, "#include \"Inventory/inventory.hp"..., 35) = 35
[pid 31316] stat64("./Character/Inventory/inventory.hpp.gch", 0xbfffe6a4) = -1 ENOENT (No such file or directory)
[pid 31316] open("./Character/Inventory/inventory.hpp", O_RDONLY|O_NOCTTY) = -1 ENOENT (No such file or directory)
..then try system directories
此处记录了这些内容:https://gcc.gnu.org/onlinedocs/cpp/Search-Path.html
GCC在包含当前文件的目录中查找#include“file”首先请求的标头
此行为无法在语言标准(ISO C)中修复,并且是实现定义的(由Richard Corden评论并由piCookie在What is the difference between #include <filename> and #include "filename"?中回答):
“分隔符”之间的指定序列。以实现定义的方式搜索指定的源文件。
但根据Posix, aka The Open Group Base Specifications Issue 7:
,这就是C编译器在Unix下的工作方式因此,名称以双引号(“”)括起来的标题应首先在#include行的文件目录中搜索,然后在-I选项中命名的目录中搜索,最后在通常的位置搜索。对于名称用尖括号(“&lt;&gt;”)括起来的标题,只能在-I选项中指定的目录中搜索标题,然后在通常的位置搜索标题。在-I选项中命名的目录应按指定的顺序进行搜索。
当你的当前目录远离源目录时这很有用(这是autotools / autoconf中的推荐方法:do mkdir build_dir5;cd build_dir5; /path/to/original/source_dir/configure --options; then make
- 这不会改变源目录,也不会在其中生成大量文件;你可以使用单一副本的源代码进行多次构建。)
当您使用-I.
(或使用-I../App
或-I/full_path/to/App
)从App目录启动g ++时,gcc(g ++)会找到Inventory
。我在标题中添加了警告以查看它何时被包含在内;和gcc / g ++的-H
选项打印包含pathes的所有包含的标题:
/root/App# cat Inventory/inventory.hpp
#warning "Inventory/inventory.h included"
/root/App# cat Character/character.cpp
#include "Inventory/inventory.hpp"
/root/App# g++ -I. ./Character/character.cpp -H -c
. ./Inventory/inventory.hpp
In file included from ./Character/character.cpp:1:
./Inventory/inventory.hpp:1:2: warning: #warning "Inventory/inventory.h included"