Symbol Name On Nix

Sometimes for debugging its handy to push out a little more info. For a tasking solution I was working on I had a failing task, but pushing out the function address in the console wasn’t very helpful. This little bit of code can resolve a pointer to a symbol name.

#include <stdio.h>
#include <dlfcn.h>


void
say_hi() {
        printf("Hello\n");
}


int global_int = 123;


int
main() {
        Dl_info info;
        int suc = dladdr(say_hi, &info);

        printf("%s\n", suc ? info.dli_sname : "Unknown - func");

        suc = dladdr(&global_int, &info);

        printf("%s\n", suc ? info.dli_sname : "Unknown - var");

        return 0;
}

build and go

cc sym_name.c && ./a.out

Outputs

say_hi
global_int

Just be aware the symbols can be stripped out.

~/Dev$ nm a.out 
0000000100000000 T __mh_execute_header
                 U _dladdr
0000000100001020 D _global_int
0000000100000e90 T _main
                 U _printf
0000000100000e70 T _say_hi
                 U dyld_stub_binder
~/Dev$ strip a.out
~/Dev$ nm a.out 
0000000100000000 T __mh_execute_header
                 U _dladdr
                 U _printf
                 U dyld_stub_binder

After that if you re run the application you will see the symbol names are gone.

~/Dev$ ./a.out
(null)
(null)