Home > Backend Development > C++ > How to Strip Unused Symbols from C/C Executables with GCC and ld?

How to Strip Unused Symbols from C/C Executables with GCC and ld?

DDD
Release: 2024-12-28 07:55:14
Original
659 people have browsed it

How to Strip Unused Symbols from C/C   Executables with GCC and ld?

How to Eliminate Unused Symbols in C/C Executables Using GCC and ld

Introduction

Optimizing executable size can be crucial in embedded systems or resource-constrained environments. To achieve this, it's important to remove unused symbols from the executable.

GCC and ld Symbols Stripping

GCC and ld provide options to discard unused symbols during compilation and linking:

GCC Options

  • -fdata-sections: Separates code and data into distinct sections in each translation unit.
  • -ffunction-sections: Splits functions into individual sections.

ld Options

  • -Wl,--gc-sections: Instructs ld to discard unreferenced sections.

Implementation

To remove unused symbols, follow these steps:

  1. Compile source files with GCC using -fdata-sections and -ffunction-sections flags.
  2. Link object files together using ld with -Wl,--gc-sections flag.

Example

Suppose we have a file test.cpp with two functions, one of which is unused:

int use(int a);
int unused(int a);
Copy after login

To remove the unused function, compile and link as follows:

gcc -Os -fdata-sections -ffunction-sections test.cpp -o test -Wl,--gc-sections
Copy after login

This command will instruct GCC to separate code and data into sections and ld to discard unreferenced sections, resulting in an executable with reduced size.

The above is the detailed content of How to Strip Unused Symbols from C/C Executables with GCC and ld?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template