What's the preferred way to include a library

2019-07-24 19:20发布

问题:

I've built the libfreenect2 library, now I want to include it in my c++ project. Before, I've included some libraries with cmake like this:

# Include OpenCV
find_package( OpenCV REQUIRED )
target_link_libraries( ${PROJECT_NAME} ${OpenCV_LIBS} )

This means that the library has to be properly "installed" to my system for cmake to find it, correct?

However, this time I need to "manually" include the necessary files and directories to my project. But I don't have a clue on how the "correct" way to do it.

Been following this tutorial, but it's confusing how I have to add library, include directories, add subdirectories (why is it suddenly "add" and not "include"), link libraries... Is the terminology inconsistent, or is the approach always really this messy? I can't see why it wouldn't be enough to just express the library directory ONCE then cmake should figure out what to do with it? Sorry about my ignorance.

Anyways, what's the preferred steps to include a customly built library?

This is my current attempt, which (when I try to compile my project) yields "cannot find -lfreenect2"

project(kinect-test)
cmake_minimum_required(VERSION 2.8)
aux_source_directory(. SRC_LIST)

add_executable(${PROJECT_NAME} ${SRC_LIST})

# Include directories
include_directories ($ENV{HOME}/freenect2/include)

# Find freenect package
set(freenect2_DIR $ENV{HOME}/freenect2/lib/cmake/freenect2)
find_package(freenect2 REQUIRED)
target_link_libraries (${PROJECT_NAME} freenect2)

回答1:

You need to specify a search path that can find the given library. I assume the file libfreenect.so (or libfreenect.a) is located in /path/to/freenect - please edit as appropriate, possibly using a variable. Above your target_link_libraries command add the command:

link_directories(/path/to/freenect)


回答2:

This is what I ended up doing:

  • Set cmake prefix to enable it to find the config file (named "freenect2Config.cmake")
  • "Find" the "package", which makes cmake run the "find script"
  • Include directories to get headers
  • Link library files

CMakeLists.txt

project(kinect-test)
cmake_minimum_required(VERSION 2.8)
aux_source_directory(. SRC_LIST)

add_executable(${PROJECT_NAME} ${SRC_LIST})

# Set cmake prefix path to enable cmake to find freenect2
set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} $ENV{HOME}/freenect2/lib/cmake/freenect2)

# Find freenect, to set necessary variables
find_package(freenect2 REQUIRED)

# Include directories to get freenect headers
include_directories($ENV{HOME}/freenect2/include)

# Link freenect libraries with the project
target_link_libraries(${PROJECT_NAME} ${freenect2_LIBRARIES})


标签: c++ cmake