Where

When

November 2017
M T W T F S S
« Jun    
 12345
6789101112
13141516171819
20212223242526
27282930  

jb_logo_6_small

logo

Overriding the default CMake build types

Let’s imagine that our C++ source code utilizes Design By Contract methodology. The default build types provided by CMake are too general to work for us, and we want to be able to toggle use of contracts during the compile. We need to create new build types that suit our needs, and we need them to work on Linux and Windows. And so we’d do something like this in CMakeLists.txt:

# Set the Configuration types ...
if(WIN32)
    set(CMAKE_CONFIGURATION_TYPES Debug_contracts Debug_no_contracts Release_contracts Release_no_contracts 
         RelWithDebInfo_contracts RelWithDebInfo_no_contracts CACHE STRING "Supported configuration types"
        FORCE)
else()
    set(CMAKE_CONFIGURATION_TYPES Debug_contracts Debug_no_contracts Release_contracts Release_no_contracts 
         CACHE STRING "Supported configuration types"
        FORCE)
endif()
# And then make the Project function call.
project(MyProject)

And then set values for your newly defined build types:

if(WIN64MSVC OR WIN64INTEL)
# Just an example for Debug_contracts; repeat with needed flags for other types.
# Contracts on is the default state. We'd add /DNDEBUG in a "no_contracts" config. 
   set(CMAKE_CXX_FLAGS_DEBUG_CONTRACTS
        "${MY_CXX_FLAGS} /Zi /D"_ITERATOR_DEBUG_LEVEL=2" /MDd /LDd /Od " 
        CACHE STRING "Compiler flags for Debug_contracts builds" )       
   set(CMAKE_SHARED_LINKER_FLAGS_DEBUG_CONTRACTS "${MY_SHARED_LINKER_FLAGS} /DEBUG /NODEFAULTLIB:MSVCRT" 
        CACHE STRING "Linker flags for shared libraries; Debug_contracts" )
   set(CMAKE_EXE_LINKER_FLAGS_DEBUG_CONTRACTS "${MY_EXE_LINKER_FLAGS} /DEBUG" 
        CACHE STRING "Linker flags for executables; Debug_contracts")            
else() # Linux
   set(CMAKE_CXX_FLAGS_DEBUG_CONTRACTS "${MY_CXX_FLAGS} -g " 
        CACHE STRING "Compiler flags for Debug_contracts builds") 
   set(CMAKE_EXE_LINKER_FLAGS_DEBUG_CONTRACTS ${CMAKE_EXE_LINKER_FLAGS} 
       CACHE STRING "Linker flags for executables; Debug_contracts") 
endif()

Note that setting CMAKE_CONFIGURATION_TYPES prior to the project function call will not eliminate the default configuration types (Debug, Release, MinSizeRel, RelWithDebInfo, et al.), from the cache, but will prevent them from appearing in the VS configuration list.

Continue Reading