编辑:从 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 不支持 PackageReference 用于纯 C++ 项目。
在 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 依赖项。
要将依赖项绑定到特定目标,您(很遗憾)必须使用 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 包。这是 CPack Nuget 生成器的documentation。