I\'m trying to get CMake to build into a directory \'build\', as in project/build
, where the CMakeLists.txt is in project/
.
I know I can do
Based on the previous answers, I wrote the following module that you can include to enforce an out-of-source build.
set(DEFAULT_OUT_OF_SOURCE_FOLDER "cmake_output")
if (${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR})
message(WARNING "In-source builds not allowed. CMake will now be run with arguments:
cmake -H. -B${DEFAULT_OUT_OF_SOURCE_FOLDER}
")
# Run CMake with out of source flag
execute_process(
COMMAND ${CMAKE_COMMAND} -H. -B${DEFAULT_OUT_OF_SOURCE_FOLDER}
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
# Cause fatal error to stop the script from further execution
message(FATAL_ERROR "CMake has been ran to create an out of source build.
This error prevents CMake from running an in-source build.")
endif ()
This works, however I already noticed two downsides:
cmake .
, they will always see a FATAL_ERROR
. I could not find another way to prevent CMake from doing any other operations and exit early.cmake
will not be passed to the "out-of-source build call".Suggestions to improve this module are welcome.