Torito
Torito

Reputation: 315

In what file a C function is defined?

Let's say I want to call a C function: printf, getpid, socketpair or any other standard C function from my code in Assembly language. I know how to do that in terms of implementation. However, I'll also have to know where one of those functions defined -- in what Linux file, so that I can pass the name of that of that file to the linker. I think it should be a "so" file. How would I find out in what file it's defined?

Note that my question is general and the functions I've mentioned above are just an example. How would I know in what Linux library any arbitrary C function defined?

Upvotes: 1

Views: 70

Answers (2)

Useless
Useless

Reputation: 67703

If it's a standard C library function, libc.so is probably correct.

If it's another library, that library's documentation should tell you. Eg. the manpage for pthread_create says

Compile and link with -pthread

and you then need to look at the GCC documentation to see what it does with that option (eg, -lpthread plus some other stuff, so you want libpthread.so).

With third-party libraries, the onus is entirely on the library developer/distributor to tell you where to find the symbols listed in their API.

Worst case you can just find all .so files under /usr, /lib, /opt or wherever else you have libraries installed, and run nm -D on them. You're looking for entries of type t or T.

Note we're assuming that you only want shared objects (dynamic libraries) - if you're talking about arbitrary third-party libraries, they could equally ship static (.a) archives.

Upvotes: 1

Petr Skocik
Petr Skocik

Reputation: 60056

These (printf, getpid, socketpair) are all part of the standard C library. That's the library that gets automatically linked to every C program.

I think the easiest way to solve your problem would be to link it with gcc, which will call the linker and link the appropriate version of the standard C library in.

If you want to proceed your way:

echo 'int main(){ }' |gcc -x c - && ldd ./a.out |grep libc

should give you the so file. In my case it's:

libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fc3a2b46000)

There's no generic solution for function x as far as I know. You'd have to google to map a function to a library. If the library uses a library specific prefix instead of bare names (like the standard C library unfortunately does in most cases), googling it should be fairly unambiguous. (After that, you'd need to find where the library's SO file is on your system.)

Upvotes: 2

Related Questions