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

标签 c++ linux windows cmake nuget

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

最佳答案

编辑:自 CMake 3.15 起,CMake 支持使用 VS_PACKAGE_REFERENCES 引用 Nuget 包.现在,这是一个比下面提议的变通方法更简洁的解决方案。要将 Nuget 包引用添加到 CMake 目标,请使用下划线 _ 分隔的包名称和包版本;这是 BouncyCaSTLe 版本 1.8.5 的示例:

set_property(TARGET MyApplication
    PROPERTY VS_PACKAGE_REFERENCES "BouncyCastle_1.8.5"
)

请注意,此解决方案仅适用于 C# 或混合 C#/C++ 项目。如前所述 here , Microsoft 不支持纯 C++ 项目的 PackageReference


在 CMake 3.15 之前,CMake 没有支持 Nuget 的内置命令,因此您必须使用 nuget command line utilities使用 CMake 包含 Nuget 依赖项。

您可以使用 CMake 的 find_program()找到 nuget 命令行实用程序(一旦安装),加上 add_custom_command()execute_process()从 CMake 执行 nuget 命令。 question 的答案更详细地讨论,但它基本上看起来像这样:

# 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()

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

要将依赖关系绑定(bind)到特定目标,您(不幸的是)必须使用 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
)

对于 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
)

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

关于c++ - 在VS2019 C++跨平台程序中包含nuget包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58488575/

相关文章:

c++ - 从 CSV 创建字符串数组

c++ - 为什么 strtol 和 strtok 的这种组合不起作用?

python - 用Nuitka编译任何Python程序后,我得到 “is not a valid win32 application”错误

linux - 如何使用管道命令显示文件中的属性?

linux - 带有 expect 模块的 scp 不工作

python - OpenSSH 公钥不适用于 Cygwin

c++ - 如何在 C++ 中将 PWSTR 转换为字符串?

Python初学者——如何自定义输出窗口

c++ - 使用 C++ 迭代器从文件中读取列表?

linux - 这些获取资源使用情况的方法有什么区别?