5

I'm trying to compile a piece of code which uses libusb:

#include <stdio.h>
#include <libusb-1.0/libusb.h>
#include <assert.h>

int main(void) {
    libusb_context *context = NULL;
    int rc = 0;

    rc = libusb_init(&context);
    assert(rc == 0);

    libusb_exit(context);
    return 0;
}

Upon compiling with gcc -lusb -lusb-1.0 sample.c -o sample the following errors emerge:

/tmp/ccr65JBT.o: In function `main':
sample.c:(.text+0x2e): undefined reference to `libusb_init'
sample.c:(.text+0x62): undefined reference to `libusb_exit'
collect2: error: ld returned 1 exit status

To make sure libusb is availible on my system:

raven@enforcer:~/sample$ pkg-config --libs libusb-1.0
-lusb-1.0
raven@enforcer:~/sample$ pkg-config --libs libusb
-lusb

I'm running Ubuntu 18.04 with gcc 7.3.0-16ubuntu3, how to fix?

Henk Schurink
  • 419
  • 6
  • 17
  • 1
    try putting the libs after your .c file in the command line –  Jul 02 '18 at 10:54
  • 1
    Possible duplicate of [Why does the order in which libraries are linked sometimes cause errors in GCC?](https://stackoverflow.com/questions/45135/why-does-the-order-in-which-libraries-are-linked-sometimes-cause-errors-in-gcc) – Ctx Jul 02 '18 at 11:45
  • I have an answer to a similar question: https://stackoverflow.com/a/74634657/5432351 – gojimmypi Nov 30 '22 at 22:05

1 Answers1

5

Got it working by appending the flags after the .c: gcc sample.c -o sample -lusb -lusb-1.0

Autotools: sample_LDADD instead of sample_LDFLAGS

Thanks to Felix Palmen.

Henk Schurink
  • 419
  • 6
  • 17
  • 1
    rough explanation: a linker typically works by holding a list of unresolved symbols and looking to resolve them from the object files (or archives or libraries) it encounters later ... and GCC lets the linker process the object files in the order they appear on the initial command line. –  Jul 02 '18 at 11:23