Getting CMake to build out of source without wrapping scripts

后端 未结 3 1407
余生分开走
余生分开走 2020-11-30 04:05

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

3条回答
  •  时光取名叫无心
    2020-11-30 04:40

    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:

    • When the user is lazy and simply runs 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.
    • Any command line arguments passed to the original call to cmake will not be passed to the "out-of-source build call".

    Suggestions to improve this module are welcome.

提交回复
热议问题