Search code examples
c++gccclangmingwmsys2

gcc and clang under msys2 cannot resolve includes with absolute paths


I try to get tests generated by the cxxtest framework working under a MinGW environment managed by mysys2. The tool generates C++ files with absolute paths. However, gcc seems to be unable to resolve this absolute paths.

Here is a minimal example to demonstrate the problem:

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

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

The file exists (at least the msys2 shell resolves the path):

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

... but calling g++ results in this error:

$ 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.

Same error with clang.

Under a full Linux environment, the example works. It also works if I replace the absolute path by a relative one (#include "file1.h").

So, I assume the problem lies in the layer over Windows that is responsible to resolve paths. Not sure whether I should report it as a bug to the msys2 project, or whether it is a known problem. If it is a known problem, are there any workarounds (like setting -I options)?

(If possible, I would like to avoid replace the absolute paths, as they are in generated code by the cxxtest framework. Technically, running a postprocessing step on the generated files would be possible but seems like a hack in the long run.)


Solution

  • 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.