Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get directory above CMAKE_CURRENT_SOURCE_DIR in CMake

Tags:

makefile

cmake

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.

like image 887
Saurabh Shrivastava Avatar asked Mar 08 '23 08:03

Saurabh Shrivastava


2 Answers

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.

like image 126
Saurabh Shrivastava Avatar answered Mar 16 '23 17:03

Saurabh Shrivastava


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)
like image 41
Kevin Avatar answered Mar 16 '23 18:03

Kevin