Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove unused C/C++ symbols with GCC and ld?

Tags:

c++

c

gcc

strip

ld

I need to optimize the size of my executable severely (ARM development) and I noticed that in my current build scheme (gcc + ld) unused symbols are not getting stripped.

The usage of the arm-strip --strip-unneeded for the resulting executables / libraries doesn't change the output size of the executable (I have no idea why, maybe it simply can't).

What would be the way (if it exists) to modify my building pipeline, so that the unused symbols are stripped from the resulting file?


I wouldn't even think of this, but my current embedded environment isn't very "powerful" and saving even 500K out of 2M results in a very nice loading performance boost.

Update:

Unfortunately the current gcc version I use doesn't have the -dead-strip option and the -ffunction-sections... + --gc-sections for ld doesn't give any significant difference for the resulting output.

I'm shocked that this even became a problem, because I was sure that gcc + ld should automatically strip unused symbols (why do they even have to keep them?).

like image 667
Yippie-Ki-Yay Avatar asked Jul 14 '11 01:07

Yippie-Ki-Yay


People also ask

Does linker remove unused functions?

So the linker is able to remove each individual function because it is in its own section. So enabling this for your library will allow the linker to remove unused functions from the library.

Does C++ compiler remove unused code?

If either the compiler or the linker can see that there are no references to C functions or C variables, they can (and usually do) remove those unused things.


1 Answers

For GCC, this is accomplished in two stages:

First compile the data but tell the compiler to separate the code into separate sections within the translation unit. This will be done for functions, classes, and external variables by using the following two compiler flags:

-fdata-sections -ffunction-sections 

Link the translation units together using the linker optimization flag (this causes the linker to discard unreferenced sections):

-Wl,--gc-sections 

So if you had one file called test.cpp that had two functions declared in it, but one of them was unused, you could omit the unused one with the following command to gcc(g++):

gcc -Os -fdata-sections -ffunction-sections test.cpp -o test -Wl,--gc-sections 

(Note that -Os is an additional compiler flag that tells GCC to optimize for size)

like image 55
J T Avatar answered Oct 03 '22 22:10

J T