Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake convert unix to windows path

I'm trying to convert a unix style MSYS path such as /c/my/path/to/a/folder to a Windows path, or something that CMake would understand, e.g C:/my/path/to/a/folder. I'd like it to work on a path that is already correct.

Is there any proper way to do it ?

Note : Please do not mention cygwin's cygpath.

Edit: file(TO_CMAKE_PATH mypath result) is not working

like image 520
Lectem Avatar asked Apr 01 '15 17:04

Lectem


2 Answers

There's no built-in CMake functionality for this, but you can write a function/macro to do it:

macro(msys_to_cmake_path MsysPath ResultingPath)
  string(REGEX REPLACE "^/([a-zA-Z])/" "\\1:/" ${ResultingPath} "${MsysPath}")
endmacro()

set(mypath "/c/my/path/to/a/folder")
msys_to_cmake_path(${mypath} result)

message("Converted \"${mypath}\" to \"${result}\".")

Having said that, I agree with Antonio's comment in that it seems unusual to need this in the first place.

like image 107
Fraser Avatar answered Sep 30 '22 06:09

Fraser


As an alternative to the accepted answer, you may wish to consider that MSYS itself will perform the conversion at any boundary between MSYS parent and native child process; thus, in an MSYS shell console:

cmd //c echo /c/my/path/to/a/folder

would display the appropriately converted path c:/my/path/to/a/folder. Additionally, this technique offers the possible advantage that it will emit the fully converted native form of a path, such as:

cmd //c echo /home/my/path/to/a/folder

to yield its native equivalent C:/MinGW/msys/1.0/home/my/path/to/a/folder, (assuming your MSYS installation is in the recommended default location, at C:/MinGW/msys/1.0).

With the caveat that running MSYS shell without proper initialization, as performed by msys.bat, may not work, (especially when running on 64-bit Windows), you may be able to run an equivalent command from within a native process, (such as within CMake), as:

C:/MinGW/msys/1.0/bin/sh -c 'cmd //c echo /home/my/path/to/a/folder'

Note that, if you invoke this from a native process which is itself running within an MSYS console, the initialization will have been correctly performed for the console's own shell process, and should thus propagate through the native process; the issues are more likely to arise if you attempt to invoke MSYS processes directly from a cmd.exe process, in a native Windows console, (or other native container).

Also note that, if the path name in question contains spaces, (never a good idea), you may need to enclose it within double quotes:

cmd //c echo "/home/my/path with spaces"

In this case, some experimentation indicates that the double quotes remain within the cmd output. I'm not entirely certain if this is necessary; you should use your discretion in your own particular usage case.

like image 21
Keith Marshall Avatar answered Sep 30 '22 06:09

Keith Marshall