包含标头中的搜索路径因编译器而异
Include search paths from included header varies for different compilers
我有以下文件夹结构:
project
├── header1.h
├── folder
│ └── header2.h
└── main.cpp
以下来源:
//main.cpp
#include "header1.h"
#include "folder/header2.h"
int main() {}
//header1.h
#pragma once
void function1() {}
//folder/header2.h
#pragma once
#include "header1.h"
void function2() {}
所以"header2.h"包括不在同一文件夹中的"header1.h"。
使用cl main.cpp
编译此代码是成功的:
Microsoft (R) C/C++ Optimizing Compiler Version 19.00.24215.1 for x86 Copyright (C) Microsoft Corporation. All rights reserved. main.cpp Microsoft (R) Incremental Linker Version 14.00.24215.1 Copyright (C) Microsoft Corporation. All rights reserved. /out:main.exe main.obj
但是对于gcc main.cpp
我得到错误:
In file included from main.cpp:2:0: folder/header2.h:2:21: fatal error: header1.h: No such file or directory #include "header1.h" ^ compilation terminated.
这完全有道理。似乎Microsoft正在使用自己的规则来解决包含问题。 有没有办法为cl
(和Visual Studio)禁用此行为? 有没有办法为gcc
启用类似 cl 的行为?
上。
我已经在Windows上使用Clang 4.0.0clang++ main.cpp
进行了检查:
In file included from main.cpp:2: ./folder/header2.h:2:10: warning: #include resolved using non-portable Microsoft search rules as: ./header1.h
[-微软-包括] #include "标题1.h" ^ 生成 1 条警告。
它甚至为此-Wmicrosoft-include
了特定的规则。
本文解释了VC++如何处理include
指令的两种形式(""
和<>
)。
我想""
表单的第(3)点会导致对项目中可能的包含目录进行非常广泛的搜索:
报价表格
(3)在当前打开的包含文件的目录中,在 它们的打开顺序相反。搜索从 父包含文件的目录,并继续向上通过 任何祖父项的目录都包含文件。
这就是为什么当header2.h
从内部处理时main.cpp
,其中还包括header1.h
,它不会给您任何错误。
GCC 搜索规则完全不同:
- 对于 include 指令的引用形式,首先搜索当前文件的目录。
- 对于 include 指令的引用形式,由 -iquote 选项指定的目录按从左到右的顺序搜索,如 它们显示在命令行上。
- 使用 -I 选项指定的目录按从左到右的顺序进行扫描。
- 使用 -isystem 选项指定的目录按从左到右的顺序进行扫描。
- 扫描标准系统目录。
- 使用 -idirafter 选项指定的目录按从左到右的顺序进行扫描。
它不会自动搜索到目前为止打开的包含文件的目录(之前包括),这是导致错误的原因。我认为没有办法绕过这个限制并强制任何一个编译器使用另一个编译器使用的搜索逻辑。
相关文章:
- 基于编译器选项的编译二进制路径
- 如何永久地向 g++ 编译器添加路径?
- 我最近更改了编译器路径以运行 c++ 代码,但现在我无法运行任何 python 代码。我该如何解决这个问题?
- 有没有办法告诉 g++ 编译器,而不是在某个 -I 路径中查找包含标头
- 在Windows上设置编译器路径
- 包含标头中的搜索路径因编译器而异
- GCC makefile 编译和语法。如何调用 c 编译器以及包含多个路径
- 在英特尔C++编译器 (Linux) 的配置搜索路径中找不到文件可执行文件
- 如何使 C/C++ 编译器在用户指定的路径中查找标头
- VS2012:“找不到资源编译器DLL.请确保路径正确.”
- 编译器无法找到给定的路径
- Eclipse 编译器包含路径子目录
- libclang:添加编译器系统包含路径(Windows中的Python)
- 如何在编译器"edg"中使用相对路径?
- 通过编译器环境变量或 C 和 C++ 中的命令行标志指定库路径
- gcc编译器错误消息路径取消父级
- 编译器警告输出反斜杠和路径中的斜杠(" /")
- eclipse中的交叉编译器前缀和路径
- 修改用于构建boost的默认编译器路径
- 我无法设置opencv库的编译器路径