3
votes

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

3 Answers

5
votes

I got it done using get_filename_component.

get_filename_component(DIR_ONE_ABOVE ../ ABSOLUTE)
message(STATUS ${DIR_ONE_ABOVE})

Complete documentation : https://cmake.org/cmake/help/latest/command/get_filename_component.html

Thanks to ngladitz from the cmake IRC channel.

0
votes

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)
0
votes

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}../