In CMake, I want to create a directory if it doesn't already exist. How can I do this?
3 Answers
When do you want to create the directory?
At build system generation
To create a directory when CMake generates the build system,
file(MAKE_DIRECTORY ${directory})
At build time
In the add_custom_command()
command (which adds a custom build rule to the generated build system), and the add_custom_target()
command (which adds a target with no output so it will always be built), you specify the commands to execute at build time. Create a directory by executing the command ${CMAKE_COMMAND} -E make_directory
. For example:
add_custom_target(build-time-make-directory ALL
COMMAND ${CMAKE_COMMAND} -E make_directory ${directory})
At install time
To create a directory at install time,
install(DIRECTORY DESTINATION ${directory})

- 12,912
- 4
- 46
- 47
-
Succint and quick. Hits the target right away! Thanks. – daparic May 29 '20 at 08:51
-
cmake -E is not a recognized flag. – Bart Louwers May 25 '23 at 12:27
-
https://cmake.org/cmake/help/latest/manual/cmake.1.html#run-a-command-line-tool – Aaron D. Marasco May 25 '23 at 20:24
To create a directory at install time,
install(DIRECTORY DESTINATION ${directory})
These will both run at configure time:
file(MAKE_DIRECTORY ${directory})
execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${directory})
To create during the build, use a custom target:
add_custom_target(mytargetname ALL COMMAND ${CMAKE_COMMAND} -E make_directory ${directory})
In addition to Chin Huang's reply, you can also do this at build time with add_custom_command
:
add_custom_command(TARGET ${target_name} PRE_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory ${directory})
You can also change the moment, when your directory is created with PRE_BUILD
| PRE_LINK
| POST_BUILD
parameters.

- 16,549
- 8
- 60
- 74

- 201
- 2
- 5