0

I have a single main.cpp file with this content:

#include <iostream>
#include <hidapi/hidapi.h>
#define MAX_STR 255

using namespace std;

int main (void) {
    int res;
    unsigned char buf[65];
    wchar_t wstr[MAX_STR];
    hid_device *handle;
    int i;
    
    cout << "Hello\n";
    
    res = hid_init();
    handle = hid_open(0xC251, 0x2201, NULL);
    
    return 0;
}

where hidapi was installed following the instructions for Ubuntu 20.04, i.e. sudo apt install libhidapi-dev. Now I want to compile this with

g++ main.cpp -o main

but I get main.cpp:(.text+0x32): undefined reference to `hid_init'. How am I supposed to make this work? (Note that I had to write #include <hidapi/hidapi.h> instead of #include <hidapi.h> because otherwise it would complain about this also, not sure if this is related with the current issue.)

user171780
  • 2,243
  • 1
  • 20
  • 43
  • You forgot to link with the library. – πάντα ῥεῖ Dec 15 '21 at 17:51
  • How is that done? I have tried with `g++ main.cpp -o main -lhidapi`, `g++ main.cpp -o main -lhidapi/hidapi`, `g++ main.cpp -o main -lhidapi -Lhidapi`, `g++ main.cpp -o main -lhidapi -Lhidapi/hidapi` but don't work. – user171780 Dec 15 '21 at 18:03
  • Find the path, where `libhdiapi.lib` is located afterinstallation and build, and configure that additionally with the `-L` option. – πάντα ῥεῖ Dec 15 '21 at 18:03
  • I am in Linux, not an expert but I think that `.lib` is for Windows. I have found some `/usr/lib/x86_64-linux-gnu/libhidapi-hidraw.so` but when I add this path with `-L` it still fails. For example `g++ main.cpp -o main -lhidapi-hidraw.so -L/usr/lib/x86_64-linux-gnu/`. I have tried several combinations of `-l` and `-L`. Is it correct having to hardcode the path for each library you include in a C++ program? Isn't there something like Python that you just `import bla` and it works out of the box? – user171780 Dec 15 '21 at 18:16
  • 2
    `"...it still fails"` is not a very useful description of the problem. Please edit your question to show both the compile/build command you invoke and the error messages verbatim. Note that if the symbol you're looking for is in `libhidapi-hidraw.so` then the linker option should probably be `-lhidapi-hidraw` rather than `-lhidapi-hidraw.so` . – G.M. Dec 15 '21 at 18:53
  • Then try finding `libhidapi.a`, which is the appropriate stubs, you shouldlink with. And no, there isn't something "simple" like `import` unless you use c++20 ready APIs. – πάντα ῥεῖ Dec 15 '21 at 18:54
  • Thank you very much for your comments. I replaced `-lhidapi-hidraw.so` by `-lhidapi-hidraw` and now it compiled. – user171780 Dec 15 '21 at 18:58

0 Answers0