16

I'm deploying a small program compiled with gcc, 4.3.2-1.1 (Debian). This program will be deployed on virtual machine templates ranging from Debain 5 to bleeding edge Fedora, Ubuntu, Slackware, Arch and others.

The program depends on some symbols from Xen's libraries which are only available in an unstable tree. Hence, installing Xen's libraries via respective package managers on the virtual machine templates would not solve my immediate issue.

Until I package my own version of these libraries, I need to statically link the executable.

Does gcc 4.3-x, by default only include symbols that are actually used when statically linking, or is there another optimization flag that I should be passing to the linker? I know that statically linking is bad, I'm doing it only as a temporary work around.

Tim Post
  • 33,371
  • 15
  • 110
  • 174

1 Answers1

19

This issue is related not only to gcc, but to ld(1) too.

By default, gcc doesn't eliminate dead code, you can check this by compiling/linking executable, and then running

objdump -d a.out

which shows you all functions in your executable.

Simple "googling" give this link.

So, to remove unused functions, you need:

  • Compile with “-fdata-sections” to keep the data in separate data sections and “-ffunction-sections” to keep functions in separate sections, so they (data and functions) can be discarded if unused.
  • Link with “--gc-sections” to remove unused sections.
Tim Post
  • 33,371
  • 15
  • 110
  • 174
S.J.
  • 1,213
  • 2
  • 12
  • 15
  • Thanks. Sometimes it's frustrating just figuring out what to search for. Searching around using 'symbols' in the query produced everything I _wasn't_ looking for :) – Tim Post Mar 15 '11 at 05:31
  • 1
    this method works... But be careful as document https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html warns: `-ffunction-sections, -fdata-sections` ... Only use these options when there are significant benefits from doing so. When you specify these options, the assembler and linker create larger object and executable files and are also slower. You cannot use gprof on all systems if you specify this option, and you may have problems with debugging if you specify both this option and -g. – EDkan Feb 26 '16 at 12:12