Is there a "$/", an easy "path-separator" variable?

Does CMake have some (easy) way to inject a platform-specific path separator? Something like “$/”?

SET(DESTINATION_DIR "${CMAKE_CURRENT_LIST_DIR}$/..$/bin")

Also … if there isn’t, it would be awesome if it could automatically swallow whitespace, so that:

SET(DESTINATION_DIR "${CMAKE_CURRENT_LIST_DIR} $/ .. $/ bin")

would expand to a well formed path without the spaces.

I guess a path join command would be an equally good way to do it:

get_joined_path(DESTINATION_DIR ${CMAKE_CURRENT_LIST_DIR} .. bin)

though this seems like it might trip up over “C:\Program Files (x86)” :slight_smile:

There is file(TO_NATIVE_PATH) to convert where needed. But you should use / everywhere within CMake code.

1 Like

But you should use / everywhere within CMake code.

Can you expand on why?

It produces confusing paths like C:\Program Files (x86)\Company\Product/1.3.1\include/headers

Surely there are no places where CMake doesn’t understand \'?

And trying to teach a large base of developers with limited cross-platform experience and/or rare contact with CMakeLists "You should always use /" is largely received as “forget about paths” and makes trying to teach them they have to normalize paths in some weird edgecases much harder.

I’m actually considering doing

if (WIN32) set("/" "\\") else() set("/" "/") endif()
...
set(_library_path "${CMAKE_CURRENT_LIST_DIR}${/}${_version_folder}${/}library.lib")

the {}s are required since to stop $ and / being recognized as individual tokens rather than a single token, but it’s probably easier to teach once it’s been instigated across all our current cmakelists.txt and *.cmake files.

Definitively, to avoid any trouble about escaping, especially when you pass variable contents to commands, it is strongly recommended to use exclusively the slash as path separator.

Moreover, to be complete, file(TO_NATIVE_PATH) is now superseded by cmake_path command.
This command offers wide possibilities to deal with paths. For example, to compute a path from fragments:

cmake_path(APPEND DESTINATION_DIR "${CMAKE_CURRENT_LIST_DIR}" ".." "bin")
1 Like