Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake: Platform independent binary stripping for release builds

Tags:

c++

strip

cmake

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?

like image 907
BullyWiiPlaza Avatar asked Dec 09 '18 12:12

BullyWiiPlaza


2 Answers

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.

like image 75
BullyWiiPlaza Avatar answered Nov 20 '22 21:11

BullyWiiPlaza


While using add_custom_command, I was having issues with the COMMAND generator expression containing spaces. The ARGS option can be used while still toggling the inclusion of the custom command through a generator expression for the COMMAND option:

add_custom_command(
  TARGET "${TARGET}" POST_BUILD
  DEPENDS "${TARGET}"
  COMMAND $<$<CONFIG:release>:${CMAKE_STRIP}>
  ARGS --strip-all $<TARGET_FILE:${TARGET}>
)

This results in strip --strip-all myapp being called when config is release, but no command being called when it's not, despite the args being specified in a separate option.

like image 2
inkychris Avatar answered Nov 20 '22 23:11

inkychris