How do I get the system's path separator with CMake

6.3k views Asked by At

I'm configuring some project with CMake. I need to get the path separator (e.g. / or \) into a CMake variable to do something with in, never mind what exactly. How can I do that?

2

There are 2 answers

2
Florian On

There is no CMake variable for the system's path separator that can directly be used.

But as @vre commented using the file(TO_NATIVE_PATH) command you could do:

file(TO_NATIVE_PATH "/" _separator)
message("The systems's path separator is '${_separator}'")

If you have complete paths the $<SHELL_PATH:...> generator expression (CMake version >= 3.4) is very useful:

Content of ... converted to shell path style. For example, slashes are converted to backslashes in Windows shells and drive letters are converted to posix paths in MSYS shells. The ... must be an absolute path.

1
byteswap On

Update, in CMake 3.20+, use the cmake_path function:

cmake_path(SET os_path_separator NORMALIZE "/")
cmake_path(NATIVE_PATH os_path_separator os_path_separator)