Optimized Removal of Unused Symbols in GCC and ld Builds
When building executables, especially for ARM-based embedded systems, optimizing executable size is crucial to improve performance. One notable issue is the presence of unused symbols within the binary, contributing to unnecessary bloating.
To alleviate this problem in GCC and ld environments, a two-stage approach is employed:
Stage 1: Separating Code Sections
Using the compiler flags -fdata-sections and -ffunction-sections instructs the compiler to divide the code within each translation unit into distinct sections representing functions, classes, and external variables. This enables the isolation of unused symbols.
Stage 2: Discarding Unreferenced Sections
During the linking phase, invoking the linker with the optimization flag -Wl,--gc-sections triggers the linker to discard sections that lack references. This ensures that unused symbols are excluded from the final executable.
For example, considering a file test.cpp with two functions, one of which is unused, the following command would generate an executable that omits the unused function:
gcc -Os -fdata-sections -ffunction-sections test.cpp -o test -Wl,--gc-sections
By incorporating this two-stage approach, unused symbols can be effectively removed, significantly reducing the size of the final executable, thereby enhancing loading performance in resource-constrained embedded systems.
The above is the detailed content of How Can We Optimize GCC and ld Builds to Remove Unused Symbols and Reduce Executable Size?. For more information, please follow other related articles on the PHP Chinese website!