1

I'm specifying an -l 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 libusb_init exists 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 gcc command with an -L option:

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 gcc command.)

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

LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/5/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/5/../../../:/lib/:/usr/lib/

...which does not include the directory I specified with -L. (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 -l option. (Maybe this isn't a valid concern, since the next line does include the -l option.) Any thoughts?

running Ubuntu 16

JellicleCat
  • 28,480
  • 24
  • 109
  • 162

1 Answers1

3

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?

Community
  • 1
  • 1
David
  • 1,624
  • 11
  • 13