Strip Symbols From Binary File During CMake Installation

Strip Symbols From Binary File During CMake Installation

When building projects with CMake, the compiled executables often contain debug symbols and other metadata. While these are useful during development, they increase the size of the final binary. For deployment, you usually want a smaller, stripped binary that contains only what's necessary to run the program. This tutorial explains how to strip symbols from a binary file during CMake installation.

Let's say we have the following CMakeLists.txt file:

cmake_minimum_required(VERSION 3.27)
project(myapp)

set(CMAKE_CXX_STANDARD 17)

add_executable(${PROJECT_NAME} main.cpp)
install(TARGETS ${PROJECT_NAME})

The main.cpp file looks like this:

#include <iostream>

int main() {
    std::cout << "Hello world" << std::endl;

    return 0;
}

Run the following command to generate the build files:

cmake -S . -B build

Build the project:

cmake --build build

At this point, the myapp binary will be inside build directory (depending on the platform and generator).

Instead of distributing a larger binary with debug information, we can tell CMake to strip it during installation by using --strip option:

cmake --install build --prefix build --strip

Here's what's happening:

  • --install build - install the project from the build directory.
  • --prefix build - set the installation prefix to build (just for demonstration). Executables are then placed under build/bin because CMake by default installs binaries into the bin subdirectory of the chosen prefix. In a real setup, you might use --prefix /usr/local, which would install them into /usr/local/bin.
  • --strip - strip debug symbols from installed executables and libraries.

On Linux systems, you can confirm the binary was stripped by running file command:

file build/bin/myapp

Example output:

build/bin/myapp: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=dfdd36106192d4481ddd86c8a65b64b5c5ba91e5, for GNU/Linux 3.2.0, stripped

Notice the last word: stripped.

Leave a Comment

Cancel reply

Your email address will not be published.