JellicleCat JellicleCat - 11 months ago 81
C Question

gcc Linker error despite specifying -l flag for libusb-1.0

I'm specifying an

flag for my library, so can anyone help me understand why I receive this error for this command?

$ gcc `pkg-config --libs --cflags libusb-1.0` sourcefile.c
/tmp/cclBFhzY.o: In function `main':
sourcefile.c:(.text+0x57): undefined reference to `libusb_init'

pkg-config --libs --cflags libusb-1.0
evaluates to
-I/usr/include/libusb-1.0 -lusb-1.0

I have verified that
in the library:

$ nm /usr/lib/x86_64-linux-gnu/libusb-1.0.a | grep libusb_init
0000000000001a60 T libusb_init

I've furthermore even tried my
command with an

gcc -I/usr/include/libusb-1.0 -L/usr/lib/x86_64-linux-gnu -lusb-1.0 sourcefile.c

Still I get the linker error. Do you see anything I'm doing wrong?

(I've read several other threads on undefined reference errors, but the answers have all been the obvious answer: specify your library in your

Oddly, I can't tell if gcc is processing my options. When I run it with the
flag, two salient lines are:


...which does not include the directory I specified with
. (But it appears that the first entry in the path is equivalent to my dir.) And:

COLLECT_GCC_OPTIONS='-v' '-I' '/usr/include/libusb-1.0' '-L/usr/lib/x86_64-linux-gnu' '-mtune=generic' '-march=x86-64'

...which does not include my
option. (Maybe this isn't a valid concern, since the next line does include the
option.) Any thoughts?

running Ubuntu 16

Answer Source

Move sourcefile.c before the linker options.

The linker moves through libraries and source files from left to right, noting unresolved symbols as it goes. When it gets to a library (such as -lusb-1.0) the linker goes through and resolves any symbols it can find at that moment.

Your libraries aren't being applied to sourcefile.c

See also:

Why does the order in which libraries are linked sometimes cause errors in GCC?