gcc: Solving “undefined reference” even when the required library is listed with -l

This post was written by eli on April 19, 2017
Posted Under: Linux,Software

It worked all so nicely on my Fedora 12 machine, and then on Ubuntu 14.04.1 it failed colossally:

$ make
gcc -Wall  -O3 -g -lusb-1.0 -c  -o bulkread.o bulkread.c
gcc -Wall  -O3 -g -lusb-1.0 -c  -o usberrors.o usberrors.c
gcc -Wall  -O3 -g -lusb-1.0 bulkread.o usberrors.o -o bulkread
bulkread.o: In function `main':
bulkread.c:39: undefined reference to `libusb_init'
bulkread.c:46: undefined reference to `libusb_set_debug'
bulkread.c:48: undefined reference to `libusb_open_device_with_vid_pid'
[ ... ]

And it went on and on. Note that there was no complaint about not finding the library, and yet it failed to find the symbols.

The problem was the position of the -l flag. It turns out that Ubuntu silently adds an –as-needed flag to the linker, which effectively means that the -l flag must appear after the object file that needs the symbols, or it will be effectively ignored.

So the correct way is:

$ make
gcc -Wall  -O3 -g -c  -o bulkread.o bulkread.c
gcc -Wall  -O3 -g -c  -o usberrors.o usberrors.c
gcc -Wall  -O3 -g bulkread.o usberrors.o -o bulkread -lusb-1.0

It’s all about the flag’s position…

Add a Comment

required, use real name
required, will not be published
optional, your blog address