How do I get the parent directory path of a path in CMake?

For CMake 3.20 and newer, the recommended way is to use cmake_path with a PARENT_PATH option:

cmake_path(GET MYPROJECT_DIR PARENT_PATH PARENT_DIR)

For older versions up to CMake 2.8.12, use the get_filename_component command with the DIRECTORY option:

get_filename_component(PARENT_DIR ${MYPROJECT_DIR} DIRECTORY)

For versions of CMake older than 2.8.12, use the PATH option:

set (MYPROJECT_DIR /dir1/dir2/dir3/myproject/)
get_filename_component(PARENT_DIR ${MYPROJECT_DIR} PATH)

Leave a Comment