Finding an object file defining a symbol

I was working on a project that needed a tiny amount of functionality from another, much larger, project.  Rather than linking in all the object files, I wanted to keep to the minimum.  Unfortunately, some of the functions I called had very generic names, and I had no idea which object files they were coming from.  Shell scripting to the rescue:

#!/bin/bash
for I in *.o; do
    objdump -twC "$I" | awk '{if($2=="g") print}' | grep "$@" | sed "s/^/$I\t/"
done

To break it down:

  • objdump, as you might guess, dumps the contents of an object file.  The -t argument tells it to dump the symbol table, the -w (wide) tells it not to truncate lines, and the -C tells it to demangle C++ symbols.
  • The awk part searches for a “g” in the second field, which flags the symbol as a global.
  • grep searches for the symbol you want.  Note that you can use regexes, and you can pass grep options such as –color=always, -i (for case insensitive), or -E (for extended regexes).
  • Finally, sed sticks the filename in front of the line so you know which file it came from.

Works both for functions and global variables.  Now when I get “undefined reference to `foo'”, I know where foo is.

Post a Comment

Your email is never shared. Required fields are marked *

*
*