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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…