Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set specific compiler flags for a specific target in a specific build configuration using CMake?

Tags:

I've got a CMakeLists where I want to build some targets using the dynamic version of the C runtime, and some other targets using the static version.

Because this needs to be set per target, the default method of setting CMAKE_CXX_FLAGS_<Config> does not work; this overrides for all targets.

To that end, I tried something like the following:

# @fn       set_target_dynamic_crt # @brief    Sets the given target to use the dynamic version of the CRT (/MD or #           /MDd) # @param    ...  A list of targets to which this setting should be applied. function( set_target_dynamic_crt )     if ( MSVC )         message (WARNING ${CMAKE_BUILD_TYPE})         if (CMAKE_BUILD_TYPE STREQUAL "Debug")             set_target_properties ( ${ARGN} PROPERTIES COMPILE_FLAGS "/MDd" )         else()             set_target_properties ( ${ARGN} PROPERTIES COMPILE_FLAGS "/MD" )         endif()     endif() endfunction() 

However, this always chooses the release version (/MD) and when I query for the build type (the message call above) I get the empty string. (I suspect this is because I'm using the Visual Studio generator; I've seen more than one reference that says CMAKE_BUILD_TYPE is for makefiles only...)

How can I set compile options like this per target?

like image 964
Billy ONeal Avatar asked Apr 17 '12 22:04

Billy ONeal


1 Answers

In CMake 2.8.12 I added a target_compile_options command to address this need:

http://public.kitware.com/Bug/view.php?id=6493

http://www.cmake.org/cmake/help/git-master/manual/cmake-generator-expressions.7.html

target_compile_options(tgt PRIVATE "/MD$<$<CONFIG:Debug>:d>") 

See

http://www.cmake.org/cmake/help/git-next/manual/cmake-buildsystem.7.html#build-specification-with-generator-expressions

for more relating to CMAKE_BUILD_TYPE and several reasons why the generator expression is better (eg IMPORTED target config mapping).

like image 86
steveire Avatar answered Sep 19 '22 00:09

steveire