How to find the parent directory in CMake ?
Assume that ${MYPRO开发者_Go百科JECT_DIR}=/dir1/dir2/dir3/myproject/
and I want ${PARENT_DIR}=/dir1/dir2/dir3/
.
How to do that ?
SET(PARENT_DIR ${MYPROJECT_DIR}/../)
doesn't seem to be the right syntax.
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)
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.
For me it didn't work (at cmake 3.18). I ended up using:
get_filename_component(VAR_PARENT ${MYPROJECT_DIR}/.. ABSOLUTE)
精彩评论