Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake: how to normalize paths? [duplicate]

Tags:

cmake

Is there a robust way to normalize paths in CMake?

Example:

# Let's assume that an environment variable MY_ROOT_DIR is set
# that points to some directory.
set(MYFILE "$ENV{MY_ROOT_DIR}/somefile.txt")
message(${MYFILE})
# This will result for example in 
# Win:         C:\path\to\my\root\dir/somefile.txt
# Unix based:  /path/to/my/root/dir/somefile.txt

In this example, it would be required to normalize MY_ROOT_DIR (that is to replace backslashes with slashes) prior to using it as path component. How would you do this in CMake?

CMake (or the tools further down the toolchain) may handle paths with mixed separators (/ or \), or may not. CMake uses / as the standard separator. A typical warning generated by CMake for paths with the wrong path separator \ may look similar to this:

CMake Warning (dev) at cmake_install.cmake:5 (set):
  Syntax error in cmake code at

    C:/path/to/my/root/build/cmake_install.cmake:5

  when parsing string

    C:\path\to\my\root/somefile.txt

  Invalid escape sequence \p

  Policy CMP0010 is not set: Bad variable reference syntax is an error.  Run
  "cmake --help-policy CMP0010" for policy details.  Use the cmake_policy
  command to set the policy and suppress this warning.

Thanks for any hints on this!

like image 600
normanius Avatar asked Dec 20 '17 16:12

normanius


1 Answers

You can use the file(TO_CMAKE_PATH) command for this.

The TO_CMAKE_PATH mode converts a native <path> into a cmake-style path with forward-slashes (/). The input can be a single path or a system search path like $ENV{PATH}. A search path will be converted to a cmake-style list separated by ; characters.

Here is an example:

file(TO_CMAKE_PATH "$ENV{MY_DIR_VAR}" ENV_MY_DIR_VAR)
like image 147
Florian Avatar answered Oct 29 '22 21:10

Florian