Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

c - How do I include only used symbols when statically linking with gcc?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...