Reputation: 19225
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
?
Upvotes: 19
Views: 13021
Reputation: 1803
At least in modern versions of CMake, you can choose to strip the binaries at install time: either by building the install/strip
target instead of the install
target, or by passing --strip
to cmake --install
(see documentation for cmake --install
)
Upvotes: 2
Reputation: 1479
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.
Upvotes: 7
Reputation: 19225
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.
Upvotes: 16