5

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

7
  • An ugly idea: concatenate all your code files temporarily into one file, make all your functions static in that file. The compiler will tell you the unused ones. But probably you would like something nicer... Commented Mar 24, 2014 at 22:14
  • Suggestion: the preprocessed sources can be maybe a better subject of the analyse. Commented Mar 24, 2014 at 22:14
  • Use a compiler/linker that removes unreferenced functions and outputs a list of those. Commented Mar 24, 2014 at 22:16
  • Do you have system or integration tests? Commented Mar 24, 2014 at 22:19
  • 6
    Have you looked HERE? Or HERE? Or HERE? Commented Mar 24, 2014 at 22:19

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

The easiest way is to process the object files in the project, rather like a linker would. It doesn't have to do anything other than notice unreferenced symbols, so this is much easier than writing a linker.

The Unix/Linux/Cygwin utility called lorder does what you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.