Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing Unused Symbols

Tags:

c++

c

linker

I want to remove dead code from a largish project and would like to start with unused symbols. Is there anyway to get the linker to list unused symbols that it has optimized out? I am using the GNU linker (LD) together with GCC.

Failing that, can any of the Binutils (readelf or objdump) perform the same function?

like image 546
doron Avatar asked Dec 15 '10 10:12

doron


2 Answers

Most compilers/linkers optimise out unused symbols. If you're running on a *nix system, you can try using the command "nm" on all the object files, filter it and sort it, to produce a list of all exported functions defined by those object files.

nm *.o | grep "^[0-9a-f]* T " | sed 's/^[0-9a-f]* T //' | sort -u > symbols_in.txt

I believe you can do the same on the final binaries.

If you then diff the two sets of results you should get a list of all unused exported functions.

Beware though that some functions may be used by code that is excluded as a result of conditional compilation. E.g. a #ifdef switch to say that on platform A, use such and such built in functionality and on another platform use your own version of the function because there is no built in or standard library equivalent, or it doesn't work properly.

like image 195
AlastairG Avatar answered Oct 13 '22 00:10

AlastairG


GCC can generate a compiler warning when it encounters functions, labels and function parameters that are unused. The compiler flags -Wunused -Wunused-parameter will do this.

I'd personally recommend turning on all warnings and extra warnings when developing. The flags are -Wall -Wextra and the dead code warnings are implied by these flags, together with a whole host of other warnings that I've found useful.

like image 23
CadentOrange Avatar answered Oct 13 '22 01:10

CadentOrange