I am running c/c++ on Ubuntu and trying to compile the following code
#include <cassert>
#include <cstdio>
#include <libusb-1.0/libusb.h>
int main() {
libusb_context *context = NULL;
libusb_device **list = NULL;
int rc = 0;
ssize_t count = 0;
rc = libusb_init(&context);
assert(rc == 0);
count = libusb_get_device_list(context, &list);
assert(count > 0);
for (size_t idx = 0; idx < count; ++idx) {
libusb_device *device = list[idx];
libusb_device_descriptor desc = {0};
rc = libusb_get_device_descriptor(device, &desc);
assert(rc == 0);
printf("Vendor:Device = %04x:%04x\n", desc.idVendor, desc.idProduct);
}
}
I get the following error when after I compile my code. Don't have any idea what should I do?
/tmp/ccESLZ0k.o: In function `main':
libusbtest.cpp:(.text+0x2f): undefined reference to `libusb_init'
libusbtest.cpp:(.text+0x64): undefined reference to `libusb_get_device_list'
libusbtest.cpp:(.text+0xd4): undefined reference to `libusb_get_device_descriptor'
collect2: ld returned 1 exit status
I am a novice user of Ubuntu, c/c++ and libusb, so any help would be appreciated
Thanks
This is a linker error.
You need to tell the linker to include libusb
, which contains these referenced functions (eg -lusb
) and also where it is (eg -L/usr/local/lib
). Actual values will depend on your installation.
As Avidanborisov's answer highlights, you can use the pkg-config tool to determine the linker flags. On my system this looks like:
% pkg-config --libs libusb-1.0
-L/usr/local/Cellar/libusb/1.0.9/lib -lusb-1.0
You can feed this information directly to gcc :
% g++ libusbtest.cpp $(pkg-config --libs libusb-1.0) -o libusbtest
Assuming all goes according to plan, you should now have an executable file libusbtest
in your current working directory. You can run it like this:
% ./libusbtest
Vendor:Device = 05ac:8006
Vendor:Device = 05ac:8006
Vendor:Device = 05ac:8005
Vendor:Device = 05ac:8005
Vendor:Device = 05ac:850a
Vendor:Device = 05ac:023f
Vendor:Device = 05ac:8403
使用pkg-config
获取该库所需的编译器标志:
g++ libusbtest.cpp `pkg-config --libs libusb` -o libusbtest
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.