msys2下的gcc和clang无法解析包含绝对路径的包含

时间:2016-08-31 16:38:44

标签: c++ gcc clang mingw msys2

我尝试在mysys2管理的MinGW环境下运行cxxtest框架生成的测试。该工具生成具有绝对路径的C ++文件。但是,gcc似乎无法解决这个绝对路径。

以下是演示此问题的最小示例:

// file1.h
#include <iostream>
inline void hallo() { std::cout << "Hallo\n"; }
// main.cpp
#include "/home/phil/example/file1.h"

int main()
{
  hallo();
  return 0;
}

文件存在(至少msys2 shell解析路径):

$ ls /home/phil/example/file1.h
/home/phil/example/file1.h

...但是调用g ++会导致此错误:

$ g++ main.cpp
main.cpp:1:38: fatal error: /home/phil/example/file1.h: No such file or directory
 #include "/home/phil/example/file1.h"
                                      ^
compilation terminated.

与clang相同的错误。

在完整的Linux环境下,该示例有效。如果我用相对的(#include "file1.h")替换绝对路径,它也有效。

因此,我认为问题出在Windows上负责解析路径的层。不确定我是否应该将其报告为msys2项目的错误,或者是否是已知问题。如果这是一个已知问题,是否有任何变通方法(如设置-I选项)?

(如果可能的话,我想避免替换绝对路径,因为它们是由cxxtest框架生成的代码。从技术上讲,对生成的文件运行后处理步骤是可能的,但从长远来看似乎是一个黑客攻击。)

2 个答案:

答案 0 :(得分:3)

Since you are running compilers that use MinGW-w64 as their runtime environment, they don't recognize POSIX-style paths like that. I think they actually interpret the root directory "/" to be "C:\". Other than that, they would only recognize native Windows-style paths.

I recommend that you pass the argument -I/home/phil/example to your compiler from some program running in the msys-2.0.dll POSIX emulation runtime environment (e.g. /usr/bin/bash or /usr/bin/make). The msys-2.0.dll runtime will then convert that argument to use a native Windows path so the compiler can understand it, and statements like #include <file1.h> will work. Alternatively, you might try putting a Windows-style path in your source code, e.g. the path should start with C:\.

Note however that having absolute paths in source code or build scripts is a bad idea since it makes it harder to build the code on a different computer. You could consider using environment variables or relative paths.

答案 1 :(得分:0)

尝试使用Cygwin提供的MinGW编译器作为包。 (换句话说,忘记MSYS环境;在Cygwin下工作,但是像以前一样以MinGW样式构建代码。)

然后你应该能够包含引用/home/phil;它只会解析为C:\Cygwin\home\phil或您的Cygwin根目录。

实际上,它也可能在MSYS下(毕竟,它只是Cygwin旧版的后代)。你只需要弄清楚/home/phil指的是什么,创建那棵树并在那里工作。