CMake : parent directory?

As of CMake 3.20, you can use the cmake_path command to get the parent directory of a given path:

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

This command supersedes the get_filename_component command.

So, in your example, it would look like this:

cmake_path(GET MYPROJECT_DIR PARENT_PATH PARENT_DIR)

You can also check if the path has a parent directory component first:

cmake_path(HAS_PARENT_PATH MYPROJECT_DIR MyDir_HAS_PARENT)
if(MyDir_HAS_PARENT)
    cmake_path(GET MYPROJECT_DIR PARENT_PATH PARENT_DIR)
endif()

This doesn't actually check the filesystem to verify a valid path, but it is a really useful path manipulation command.


As of CMake 2.8.12, the recommended way is to use the get_filename_component command with the DIRECTORY option:

get_filename_component(PARENT_DIR ${MYPROJECT_DIR} DIRECTORY)

For older versions of CMake, use the PATH option:

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

Tags:

Cmake