VS2019 C++跨平台程序中包含nuget包

Jas*_*son 5 c++ linux windows cmake nuget

我的任务是开始使用 CMake 布置 C++ 跨平台程序。我们的主要依赖项之一涉及内部 nuget 包。对于我们的 Windows C++ 项目,我只需右键单击该项目并选择Manage Nuget Packages。在跨平台中,没有这样的选项,我正在努力寻找有关如何包含这些依赖项的任何相关信息。任何人都可以将我链接到任何好的信息来源或演示吗?

squ*_*les 5

编辑:从 CMake 3.15 开始,CMake 支持使用VS_PACKAGE_REFERENCES. 现在,这是一个比下面提出的解决方法简洁的解决方案。要将 Nuget 包引用添加到 CMake 目标,请使用由下划线分隔的包名称和包版本_;这是BouncyCastle1.8.5 版的示例:

set_property(TARGET MyApplication
    PROPERTY VS_PACKAGE_REFERENCES "BouncyCastle_1.8.5"
)
Run Code Online (Sandbox Code Playgroud)

在 CMake 3.15 之前,CMake 没有支持 Nuget 的内置命令,因此您必须使用nuget 命令行实用程序来包含使用 CMake 的 Nuget 依赖项。

您可以使用 CMakefind_program()来定位nuget命令行实用程序(安装后),与CMake结合使用add_custom_command()execute_process()执行nuget来自 CMake 的命令。这个问题的答案更详细地讨论,但它本质上可能是这样的:

# Find Nuget (install the latest CLI here: https://www.nuget.org/downloads).
find_program(NUGET nuget)
if(NOT NUGET)
    message(FATAL "CMake could not find the nuget command line tool. Please install it!")
else()
    # Copy the Nuget config file from source location to the CMake build directory.
    configure_file(packages.config.in packages.config COPYONLY)
    # Run Nuget using the .config file to install any missing dependencies to the build directory.
    execute_process(COMMAND 
        ${NUGET} restore packages.config -SolutionDirectory ${CMAKE_BINARY_DIR}
        WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
    )
endif()
Run Code Online (Sandbox Code Playgroud)

这假设您有一个现有packages.config文件,其中列出了项目的 nuget 依赖项。

要将依赖项绑定到特定目标,您(不幸的是)必须使用nuget放置程序集/库的完整路径。

对于 .NET nuget 包,这看起来像这样:

# Provide the path to the Nuget-installed references.
set_property(TARGET MyTarget PROPERTY 
    VS_DOTNET_REFERENCE_MyReferenceLib
    ${CMAKE_BINARY_DIR}/packages/path/to/nuget/lib/MyReferenceLib.dll
)
Run Code Online (Sandbox Code Playgroud)

对于 C++ 风格的 nuget 包,它可能如下所示:

add_library(MyLibrary PUBLIC
    MySource.cpp
    MyClass1.cpp
    ...
)

# Provide the path to the Nuget-installed libraries.
target_link_libraries(MyLibrary PUBLIC 
    ${CMAKE_BINARY_DIR}/packages/path/to/nuget/lib/MyCppLib.dll
)
Run Code Online (Sandbox Code Playgroud)

顺便说一句,CMake确实支持使用 CPack创建Nuget 包。这是CPack Nuget 生成器的文档