Stripping Unused Symbols from Executables with GCC and ld
In situations where reducing the size of executables is crucial, developers may encounter issues with unused symbols remaining in the final build. This can lead to unnecessarily large file sizes and performance inefficiencies. To address this, a specific compilation and linking strategy can be implemented using GCC and ld.
Compilation Phase:
To separate code into distinct sections within a translation unit, the following compiler flags can be used:
These flags allow the compiler to allocate unused code into separate sections for later removal by the linker.
Linking Phase:
During the linking process, the linker optimization flag -Wl,--gc-sections can be employed. This flag instructs the linker to discard any unreferenced sections.
By combining these compilation and linking techniques, unused symbols can be effectively removed from the resulting executable. For instance, if a file test.cpp contains two functions and one is unused, the following command can be used:
gcc -Os -fdata-sections -ffunction-sections test.cpp -o test -Wl,--gc-sections
In this command, -Os is an additional compiler flag for size optimization. By following these steps, developers can significantly reduce the size of their executables and enhance performance in resource-constrained environments.
The above is the detailed content of How Can GCC and ld be Used to Remove Unused Symbols from Executables?. For more information, please follow other related articles on the PHP Chinese website!