getsoubl
getsoubl

Reputation: 1055

Cmake create a Makefile supports debug and release with different configuration

Is it possible to generate one makefile for debug and release mode, with different configuration using cMake? For example different CXX options or different paths where the executable is installed?

This a basic cMakeList.txt which creates a makefile for release and for debug mode.

cmake_minimum_required(VERSION 3.10)

# set the project name
project(Tutorial)

# add the executable
add_executable(Tutorial main.cpp)
set(CMAKE_CXX_STANDARD 17)
ADD_CUSTOM_TARGET(debug
  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.")

How is it expanded to support different Cxx options?

Upvotes: 0

Views: 1075

Answers (1)

fabian
fabian

Reputation: 82461

In this CMakeLists.txt file you set up a second version of the project during the configuration of the original project that is responsible for generating another version of the project for the release version. There are several drawbacks to this approach:

  • Doesn't deal with multi configuration generators(e.g. Visual Studio), properly
  • It sets up the release configuration twice, if you pass -DCMAKE_BUILD_TYPE=Release to the original setup.
  • It shares the same binary directory; This could very easily mess up the project badly

My recommendation would be to use generator expressions in all places where they are allowed

target_link_libraries(my_target PRIVATE
    $<$<CONFIG:Release>:libLinkedInReleaseOnly>
    $<$<CONFIG:Debug>:libLinkedInDebugOnly>
)

# define preprocessor macro containg the configuration name
target_compile_definitions(my_target PRIVATE MY_CONFIG_DEFINE=\"$<CONFIG>\")

and fall back to versions of properties and variables that are configuration dependent (i.e. include <CONFIG> in the linked lists) and setting up projects in multiple build directories with different configurations.

#bash example
for CONFIG in Debug Release
do
    mkdir $CONFIG
    cmake -D CMAKE_BUILD_TYPE=$CONFIG -S . -B $CONFIG
done

which allows you to do cmake --build Debug or cmake --build Release to build debug or release configurations of your project respectively. (You may want to set this up in a location different to the source dir btw which would require you to pass a different path as -S parameter.)

Upvotes: 2

Related Questions