[CMake] How to support separate debug and release build directories?

David Aldrich david.aldrich.ntml at gmail.com
Fri Jun 21 09:19:29 EDT 2019


Thanks for the help I have received in the past few days. I am making
incremental improvements to my CMake project and have a new challenge.  I
am running CMake 3.13 on Centos 7.6, targeting make.  My CMake file
successfully builds debug or release targets and puts the executable in an
out-of-source build directory.  I have added debug and release make targets
so I can execute 'make debug' etc.

I now want to support separate target directories: build/debug and
build/release.  I've shown my CMakeLists.txt below. So far I've just added
an attempt to support build/debug:

if (CMAKE_BUILD_TYPE EQUAL "DEBUG")
    message("debug mode")
    set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/debug)
endif (CMAKE_BUILD_TYPE EQUAL "DEBUG")

but:

$ cmake3 -DCMAKE_BUILD_TYPE=DEBUG ..

puts the target into build, not build/debug.

I would also like this to work if I use the make targets e.g. make debug.

Here's my full CMakeLists.txt.  Any advice would be appreciated.

cmake_minimum_required(VERSION 3.5 FATAL_ERROR)

if(NOT CMAKE_BUILD_TYPE)
  set(CMAKE_BUILD_TYPE "Release")
  message(STATUS "Build type not specified: Use Release by default")
endif(NOT CMAKE_BUILD_TYPE)

project(hello_world LANGUAGES CXX)    # Among other things, this sets
PROJECT_NAME

add_executable(${PROJECT_NAME} "")

target_include_directories(${PROJECT_NAME}
    PRIVATE
        ${CMAKE_CURRENT_SOURCE_DIR})

target_sources(${PROJECT_NAME}
  PRIVATE
    main.cpp
    Message.cpp)

ADD_CUSTOM_TARGET(debug
  COMMAND ${CMAKE_COMMAND} -DCMAKE_BUILD_TYPE=Debug ${CMAKE_SOURCE_DIR}
  COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target all
  COMMENT "Creating the executable in the debug mode.")

ADD_CUSTOM_TARGET(release
  COMMAND ${CMAKE_COMMAND} -DCMAKE_BUILD_TYPE=Release ${CMAKE_SOURCE_DIR}
  COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target all
  COMMENT "Creating the executable in the release mode.")

if (CMAKE_BUILD_TYPE EQUAL "DEBUG")
    message("debug mode")
    set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/debug)
endif (CMAKE_BUILD_TYPE EQUAL "DEBUG")
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://cmake.org/pipermail/cmake/attachments/20190621/ff39f1a4/attachment.html>


More information about the CMake mailing list