How to Link a third Party Library (LibUSB) in CMake

前端 未结 2 1498
臣服心动
臣服心动 2020-12-20 00:58

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 f         


        
2条回答
  •  失恋的感觉
    2020-12-20 01:27

    In general, to link a third party library, you need to add the include directory where the compiler will look for the headers, and the libraries which are used by the linker.
    To add include directories use target_include_directories, to add a library to be linked to a target use target_link_libraries.
    For libUSB and a testLibUSB.cpp source file this would result in

    add_executable(targetTestLibUSB testLibUSB.cpp)
    target_include_directories(targetTestLibUSB ${LIBUSB_INCLUDE_DIR})
    target_link_libraries(targetTestLibUSB ${LIBUSB_LIBRARY})
    

    If you have several targets, you might want to use include_directories and link_libraries before defining any target. These commands apply to all targets of a project after they are set and save a lot of repetition

    You can specify the paths for LIBUSB_INCLUDE_DIR and LIBUSB_LIBRARY by hand. But more flexible and portable is to use CMake built-in mechanisms to find headers and libraries.
    Header can be searched by find_path and libraries by find_library.
    in your case this could be

    find_path(LIBUSB_INCLUDE_DIR
      NAMES libusb.h
      PATH_SUFFIXES "include" "libusb" "libusb-1.0")
    find_library(LIBUSB_LIBRARY
      NAMES usb
      PATH_SUFFIXES "lib" "lib32" "lib64")
    

    The PATH_SUFFIXES are optional. If you have installed the library in a default location, CMake will find it automatically. Otherwise specify CMAKE_PREFIX_PATH and CMake will look for the headers and libraries there, too. You can specify the variable either by adding it in the CMake GUI or adding -DCMAKE_PREFIX_PATH=/path/to/add to your CMake call.

    A common pitfall is to not delete the CMakeCache.txt file in the build directory. CMake caches the values for LIBUSB_INCLUDE_DIR and LIBUSB_LIBRARY and if you makes adjustment to the prefix path or your search logic, it still does not reevaluate the variable values but sticks to the cached values.

提交回复
热议问题