Issue
I am attempting to use LibUSB in a project. However whenever I attempt to use basic libUSB functions I get the following error:
...src/main/main.cpp.o: In function `main':
...src/main/main.cpp:10: undefined reference to `libusb_init'
...src/main/main.cpp:11: undefined reference to `libusb_set_debug'
collect2: error: ld returned 1 exit status
The package LibUSB-devel is installed (I'm on fedora 22) and my IDE KDevelop finds and recognises the headers, to the point it offers LibUSB code completions once you have added the import statement. I don't have any custom include lines in either my IDE or CMake (my build system) so I would like to know what I need to to to make CMake find the LibUSB headers.
This is the contents of main.cpp
, just in case I messed something up:
#include <iostream>
#include <libusb-1.0/libusb.h>
int main(int argc, char **argv) {
libusb_init(NULL);
libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING);
/*snip*/
std::cout << "Hello, world! PTPID=" << std::endl;
return 0;
}
The following are the CMakeLists.txt
:
../
cmake_minimum_required(VERSION 2.8.11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(CMAKE_BUILD_TYPE Debug)
project(aProjectThatHasHadIt'sNameObcured)
add_subdirectory(src)
.../src/cmakelists.txt just adds subdirectories
.../src/main/
add_executable(main main.cpp)
Solution
From your projects CMakeLists.txt
file it doesn't become apparent to me how you've tried to link libusb. The way I would do is the following:
target_link_libraries(project_name <other_dependencies> usb-1.0)
(Just to clarify I mean the CMakeLIsts.txt file in which you add your executable)
You're trying to import from <libusb-1.0/...>
thus you need to link usb-1.0 (the lib is always omitted from linker commands!)
I'm on Fedora 23, also using KDevelop and I didn't have to specify a path. Especially because on my system all the environment variables used in the previous answer are NULL anyways.
And to confirm where and how a library is installed in the future you can just do:
locate libusb | grep .so
Hope this was somewhat helpful.
Answered By - AreusAstarte Answer Checked By - Katrina (WPSolving Volunteer)