Skip to content

Instantly share code, notes, and snippets.

@scivision
Last active Nov 10, 2021
Embed
What would you like to do?
Expand ~ tilde to home directory in CMake script
# CMake 3.21 makes this unnecessary with file(REAL_PATH ... EXPAND_TILDE)
# https://cmake.org/cmake/help/latest/command/file.html#real-path
function(expanduser in outvar)
# expands ~ to user home directory
#
# cmake_path and file do not expand ~
# get_filename_component expands ~ in C++ similar to above
#
# usage:
# expanduser("~/code" x)
string(SUBSTRING ${in} 0 1 first)
if(NOT ${first} STREQUAL "~")
set(${outvar} ${in} PARENT_SCOPE)
return()
endif()
if(WIN32 AND NOT CYGWIN)
set(home $ENV{USERPROFILE})
else()
set(home $ENV{HOME})
endif()
if(NOT home)
set(${outvar} ${in} PARENT_SCOPE)
return()
endif()
string(SUBSTRING ${in} 1 -1 tail)
if(CMAKE_VERSION VERSION_LESS 3.20)
file(TO_CMAKE_PATH ${home}${tail} out)
else()
cmake_path(CONVERT ${home}${tail} TO_CMAKE_PATH_LIST out)
endif()
set(${outvar} ${out} PARENT_SCOPE)
endfunction(expanduser)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment