Search code examples
static-librariesbinaryfileselfobject-files

How to list all externally-undefined symbols of a static library on Linux?


I have a static library libfoo.a, which is just a compression of multiple .o files. I am looking for a way to list all symbols that

  • appear in the static library as UND
  • have no definition in this static library

So that I can find out all external symbol dependencies of this library.


Solution

  • You can use this method:

    ld -r -o deleteme.o --whole-archive libfoo.a
    nm -C --undefined-only deleteme.o       # `-C` if you might have C++ archive members
    rm deleteme.o
    

    Demo:

    one.c

    extern void two(void);
    
    void one()
    {
        two();
    }
    

    two.c

    extern void three(void);
    
    void two()
    {
        three();
    }
    

    Make a static library libonetwo.a:

    $ gcc -Wall -c one.c two.c
    $ ar rcs libonetwo.a one.o two.o
    

    nm parses the static library as if it were just a commandline list of its members:

    $ nm --undefined-only libonetwo.a 
    
    one.o:
                     U _GLOBAL_OFFSET_TABLE_
                     U two
    
    two.o:
                     U _GLOBAL_OFFSET_TABLE_
                     U three
    

    So incrementally link them all into a temporary object file:

    $ ld -r -o deleteme.o --whole-archive libonetwo.a
    

    Then see the residual undefined symbols of that object file and delete it:

    $ nm --undefined-only deleteme.o && rm deleteme.o 
                     U _GLOBAL_OFFSET_TABLE_
                     U three