Discovering Unused Code?

Glom has been through a few refactorings. I’m sure that some of its functions are never called by anything, and I’d like to remove those to clean up the code a little.

Is there some tool that can tell me what’s not used in a C/C++ application? gcov can apparently tell me what code is used at runtime during specific tests, but running the application shouldn’t be necessary. I guess that some combination of nm and strip could give me a list, but that’s not ideal.

15 thoughts on “Discovering Unused Code?

  1. This will create a list of all symbols *defined and exported* by object files in your project:

    find -iname ‘*.o’ -exec nm \{\} \; | grep ” T ” | cut -c 20 | sort > symbols.defined

    This will create a list of all symbols *imported* by object files in your project:

    find -iname ‘*.o’ -exec nm \{\} \; | grep ” U ” | cut -c 20 | sort | uniq > symbols.used

    The latter will list both symbols defined in other libraries you are linking to and those defined in your own code. In C people usually define a common prefix for their exported symbols hence you can now do a “egrep ^foo_” (with foo_ being the prefix) over symbols.used to get the list of imported symbols that belong to your project. And then, you can generate a diff to the list of defined symbols and voila you have the list of defined but not used and used but not defined symbols:

    egrep ‘^foo_’ symbols.used | diff -u symbols.defined –

    That was easy, wasn’t it?

    Make sure to use a fresh checkout and do a complete build of this before you run this because otherwise you might have left over .o files lying around.

  2. If you follow blah’s idea, note that it potentially needs to be repeated multiple times: it won’t pick up code that is only referenced by unused code in the first pass.

  3. Would passing -Wunreachable-code -Wunused to gcc do what you’re looking for?

  4. There are two different ways to phrase the question. It’s easy to find
    functions that are never called from anywhere in the code: there are no references to the relevant symbol. But it’s more commonly the case
    that there is no feasible path through the executable that reaches
    the code in question. Coverity can find dead code by path-based analysis, but it’s proprietary and expensive.

    Adam Petaccia: -Wunreachable-code works only within one function, or one function plus those functions that are inlined into it.

  5. ajax, doesn’t -Wall already tell us about static functions that are not used? I’ve definitely seen that warning sometimes.

Comments are closed.