本指南为开发人员提供了使用 vcpkg 从 Azure SDK 为 C++ 安装库,并通过 CMake 将其集成到项目中的必要步骤。 按照说明作,可以设置开发环境并开始在C++应用程序中使用 Azure 服务。 无论你是 Azure 新手还是希望简化集成过程,本文档都有助于快速高效地入门。
先决条件
验证 git 和 CMake 安装
为了确保顺利集成过程,请务必验证是否已正确安装 git 和 CMake。
若要验证 git 是否已正确安装,请在终端中运行以下命令:
git --version
应获得一个输出,该输出表示当前安装的 git 版本,如下所示:
git version <version>
若要验证 CMake 是否已正确安装,请在终端中运行以下命令:
cmake --version
应获得表示当前安装的 CMake 版本的输出,如下所示:
cmake version <version>
安装 vcpkg
若要管理和安装用于C++库的 Azure SDK,请使用 vcpkg。 vcpkg 是一个跨平台包管理器,可简化处理依赖项的过程。
若要安装 vcpkg,请先克隆 vcpkg 存储库。 建议的方法是将 vcpkg 克隆到开发环境中的中心位置,而不是在C++项目目录中。 在此示例中,vcpkg 克隆到 home dir。
cd ~ git clone https://github.com/microsoft/vcpkg.git
克隆 vcpkg 存储库后,遍历到新目录并运行
bootstrap-vcpkg.bat
脚本。cd .\vcpkg\ .\bootstrap-vcpkg.bat
启动 vcpkg 后,将其添加到路径,以便可以从项目目录访问 vcpkg 可执行文件。 请记住,将
<path\to\vcpkg>
命令示例中的路径替换为之前克隆的 vcpkg 目录的路径。$env:Path = "$env:Path;<path\to\vcpkg>"
若要验证 vcpkg 目录是否已添加到路径,请遍历回项目目录并运行以下命令:
vcpkg --version
应会收到以下输出:
vcpkg package management program version <version>
安装库
本部分指导你通过 vcpkg 使用 Azure SDK 安装必要的 C++ 库的过程。 本部分介绍如何在清单模式下使用 vcpkg,这将创建几个 vcpkg 项目文件,以帮助管理项目的依赖项,即使与其他协作者共享也是如此。
在项目的根目录中运行以下命令,在清单模式下启动新的 vcpkg 项目:
vcpkg new --application
现在,项目目录中应有 一个vcpkg.json 文件和一个 vcpkg-configuration.json 文件。
现在,可以通过运行以下命令,将 Azure SDK for C++ 中的 Azure Key Vault 和标识库添加到项目中:
vcpkg add port azure-identity-cpp azure-security-keyvault-secrets-cpp
vcpkg.json 文件现在应包含以下内容:
{ "dependencies": [ "azure-identity-cpp", "azure-security-keyvault-secrets-cpp" ] }
创建 Azure 密钥保管库资源
本部分讨论如何使用 Azure CLI 创建 Azure Key Vault 资源。 此 Key Vault 资源安全地存储和管理敏感信息,例如机密和密钥。
在终端中输入以下命令,使用 Azure CLI 登录:
az login
使用弹出窗口登录到 Azure。
使用弹出窗口登录后,选择要在终端中使用的 Azure 订阅。
然后使用以下命令创建 Key Vault 资源,并记住要用自己的唯一名称替换
<your-resource-group-name>
和<your-key-vault-name>
:az keyvault create --resource-group <your-resource-group-name> --name <your-key-vault-name>
在输出中,应会看到具有
vaultUri
属性的属性列表。 使用以下命令将它设置为要用于程序中的环境变量:$env:AZURE_KEYVAULT_URL = "https://<your-key-vault-name>.vault.azure.net/"
- 最后,请确保 Azure 帐户具有使用 Key Vault 机密的适当权限。 可以通过在 Azure 门户中 Key Vault 资源的访问控制(IAM)页上分配“Key Vault 机密官员”角色来为自己提供适当的权限。 IAM 代表标识和访问管理。
设置你的项目
本部分介绍创建必要的文件夹和文件以设置 Azure C++ 项目的过程。
在项目目录的根目录中,创建 CMakeLists.txt 文件。 此文件用于配置 CMake 项目。 将以下代码添加到 CMakeLists.txt 文件:
# Specify the minimum version of CMake required to build this project cmake_minimum_required(VERSION 3.30.0) # Set the path to the vcpkg toolchain file # Remember to replace the path below with the path where you cloned vcpkg set(CMAKE_TOOLCHAIN_FILE "/path/to/vcpkg-root/scripts/buildsystems/vcpkg.cmake") # Define the project name, version, and the languages used project(azure_sample VERSION 0.1.0 LANGUAGES C CXX) # Find and include the azure-identity-cpp package find_package(azure-identity-cpp CONFIG REQUIRED) # Find and include the azure-security-keyvault-secrets-cpp package find_package(azure-security-keyvault-secrets-cpp CONFIG REQUIRED) # Add an executable target named 'azure_sample' built from the main.cpp source file add_executable(azure_sample main.cpp) # Link the azure-identity and azure-security-keyvault-secrets # libraries to the azure_sample target target_link_libraries(azure_sample PRIVATE Azure::azure-identity Azure::azure-security-keyvault-secrets )
在项目目录的根目录中,创建 main.cpp 文件。 将以下代码添加到 main.cpp 文件:
#include <azure/identity.hpp> #include <azure/keyvault/secrets.hpp> #include <iostream> using namespace Azure::Security::KeyVault::Secrets; int main() { try { // Set Key Vault URL string auto const keyVaultUrl = std::getenv("AZURE_KEYVAULT_URL"); // Create Default Azure Credential to Authenticate. // It will pick up on our AzureCLI login auto credential = std::make_shared<Azure::Identity::DefaultAzureCredential>(); // Create Key Vault Secret Client SecretClient secretClient(keyVaultUrl, credential); // Create a Secret std::string secretName("MySampleSecret"); std::string secretValue("My super secret value"); secretClient.SetSecret(secretName, secretValue); // Get the Secret KeyVaultSecret secret = secretClient.GetSecret(secretName).Value; std::string valueString = secret.Value.HasValue() ? secret.Value.Value() : "NONE RETURNED"; std::cout << "Secret is returned with name " << secret.Name << " and value " << valueString << std::endl; } catch (Azure::Core::Credentials::AuthenticationException const &e) { std::cout << "Authentication Exception happened:" << std::endl << e.what() << std::endl; return 1; } catch (Azure::Core::RequestFailedException const &e) { std::cout << "Key Vault Secret Client Exception happened:" << std::endl << e.Message << std::endl; return 1; } return 0; }
为构建产物创建 build 目录。
生成并运行
本部分讨论如何使用 CMake 命令配置和生成项目,然后运行程序以确保正确设置所有内容。 本部分中的命令应从项目的根目录运行,其中build
目录、CMakeLists.txt
和main.cpp
文件所在。
若要配置 CMake,请输入以下命令:
cmake -B ./build
若要生成项目,请输入以下命令:
cmake --build ./build
若要运行程序,请输入以下命令:
.\build\Debug\azure_sample.exe
程序应具有以下输出:
Secret is returned with name MySampleSecret and value My super secret value
故障排除
找不到资源组
使用 AzureCLI 创建 Key Vault 实例时,如果收到以下错误,则尝试将 Key Vault 实例添加到的资源组不存在。
(ResourceGroupNotFound) Resource group '<your-resource-group-name>' could not be found.
Code: ResourceGroupNotFound
Message: Resource group '<your-resource-group-name>' could not be found.
若要创建资源组,可以使用以下命令:
az group create --name <your-resource-group-name> --___location <your-resource-group-___location>
有关详细信息,请查看 有关管理 Azure 资源组的 AzureCLI 文档。
CMake 配置或生成找不到 Azure 包
运行 CMake 配置或生成命令时,如果收到以下错误或类似内容,则 CMakeLists.txt
文件未在建立 CMake 项目之前或根本不运行 vcpkg.cmake
模块。
CMake Error at CMakeLists.txt:12 (find_package):
Could not find a package configuration file provided by
"azure-identity-cpp" with any of the following names:
azure-identity-cppConfig.cmake
azure-identity-cpp-config.cmake
Add the installation prefix of "azure-identity-cpp" to CMAKE_PREFIX_PATH or
set "azure-identity-cpp_DIR" to a directory containing one of the above
files. If "azure-identity-cpp" provides a separate development package or
SDK, be sure it has been installed.
在 CMakeLists.txt 文件中验证行 set(CMAKE_TOOLCHAIN_FILE "/path/to/vcpkg-root/scripts/buildsystems/vcpkg.cmake")
是否位于上面 project(azure_sample VERSION 0.1.0 LANGUAGES C CXX)
。
然后,还要验证在set(CMAKE_TOOLCHAIN_FILE "/path/to/vcpkg-root/scripts/buildsystems/vcpkg.cmake")
行中的/path/to/vcpkg-root/
是否已更新为 vcpkg 安装的位置。
cmake 代码中的语法错误
运行 CMake 配置或生成命令时,如果收到以下错误, CMakeLists.txt 文件可能包含使用 \
的路径。 使用窗口的路径时,此问题可能很常见。
Syntax error in cmake code at
C:/Users/username/Desktop/CppProject/CMakeLists.txt:6
when parsing string
C:\Users\username\vcpkg\scripts\buildsystems\vcpkg.cmake
Invalid character escape '\U'.
尽管 Windows 在文件路径中使用\
,但 CMake 仅在文件路径中使用/
。 可以通过在 CMakeLists.txt 文件中将所有路径中的 \
替换为 /
来解决该问题。
如果在进行更改后错误仍然存在,请参阅 更改后 CMake 错误仍然存在 部分,了解如何解决这些问题。
进行更改后,CMake 错误仍然存在
运行 CMake configure 命令时,如果在进行更改以修复它后继续收到相同的错误,请尝试清除 CMake 缓存。 可以通过删除 生成 目录的内容来清除 CMake 缓存,然后重新运行 CMake 配置命令。
CMake 3.30 或更高版本是必需的
运行 CMake configure 命令时,如果收到如下所示的错误,则可能需要更新 CMake 版本。
CMake Error at CMakeLists.txt:2 (cmake_minimum_required):
CMake 3.30.0 or higher is required. You are running version 3.25.0
若要解决此错误,请将 CMake 的安装更新为错误消息中所述的版本。
调用方无权对资源执行操作
运行C++示例程序时,如果收到如下错误,则你没有适当的权限来处理指定 Key Vault 资源的机密。
Key Vault Secret Client Exception happened:
Caller is not authorized to perform action on resource.
If role assignments, deny assignments or role definitions were changed recently, please observe propagation time.
Caller: <redacted-application-information>
Action: 'Microsoft.KeyVault/vaults/secrets/setSecret/action'
Resource: <redacted-resource-information>
Assignment: (not found)
DenyAssignmentId: null
DecisionReason: null
Vault: <your-key-vault-name>;___location=<your-key-vault-___location>
可以使用 Azure 门户或 Azure CLI 向帐户授予适当的权限。
若要使用 Azure 门户更新权限,请导航到 Key Vault 资源的 访问控制(IAM) 页。 选择“ 添加 ”下拉列表,然后选择“ 添加角色分配”。 在 “角色 ”页上,选择 Key Vault 机密官员 角色,然后选择页面底部的 “下一步 ”。 在“成员”页上,将“分配访问权限”保留为“用户、组或服务主体”选项,然后在“选择成员”链接上选择。 在右侧的弹出窗口中,搜索并选择你的 ID,然后选择弹出窗口底部的“ 选择 ”。 所选的 ID 现在应显示在 “成员 ”部分的表中。 选择底部的 “审阅 + 分配 ”按钮。 然后再次选择 “审阅 + 分配 ”按钮。
若要使用 Azure CLI 更新权限,请输入以下命令,将用户主体名称替换为 <upn>
订阅 ID、 <subscription-id>
<resource-group-name>
资源组名称以及 <your-unique-keyvault-name>
Key Vault 实例名称:
az role assignment create --role "Key Vault Secrets Officer" --assignee "<upn>" --scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.KeyVault/vaults/<your-unique-keyvault-name>"
VS Code 包括错误
如果在使用 VS Code 时在 include 语句下看到错误行(如下图所示),编辑器不知道在何处查找包含目录。
vcpkg 在清单模式下会将包含标头置于 build/vcpkg_installed/<vcpkg-platform-triplet>/include
中。
将 <vcpkg-platform-triplet>
替换为您平台的 vcpkg 三重件。
若要将 include 目录添加到 VS Code 设置,请将鼠标悬停在包含语句附近的错误行上。 然后选择弹出窗口底部的 “快速修复...” 链接。 在“快速修复”选项中,选择“ 添加到 "includePath": ${workspaceFolder}/build/vcpkg_installed/<vcpkg-platform-triplet>/include
”选项。 C/C++“扩展配置”选项卡应打开,在“包含路径”部分下,应会看到列出的包含目录的路径。
Linux bootstrap-vcpkg 找不到依赖项
在 Linux 上运行 bootstrap-vcpkg.sh 脚本时,如果收到如下所示的错误,则无需安装必要的工具来运行脚本。
Could not find zip. Please install it (and other dependencies) with:
On Debian and Ubuntu derivatives:
sudo apt-get install curl zip unzip tar
On recent Red Hat and Fedora derivatives:
sudo dnf install curl zip unzip tar
On older Red Hat and Fedora derivatives:
sudo yum install curl zip unzip tar
On SUSE Linux and derivatives:
sudo zypper install curl zip unzip tar
On Arch Linux and derivatives:
sudo pacman -Syu base-devel git curl zip unzip tar cmake ninja
On Alpine:
apk add build-base cmake ninja zip unzip curl git
(and export VCPKG_FORCE_SYSTEM_BINARIES=1)
若要安装这些工具,请在 Linux 分发版的错误消息中使用提供的命令。 例如,在 Ubuntu 上,命令如下:
sudo apt-get install curl zip unzip tar
然后重新运行 bootstrap-vcpkg.sh
脚本。
Linux 找不到工具链文件
运行 CMake configure 命令时,如果收到如下错误,则 vcpkg.cmake 模块的路径未正确设置。
CMake Error at /usr/share/cmake-3.28/Modules/CMakeDetermineSystem.cmake:176 (message):
Could not find toolchain file:
/path/to/vcpkg-root/scripts/buildsystems/vcpkg.cmake
Call Stack (most recent call first):
CMakeLists.txt:9 (project)
在 CMakeLists.txt 文件中,将语句更新为安装 vcpkg 的正确路径。
Linux vcpkg 安装失败
运行 CMake configure 命令时,如果收到如下错误,则需要安装包的系统依赖项。
CMake Error at /path/to/vcpkg/scripts/buildsystems/vcpkg.cmake:904 (message):
vcpkg install failed. See logs for more information:
要查找所需的系统包,请在 CMake 配置命令的输出中搜索以 Could not find <system-package>
开头的行,并用缺少的系统包替换 <system-package>
。 此行下方应是安装缺少的系统包的命令。 运行该命令。 然后重新运行 CMake 配置命令。 可能需要多次重复此过程,具体取决于缺少的系统包数。