Reputation: 5229
How to get the working directory from which cmake
was called?
I know that I can run execute_process()
at the beginning of my CMake code but maybe there is some better way like a built-in variable to the working directory of the CMake process.
What I want to achieve is to convert a relative path given in a CMake variable (given with -D...
) to an absolute path in CMake.
Upvotes: 3
Views: 5528
Reputation: 19916
What I want to achieve is to convert a relative path given in a CMake variable (given with -D...) to an absolute path in CMake.
Then simply create a cache variable of type PATH
(for directories) or FILEPATH
in your CMakeLists.txt. CMake will convert untyped command line arguments to absolute paths automatically.
$ cat CMakeLists.txt
cmake_minimum_required(VERSION 3.22)
project(test NONE)
set(input_file "" CACHE FILEPATH "some input file")
message(STATUS "${input_file}")
$ cmake -S . -B build -Dinput_file=foo.txt
-- /path/to/foo.txt
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
See the documentation:
It is possible for the cache entry to exist prior to the call but have no type set if it was created on the cmake(1) command line by a user through the
-D<var>=<value>
option without specifying a type. In this case the set command will add the type. Furthermore, if the<type>
isPATH
orFILEPATH
and the<value>
provided on the command line is a relative path, then the set command will treat the path as relative to the current working directory and convert it to an absolute path.
Here: https://cmake.org/cmake/help/latest/command/set.html?highlight=current%20working%20directory
Relatedly, when running in script mode (rather than project mode), several of the usual variables are set to the current working directory:
When run in
-P
script mode, CMake sets the variablesCMAKE_BINARY_DIR
,CMAKE_SOURCE_DIR
,CMAKE_CURRENT_BINARY_DIR
andCMAKE_CURRENT_SOURCE_DIR
to the current working directory.
https://cmake.org/cmake/help/latest/variable/CMAKE_SOURCE_DIR.html
Upvotes: 2