Search code examples
c++cmakestrip

CMake: Platform independent binary stripping for release builds


How can you add binary stripping to CMake for gcc and clang as a post-processing step but only in release builds? MSVC strips by default so it does not have to be handled.

One of the problems is that clang does not have a -s compilation flag but gcc does so doing it this way does not work.

Another idea is to use the strip command. The -s switch again exists on Linux but not on XCode (this is Apple's development toolchain).

So the final choice is to use the strip command without any arguments besides the binary itself which appears to be a decent generic solution. How can this be used in CMake?


Solution

  • In CMake add_custom_command can execute post build commands such as strip. The PROJECT_NAME variable is defined as your target binary e.g.

    # Set the project name
    set(PROJECT_NAME "MyProject")
    project(${PROJECT_NAME})
    

    Place the following code after add_executable of your CMakeLists.txt:

    # Strip binary for release builds
    add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
        COMMAND $<$<CONFIG:release>:${CMAKE_STRIP} ${PROJECT_NAME}>)
    

    CMAKE_STRIP is the file path to the platform's strip utility (e.g. /usr/bin/strip on Linux). The $<$<CONFIG:cfg>:str> generator expression will expand to str when building the configuration cfg, and to an empty string otherwise. In this scenario, this directly means "call strip when building in Release, and do nothing otherwise". Note that the CONFIG generator is case insensitive on your build type, and will work when using multi-config generators.