The Linux Page

Debug and/or Release specific command line option in cmake

Today I ran in a problem with cmake which was to very simply select /MT instead of /MD for a small set of projects. The problem is that so far this feature was at least on a per directory basis. Since the exact same directory is used to build the dynamic (DLL) and static (.lib) libraries, having two directories is not exactly an option here.

set ( CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT" )
set ( CMAKE_C_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT" )
set ( CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_RELEASE} /MTd" )
set ( CMAKE_C_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_RELEASE} /MTd" )

Looking really deep in the problem, I could quickly see that cmake did not offer that super basic capability (sorry!) It was available via set() but that was not granular enough. However, I was lucky enough to find out that some people had been working on this issue since 2008 and... it just came out in June 2013! So I was in luck, for once. This is now possible. We have to use the target_compile_options() command that sets the COMPILE_OPTIONS variable to the value you decide to set it to, possibly different depending on the configuration name. There is the code:

    target_compile_options( ${PROJECT_NAME}
        PUBLIC "/MT$<$<STREQUAL:$<CONFIGURATION>,Debug>:d>"
    )

Simple, right?

The $<...> syntax are inline expressions (cmake calls them generator expressions). Here we get the value of the current configuration ($<CONFIGURATION>). Then we compare that current configuration with the string Debug. That gives us the Boolean result 0 or 1. The $<0:...> or $<1:...> expression uses or not the ... value, the string d in our example. So if the configuration is Debug, add a "d" to the /MT option.