Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect unused functions in C [duplicate]

I'm looking for a way to check if my C project, that compiles to an ELF, has unused functions, and locate them. That is functions that are declared but are not called anywhere in my code.

The solution can be one of:

  • A utility that goes through my .c files, analysing them
  • A utility that goes through my compiled ELF file, that has symbols, analysing it statically
  • A way to warn about unused functions in gcc (and -Wunused-functions doesn't do that for global functions)

The solution cannot be one of:

  • Deleting unused functions in compile time, without knowing what functions were deleted
  • Analysing the ELF file in run-time, since not every function will be called in every run such as gprof (some functions take days until they are called, but in the code flow you can see that they are eventually called)
  • A utility that discovers dead-code inside functions (i.e. code after a return from function), rather than unused functions

Thank you

like image 588
speller Avatar asked Nov 10 '22 10:11

speller


1 Answers

If you need something exact, automated or polished, you need your compiler and build-system to team up and do it for you, somehow.

If you don't need exact results or something particularly automated or polished, then here's a very rough approximation: It'll find every word that occurs only once in all of your .c files.

find . -name \*.c -exec cat {} \; \
   | tr -s '[[:space:];:,?!.|()-"<>=]' '\n' \
   | sort \
   | uniq -u

This could of course fail in a million ways: preprocessor tricks, comments repeating function names, functions named the same as common words used in comments etc.

like image 61
Søren Debois Avatar answered Nov 15 '22 10:11

Søren Debois