CMAKE_BINARY_DIR is created too late in the configuration phase
We are using camke -B ${build_dir} -S ${src_dir} ...
to have an out-of-source build. The CMake documentation at https://cmake.org/cmake/help/latest/manual/cmake.1.html#cmdoption-cmake-B says that ${build_dir}
will be created if it does not exist. However, it seems that the folder is created rather late in the CMake configuration process. My guess it, that this happens implicitly when a stable build configuration is written to ${build_dir}/CMakeCache.txt
.
In our use case, during the configuration phase, we execute an external application via execute_process(), which must write an output file somewhere, so other steps can pick it up. Using
${build_dir}seems a sane choice for the file location. However, the application complains that it can't create the file because
${build_dir}` does not exist. As a work-around, we have to use this now:
# At this stage CMake may not have created CMAKE_BINARY_DIR yet, so
# ensure it exists and we can place files there.
if(NOT EXISTS "${CMAKE_BINARY_DIR}")
file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}")
endif()
# Execute external app that collects config data and
# writes it to $(CMAKE_BINARY_DIR)/foo.cfg
execute_process(...)
This solves the problem, but we consider this a rather crude solution. The expectation is, that CMake should have created this folder for us. Furthermore, CMake should have abort the configuration phase early in case any issues prevent creating this folder.
Note that in many cases, external tool may create the ${build_dir}
folder silently if they have to put something in there, or a build system wrapper created this folder already, so many developers may never run into this issue. Also, creating files in the build folder during the configuration phase might be considered a bad thing, but unfortunately this can't be done in the build phase at the moment. Storing config data from the external application in a CMake variable to avoid touching '${build_dir}' also does not seem a good option due to the amount of data.
Ideally, CMake would create the '${build_dir}' folder before running any scripts. At minimum, the documentation should be clarified to state when exactly the folder is created by CMake, and creating it in a CMake script might be necessary. Also, when CMAKE_BINARY_DIR
is set up with a folder, CMake should guarantee the folder exists.