使用 OpenCV 的 CMake 模块目标而不是直接包含所有库?

Using OpenCV's CMake module targets instead of including all libraries directly?

问题:我有一个使用 OpenCV 的项目。如果需要,我可以切换到最新版本。我的项目使用 CMake。我目前像这样集成 opencv:

# OPENCV package
find_package(OpenCV)
add_library(opencv INTERFACE)
target_include_directories(opencv
        INTERFACE
        ${OpenCV_INCLUDE_DIRS})
target_link_libraries(opencv
        INTERFACE
        ${OpenCV_LIBS})

add_executable(opencv_example example.cpp)

target_link_libraries(opencv_example 
    PRIVATE 
        opencv
)

我找不到使用显式模块依赖目标的 OpenCV 示例。为了不使全局包含不必要地混乱或留下裸露的变量。我为 OpenCV 创建了一个接口目标并使用这个接口目标而不是做 OpenCV CMake example recommends:

# Find OpenCV, you may need to set OpenCV_DIR variable
# to the absolute path to the directory containing OpenCVConfig.cmake file
# via the command line or GUI
find_package(OpenCV REQUIRED)

# Declare the executable target built from your sources
add_executable(opencv_example example.cpp)

# Link your application with OpenCV libraries
target_link_libraries(opencv_example ${OpenCV_LIBS})

我的问题是,是否可以只使用 OpenCV 的模块目标,而不必携带整个厨房水槽?

示例(参见模块列表 here):

...

add_executable(opencv_example example.cpp)

target_link_libraries(opencv_example 
    PRIVATE
        opencv::core 
        opencv::video
        opencv::imgproc
)

因此我只获得了我实际使用的模块所需的依赖项。我查看了 OpenCV 存储库,但它充满了自定义的 cmake 宏和函数,很难看出目标的声明位置,更不用说是否可以从 find_package.

访问它了

虽然 opencv::module 不起作用,但如果您使用 find_package,最多从 OpenCV3.2 开始(它可能以前可用),您可以使用像 opencv_module 这样的目标例如:

find_package(OpenCV REQUIRED COMPONENTS core imgproc video)

add_executable(opencv_example example.cpp)

target_link_libraries(opencv_example 
    PRIVATE
        opencv_core 
        opencv_video
        opencv_imgproc
)

我发现这些目标是在这里导出的:https://github.com/opencv/opencv/issues/8028#issuecomment-273419374