Size optimization with gold linker


When I use -flto -fuse-ld=gold to force clang to use gold as the linker. I found gold doesn’t support the optimization flag -Os. It says that the flag must between 0-3.

Does anyone know how to use size optimization with gold linker? Many Thanks.


There are two independent sets of “-O” options:

  1. The gcc/clang options -O[0-3sz]

These include -O0 to -O3 and -Os (optimize for size) and -Oz (attempt to achieve minimum size, even at significant runtime cost). These options affect the compiler’s optimizer. For example, they affect things like inlining and unrolling where performance can often be significantly increased at the cost of code size.

  1. The ld/gold/lld options -O[0-3]

As you found, these range from -O0 to -O3 and control features like linker string merging and tail duplication that tend to save some binary size. There is no -Os or -Oz since, unlike the compiler, the linker only does size optimizations (whereas the compiler has to balance performance against code size).

So to answer your question, the fact that there is no -Os for gold is as intended.

FWIW, if you are trying to save on code size, consider also passing -ffunction-sections -fdata-sections to clang/gcc when compiling your .cpp files and then pass --gc-sections --icf=all to gold/lld.

– Sean Silva