Question

I'm trying to setup a post-build command for CMake, which I have done using the ADD_CUSTOM_COMMAND directive as stated in the CMake documentation. What I'd like to do though, is only have the post-build run if I am creating a release build of my executable.

How does one accomplish this?

Was it helpful?

Solution

For Makefile-based generators you can check the CMAKE_BUILD_TYPE variable and act upon its value:

if(CMAKE_BUILD_TYPE STREQUAL Debug)
    message(STATUS "Do debug stuff")
elseif(CMAKE_BUILD_TYPE STREQUAL Release)
    message(STATUS "Do release stuff")
elseif(CMAKE_BUILD_TYPE STREQUAL RelWithDebInfo)
    message(STATUS "Do release with debug info stuff")
elseif(CMAKE_BUILD_TYPE STREQUAL MinSizeRel)
    message(STATUS "Do minimal size release stuff")
endif()

For Visual Studio based builds, this SO question seems to suggest that CMAKE_BUILD_TYPE also works with VS 2005+.

OTHER TIPS

I ran into something similar, wanting to copy a DLL file to a destination directory but only for release builds. After lots of torn hair I managed to get it to work using a few generator expressions (the $<...> thingies). I'm putting it here seven years later not so much to solve your problem (though I would admire your level of pertinence), but in order to save the cranial hair of the next person having this same problem and finding this question on google:

set(no_copy $<NOT:$<CONFIG:Release>>) # An abbreviation to make the example easier to read.
add_custom_command(TARGET myDLL POST_BUILD
    COMMAND "${CMAKE_COMMAND}" -E
    # do nothing for non-Release build
    $<${no_copy}:echo>
    # output text to make clear that the copy command is not actually issued
    $<${no_copy}:"copy omitted for non-release build, command would have been ">
    # the actual copy command, which is overridden by the "echo" above
    # in the case of a non-release build
    copy_if_different $<TARGET_FILE:myDLL> ${DIR_FOR_DLL})

The trick is to write an echo in front of the command that would otherwise be issued. This way, the command is not executed, even though a bit of noise is output. One could enclose the remainder of the command line in a number of generator expressions to shorten the output at the expense of a completely unreadable cmake file. On the other hand there seems to be no way to suppress the copy portably without generating any output. Finally, if you think there's an easy out and you can just write if($<CONFIG:Release>) ... endif(), I advise you to spare yourself the disappointment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top