Separating Release and Debug Information with CMake using objcopy
2 min readSep 15, 2024
Why use RelWithDebInfo?
- Speed of a Release Build
- Includes Debug information which makes it easier to debug in case of problems
Why Separate the 2?
- Debug information makes the generated target (executable or shared library) size bigger
- Due to the proprietary nature of certain applications, internal organisational policies etc. it is quite possible that the organisation might not wish to distribute thedebug portions of the build.
However, the organisation logically believes that the Debug information is important enough to retain for easy debugging of issues pointed out by clients etc. - The approach mentioned below works with gdb
How?
We will take advantage of the objcopy command.
Using it we can:-
- Separate the debugging information into a different file
- Remove debugging information from the original file
- Link the 2 files together
In CMake, one of the major advantages is that objcopy can be found using CMAKE_OBJCOPY
# NOTE: The dbg extension is used solely because it is used as a standard
# NOTE: In Linux documentation etc.
# NOTE: Obtained from https://www.man7.org/linux/man-pages/man1/objcopy.1.html
add_custom_command(
TARGET ${TARGET}
# Separate the Debug Information from the Target file
COMMAND ${CMAKE_OBJCOPY} ARGS --only-keep-debug $<TARGET_FILE:${TARGET}> $<TARGET_FILE:${TARGET}>.dbg
# As we have previously separated the debug information from the
# previous output, remove all debug information from the same
COMMAND ${CMAKE_OBJCOPY} ARGS --strip-debug $<TARGET_FILE:${TARGET}>
# Link the Separate Debug Information with the Final Release
COMMAND ${CMAKE_OBJCOPY} ARGS --add-gnu-debuglink=$<TARGET_FILE:${TARGET}>.dbg $<TARGET_FILE:${TARGET}>
DEPENDS ${TARGET}
POST_BUILD
)
Cleaning the Artifacts
In case CMake’s clean command is run, it does not end up erasing the debugging information files generated in the previous step.
# NOTE: Add this to the clean target
# NOTE: This is needed because otherwise old debug information
# NOTE: Will not be cleared upon clean
set_property(
TARGET ${TARGET}
APPEND
PROPERTY
ADDITIONAL_CLEAN_FILES
$<TARGET_FILE:${TARGET}>.dbg
)
In order, to ensure the same, we would have to take advantage of CMake’s ADDITIONAL_CLEAN_FILES.
Complete Example
Contact Me
In case of any doubts, you can contact me via LinkedIn.