CMake file separator

In many cases, using the Unix-type slash file separator / will work even on Windows. Trying to manually specify backslash Windows file separator \ can cause problems in CMake and many other languages. Thus in CMake and other languages like Python, we always use / as path separator, and only transform to backslash for the rare cases it’s needed.

Transform to Unix file separator

file(TO_CMAKE_PATH …) switches backslash \ file separators to Unix slash / file separators. This becomes relevant if manually adjusting Include paths by appending to _INCLUDE_DIRS or similar. If backslashes sneak through, all kinds of weird build-time errors can result, and even configure-time errors if you use “check_c_source_compiles()” and similar. As the docs note, put quotes "${mypath}" around the variable expansion to ensure CMake doesn’t mangle the path.

The source code is in cmFileCommand.cxx in function HandlePathCommand. Many internal factory CMake scripts use TO_CMAKE_PATH without if() guards.

Example

This CMake script can be used like

cmake -Din=c:\foo\bar -P to_cmake_path.cmake
file(TO_CMAKE_PATH "${in}" out)

message("${in} => ${out}")

prints out:

c:/Program Files/CMake

Transform to native file separator

This would be much more rarely used, but if needed, CMake can transform paths to native file separator, with the caveat that this can cause unpredictable Windows-specific backslash problems, as with any program.

file(TO_NATIVE_PATH ...)

CMake expanduser ~