为什么 VS C++ 中的路径包含正斜杠而不是反斜杠?

Why Path in VS C++ contains forward slash not backslash?

我得到了数千个包含带正斜杠的文件的文件

#include <this/thread.hpp>

为什么?原程序是用VS 2008写的。

这会导致致命错误 C1083

如果我将路径更改为 #include "..\this\thread.hpp",它会找到文件

Windows 接受正斜杠和反斜杠作为路径分隔符。至少从 Windows XP 开始。

我无法读懂思想,但我猜想正斜杠被用于(潜在的)可移植性 and/or 标准合规性的名称,因为 include 指令中的反斜杠在 c++03 中具有未定义的行为。

c++03 §2.8/2:

If either of the characters ’ or \, or either of the character sequences /* or // appears in a q-char-sequence or a h-char-sequence, or the character " appears in a h-char-sequence, the behavior is undefined.

根据草案,c++11 中的措辞已更改。行为不再是未定义的,但仍然是实现定义的。

c++11 草案 §2.9/2

The appearance of either of the characters ’ or \ or of either of the character sequences /* or // in a q-char-sequence or an h-char-sequence is conditionally supported with implementation-defined semantics, as is the appearance of the character " in an h-char-sequence.

关于您的错误:

If I change the path to #include "..\this\thread.hpp" it finds the file

密切注意您的两个不同的包含指令。有比路径分隔符更多的区别。首先,正斜杠版本不引用父路径 (../),其次,路径包含在 < > 中,这在这种情况下是错误的,因为路径似乎是相对于当前文件。有关详细信息,请参阅 。

错误 C1083 是 "cannot open include file",这通常意味着编译器找不到文件。

#include <this/thread.hpp>

在您的包含目录路径中是否有名为“this”的目录?这比正斜杠更可能是问题所在。

虽然不是 C++ 特定的,但它是使用 \ 转义字符的地方,至少当它在 <...> 标记内时,这样如果你真的想将它指定为路径分隔符,您需要键入 \。为避免每次您只想使用一种类型的反斜杠时都使用双反斜杠,并且由于其作用方式相同,如果您仅使用 /,则可以应用相同的功能来指定文件夹之间的路径分隔。这种简单性减少了不理解转义的人的困惑,这样他们就不会从字面上采用转义路径并将其放入资源管理器地址栏中,并且在没有将他们带到正确的位置时感到困惑。

请注意,如果它需要 <...> 标记,则您指定的是系统文件,而 "..." 语句是包含本地生成的。这些语法在转义要求上有所不同。