How can I find out what linker flags are needed to use a given C library function?

The question is how to determine what linker flag to use from inspection of the source file. The example below will work for Debian. The header files are the relevant items to note here.

So, suppose one has a C source file containing the header

#include <X11/extensions/XInput.h>.

We can do a search for XInput.h using, say apt-file. If you know this header file is contained in an installed package, dpkg -S or dlocate will also work. E.g.

apt-file search XInput.h
libxi-dev: /usr/include/X11/extensions/XInput.h

That tells you that this header file belongs to the development package for libxi (for C libraries, the development packages (normally of the form libname-dev or libname-devel) contain the header files), and therefore you should use the -lxi linker flag.

Similar methods should work for any distribution with a package management system.


Here's a community wiki to collect other distros' equivalent tools for Faheem's method. Feel free to edit, but keep the sort alphabetical for searching.

Arch

Use pkgfile from the extra repository, passing the header file name as a parameter.

Example:

$ pkgfile XInput.h
extra/libxi
extra/nx-headers

Debian

(and anything Debian-based using dpkg)

apt-file search for the header file name, as covered.

Gentoo

As covered in another question by warl0ck, use the pfl package's e-file program, or alternatively, the web-based Portage File List search.

Tags:

C

Ld

Compiling