Running example C code is a painful exercise unless it comes with a makefile.
I often find myself with a C file containing code that supposedly does something very cool, but for which a first basic attempt at compilation (gcc main.c
) fails with—
main.c:(.text+0x1f): undefined reference to `XListInputDevices'
clang-3.7: error: linker command failed with exit code 1 (use -v to see invocation)
—or similar.
I know this means I'm missing the right linker flags, like -lX11
, -lXext
or -lpthread
.
But which ones?
The way I currently deal with this is to find the library header that a function was included from, use Github's search to find some other program that imports that same header, open its makefile, find the linker flags, copy them onto my compilation command, and keep deleting flags until I find a minimal set that still compiles.
This is inefficient, boring, and makes me feel like there must be a better way.
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments