【问题标题】:How to include Vcpkg on CMakeLists.txt?如何在 CMakeLists.txt 中包含 Vcpkg?
【发布时间】:2022-07-14 01:07:43
【问题描述】:

所以我有一个依赖于opencv的项目,它是用vcpkg安装的。该项目是使用 cmake 构建的。

CMakeLists.txt

cmake_minimum_required(VERSION 3.19.1)

set(CMAKE_TOOLCHAIN_FILE ~/vcpkg/scripts/buildsystems/vcpkg.cmake)

project(mylib)

set (CMAKE_CXX_STANDARD 14)

find_package(OpenCV REQUIRED)

include_directories(~/vcpkg/installed/x64-osx/include)

link_libraries(${OpenCV_LIBS})

set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE)

add_library(mylib SHARED mylib another_lib)

可以看出,我正在尝试使用相同的CMakeLists.txt 在 macOS 和 Windows 上构建它。

link_libraries(${OpenCV_LIBS}) 可以很好地在不同操作系统之间转换。

但是include_directories(~/vcpkg/installed/x64-osx/include) 仅适用于macOS,在Windows 上它应该引用C:/vcpkg/installed/x64-windows/include

有没有什么 opecv/vcpkg 可以用来代替这些?

【问题讨论】:

    标签: c++ windows macos cmake vcpkg


    【解决方案1】:

    这个include_directories(~/vcpkg/installed/x64-osx/include) 看起来很奇怪。这应该是:

    include_directories(${OpenCV_INCLUDE_DIRS})
    

    【讨论】:

      【解决方案2】:

      可以在manifest模式下使用vcpkghttps://vcpkg.readthedocs.io/en/latest/users/manifests/

      通过这种方式,您可以创建一个 JSON 文件列出所有依赖项,并且在调用 cmake 时,vcpkg 将自动引导并安装所有依赖项。

      【讨论】:

        【解决方案3】:

        include_directorieslink_libraries 是旧式 cmake,应该避免使用。应该改用target_link_libraries

        也不建议使用特定于您我们系统的路径。 配置项目时应提供CMAKE_TOOLCHAIN_FILE值。

        IMO 应该是这样的:

        cmake_minimum_required(VERSION 3.19.1)
        
        # this way others can override this value form command line
        set(CMAKE_TOOLCHAIN_FILE ~/vcpkg/scripts/buildsystems/vcpkg.cmake CACHE FILEPATH "Path to toolchain")
        
        project(mylib)
        find_package(OpenCV REQUIRED)
        
        set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS TRUE)
        
        add_library(mylib SHARED mylib another_lib)
        
        # this should resolve problems with include and linking at the same time
        # and only yor target will be impacted (and targets linking your target 
        # since PUBLIC is used)
        target_link_libraries(mylib PUBLIC ${OpenCV_LIBS})
        

        【讨论】:

          最近更新 更多