To inherit a custom configuration (e.g., MyConfig) from Debug in CMake, you need to ensure that your custom configuration uses the same compiler flags, definitions, and settings as Debug by default. Here’s how to achieve this:
1. Define CMAKE_CONFIGURATION_TYPES Early
First, declare your custom configuration in CMAKE_CONFIGURATION_TYPES before the project() command:
cmake_minimum_required(VERSION 3.15)
# Add 'MyConfig' to the list of available configurations
set(CMAKE_CONFIGURATION_TYPES "Debug;Release;RelWithDebInfo;MinSizeRel;MyConfig" CACHE STRING "Configurations" FORCE)
project(MyProject)
2. Inherit Debug Settings for MyConfig
To make MyConfig behave like Debug by default, you can:
- Copy
Debug-specific flags (e.g., CMAKE_CXX_FLAGS_DEBUG) to MyConfig.
- Use
CMAKE_CXX_FLAGS_MYCONFIG (or equivalent for C, linker, etc.) to mirror Debug.
Method 1: Explicitly Copy Debug Flags
if(CMAKE_CONFIGURATION_TYPES)
# Inherit compiler flags from Debug
set(CMAKE_C_FLAGS_MYCONFIG "${CMAKE_C_FLAGS_DEBUG}" CACHE STRING "Flags for MyConfig" FORCE)
set(CMAKE_CXX_FLAGS_MYCONFIG "${CMAKE_CXX_FLAGS_DEBUG}" CACHE STRING "Flags for MyConfig" FORCE)
set(CMAKE_EXE_LINKER_FLAGS_MYCONFIG "${CMAKE_EXE_LINKER_FLAGS_DEBUG}" CACHE STRING "Linker flags for MyConfig" FORCE)
# ... Add other flags as needed (e.g., static/shared libs)
endif()
Method 2: Use CMAKE_CXX_FLAGS_INIT (Advanced)
If you want to ensure consistency across all projects, you can define initial flags in a toolchain file or early in CMakeLists.txt:
set(CMAKE_CXX_FLAGS_MYCONFIG_INIT "${CMAKE_CXX_FLAGS_DEBUG_INIT}")
3. Apply Configuration-Specific Settings
Use generator expressions to conditionally apply settings for MyConfig (e.g., extra defines or includes):
add_executable(my_app main.cpp)
# Inherit Debug's defines and add custom ones
target_compile_definitions(my_app
PRIVATE
$<$<CONFIG:Debug>:DEBUG_MODE> # Debug-specific
$<$<CONFIG:MyConfig>:DEBUG_MODE> # Inherit Debug's define
$<$<CONFIG:MyConfig>:MY_CONFIG_EXTRA> # MyConfig-only define
)
# Inherit Debug's optimization level (typically -O0)
set_target_properties(my_app PROPERTIES
COMPILE_OPTIONS "$<$<CONFIG:MyConfig>:-O0>"
)