Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which library the program is linked to that provides a given function?

Tags:

c

gdb

I have a program invoking function foo that is defined in a library. How can I know where the library is in the file system? (like is it a static library or a dynamically linked lib?)

Update: with using ldd, the program has a lot of dependency library. How to tell which lib contains function foo?

like image 882
Richard Avatar asked Dec 03 '22 09:12

Richard


2 Answers

You didn't say which OS you are on, and the answer is system-dependent.

On Linux and most UNIX systems, you can simply ask the linker to tell you. For example, suppose you wanted to know where printf is coming from into this program:

#include <stdio.h>
int main()
{
  return printf("Hello\n");
}

$ gcc -c t.c
$ gcc t.o -Wl,-y,printf
t.o: reference to printf
/lib/libc.so.6: definition of printf

This tells you that printf is referenced in t.o and defined in libc.so.6. Above solution will work for both static and shared libraries.

Since you tagged this question with gdb, here is what you can do in gdb:

gdb -q ./a.out
Reading symbols from /tmp/a.out...done.

(gdb) b main
Breakpoint 1 at 0x400528
(gdb) run

Breakpoint 1, 0x0000000000400528 in main ()
(gdb) info symbol &printf
printf in section .text of /lib/libc.so.6

If foo comes from a shared library, gdb will tell you which one. If it comes from a static library (in which case gdb will say in section .text of a.out), use the -Wl,-y,foo solution above. You could also do a "brute force" solution like this:

find / -name '*.a' -print0 | xargs -0 nm -A | grep ' foo$'
like image 92
Employed Russian Avatar answered Jan 18 '23 15:01

Employed Russian


For shared libs try using ldd command line tool.

For static libs the library is in the program itself - there are no external dependencies, which is the whole point of using static libs.

like image 21
pajton Avatar answered Jan 18 '23 17:01

pajton