gpt4 book ai didi

c++ - 包含 header 的搜索路径因编译器而异

转载 作者:行者123 更新时间:2023-11-28 04:49:16 35 4
gpt4 key购买 nike

我有以下文件夹结构:

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.

这完全有道理。似乎微软正在使用他们自己的规则来解析包含。有没有办法为 cl(和 Visual Studio)禁用此行为?有没有办法为 gcc 启用类似 cl 的行为?


更新。

我已经在 Windows 上使用 Clang 4.0.0 clang++ 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

[-Wmicrosoft-include] #include "header1.h" ^ 1 warning generated.

它甚至有一个特定的规则-Wmicrosoft-include

最佳答案

This article解释了 "" 的两种形式( <>include )指令由 VC++ 处理。

我猜想 ""(3) 点表单导致在项目中的可能包含目录中进行非常广泛的搜索:

Quoted form

(3) In the directories of the currently opened include files, in the reverse order in which they were opened. The search begins in the directory of the parent include file and continues upward through the directories of any grandparent include files.

这就是为什么当header2.hmain.cpp 中处理,其中还包括 header1.h , 它不会给你任何错误。

GCC 搜索规则非常不同:

  1. For the quote form of the include directive, the directory of the current file is searched first.
  2. For the quote form of the include directive, the directories specified by -iquote options are searched in left-to-right order, as they appear on the command line.
  3. Directories specified with -I options are scanned in left-to-right order.
  4. Directories specified with -isystem options are scanned in left-to-right order.
  5. Standard system directories are scanned.
  6. Directories specified with -idirafter options are scanned in left-to-right order.

它不会自动搜索到目前为止(包含之前)打开的包含文件的目录,这是您出错的原因。我认为没有办法绕过此限制并强制其中一个编译器使用另一个编译器使用的搜索逻辑。

关于c++ - 包含 header 的搜索路径因编译器而异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48538707/

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