0

I am trying to use functions in dlcfn.h, to print custom trace from my C application.

I do link with -ldl, yet the linker complains that it cannot find dladdr().

What am I missing?

Here is an example, inst.c:

#define _GNU_SOURCE

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

__attribute__((no_instrument_function))
void __cyg_profile_func_enter (void *this_fn, void *call_site) {
    printf("%p\n", this_fn);

    Dl_info info;
    if (dladdr(this_fn, &info)) {
        printf("%p [%s] %s\n",
            this_fn,
            info.dli_fname ? info.dli_fname : "?",
            info.dli_sname ? info.dli_sname : "?");
    }
}

__attribute__((no_instrument_function))
void __cyg_profile_func_exit (void *this_fn, void *call_site) {
}

void my_function_b(void)
{
    printf("b!\n");
}

void my_function_a(void)
{
    printf("a!\n");
    my_function_b();
}

int main(void)
{
    my_function_a();
    my_function_b();
    return 0;
}

And a Makefile:

CFLAGS += -O0 -g -finstrument-functions -rdynamic -ldl

inst: inst.c
    gcc $(CFLAGS) $^ -o $@

The result:

$ make
gcc -O0 -g -finstrument-functions -ldl inst.c -o inst
/usr/bin/ld: /tmp/ccKL1sh2.o: in function `__cyg_profile_func_enter':
/home/gauthier/tmp/inst/inst.c:12: undefined reference to `dladdr'
collect2: error: ld returned 1 exit status
make: *** [Makefile:4: inst] Error 1
Gauthier
  • 40,309
  • 11
  • 63
  • 97

1 Answers1

1

You should put libraries after source or object files which import their functions, otherwise linker will optimize them out:

gcc -O0 -g -finstrument-functions inst.c -ldl -o inst
yugr
  • 19,769
  • 3
  • 51
  • 96
  • Thanks! This, again :) I was also missing `-rdynamic`, and it needs to be given at link time too, so also after the sources. Without it, dli_sname is NULL. – Gauthier Nov 15 '22 at 14:33