Get directory above CMAKE_CURRENT_SOURCE_DIR in CMake

Viewed 5505

CMAKE_CURRENT_SOURCE_DIR returns the directory where the currently processed CMakeLists.txt is located in. The path is a full path from root.

How can we access, say a directory above the CMAKE_CURRENT_SOURCE_DIR.

E.g. If CMAKE_CURRENT_SOURCE_DIR = /Users/saurabhshri/Documents/GitHub/repo/src/

And I want the path /Users/saurabhshri/Documents/GitHub/repo/.

Of course doing ../${PROJECT_SOURCE_DIR} gives ..//Users/saurabhshri/Documents/GitHub/repo/src/.

I looked into "Locations" documentation of CMake (https://cmake.org/Wiki/CMake_Useful_Variables#Locations) and can not find anything.

3 Answers

In CMake 3.20 and greater, you can get the parent path using the cmake_path command, which supersedes the get_filename_component command:

cmake_path(GET <path-var> PARENT_PATH <out-var>)

So, in your case, you could use this:

cmake_path(GET CMAKE_CURRENT_SOURCE_DIR PARENT_PATH MY_PARENT_DIR)

If you want to like

E.g. If CMAKE_CURRENT_SOURCE_DIR = >/Users/saurabhshri/Documents/GitHub/repo/src/ And I want the path /Users/saurabhshri/Documents/GitHub/repo/.

More easier way than above answers

${CMAKE_CURRENT_SOURCE_DIR}../

Related