Home >Backend Development >C++ >How Can I Reduce C/C Executable Size by Stripping Unused Symbols?

How Can I Reduce C/C Executable Size by Stripping Unused Symbols?

Barbara Streisand
Barbara StreisandOriginal
2024-12-17 13:05:25988browse

How Can I Reduce C/C   Executable Size by Stripping Unused Symbols?

Optimizing Executable Size: Stripping Unused C/C Symbols

Minimizing executable size is crucial, especially in resource-constrained environments. By stripping unused symbols from an executable, it becomes leaner and more efficient in terms of memory usage. This article explores how to achieve this optimization using GCC and ld.

GCC and ld Configuration

GCC and ld can be configured to remove unused symbols from executables and libraries. To do this, two stages of compilation are required:

  1. Data Separation: During compilation, use the -fdata-sections and -ffunction-sections flags with GCC. These flags instruct the compiler to segregate code into separate sections within each translation unit, including functions, classes, and external variables.
  2. Link Optimization: When linking the translation units together, employ the linker optimization flag -Wl,--gc-sections. This flag triggers the linker to automatically discard any unreferenced sections.

Example

Consider a file test.cpp which contains two declared functions, but one of them is unused. To exclude the unused function from the final executable, use the following command:

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

The -Os flag instructs GCC to prioritize code size optimization.

Conclusion

By applying these configuration changes, the compiler and linker can identify and remove unused symbols, significantly reducing the size of the resulting executable. This optimization is especially valuable for embedded systems or other environments with strict resource limitations.

The above is the detailed content of How Can I Reduce C/C Executable Size by Stripping Unused Symbols?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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