使用适用于 C++ 的 AWS SDK 创建简单的应用程序 - 适用于 C++ 的 AWS SDK

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用适用于 C++ 的 AWS SDK 创建简单的应用程序

CMake 是一款构建工具,可用于管理应用程序的依赖项,并生成适用于目标构建平台的 Makefile 文件。您可以使用 CMake 通过适用于 C++ 的 AWS SDK 创建和构建项目。

此示例报告您拥有的 Amazon S3 存储桶。在此示例中,您的 AWS 账户中不需要 Amazon S3 存储桶,但如果您至少有一个存储桶,那会更有趣。如果您还没有存储桶,请参阅《Amazon Simple Storage Service 用户指南》中的创建存储桶

步骤 1:编写代码

此示例由一个文件夹(包含一个源文件 [hello_s3.cpp])和一个 CMakeLists.txt 文件组成。该程序使用 Amazon S3 来报告存储桶信息。此代码也可在 GitHub 上的 AWS 代码示例存储库中找到。

可以在 CMakeLists.txt 构建配置文件中设置许多选项。有关更多信息,请参阅 CMake 网站上的 CMake 教程

注意

深度探索:设置 CMAKE_PREFIX_PATH

默认情况下,在 macOS、Linux、Android 和其他非 Windows 平台上,适用于 C++ 的 AWS SDK 的安装位置为 /usr/local,在 Windows 上的安装位置为 \Program Files (x86)\aws-cpp-sdk-all

当您将 AWS SDK 安装到这些标准位置时,CMake 会自动找到必要的资源。但是,如果您将 AWS SDK 安装到自定义位置,则必须告诉 CMake 在哪里可以找到构建 SDK 时产生的以下资源:

  • AWSSDKConfig.cmake:一个配置文件,它会告诉 CMake 如何在项目中查找和使用 AWS SDK 库。如果没有这个文件,CMake 就无法找到 AWS SDK 标头文件、无法链接到 AWS SDK 库,或无法设置正确的编译器标志。

  • (适用于版本 1.8 及更早版本)依赖项的位置:aws-c-event-streamaws-c-commonaws-checksums

要设置自定义安装路径,请执行以下操作:

cmake -DCMAKE_PREFIX_PATH=/path/to/your/aws-sdk-installation /path/to/project/you/are/building

如果您未设置自定义安装的 CMAKE_PREFIX_PATH,则当 CMake 尝试在 CMakeLists.txt 中处理 find_package(AWSSDK) 时,您的构建将失败,并显示“Could not find AWSSDK”之类的错误。

注意

深入探索:Windows 运行时库

要运行您的程序,程序的可执行位置需要有几个 DLL:aws-c-common.dllaws-c-event-stream.dllaws-checksums.dllaws-cpp-sdk-core.dll,以及基于程序组件的任何特定 DLL(此示例还需要 aws-cpp-sdk-s3,因为它使用 Amazon S3)。CMakeLists.txt 文件中的第二条 if 语句将这些库从安装位置复制到可执行位置,以满足此要求。AWSSDK_CPY_DYN_LIBS 是由 适用于 C++ 的 AWS SDK 定义的宏,用于将 SDK 的 DLL 从安装位置复制到程序的可执行位置。如果这些 DLL 不在可执行位置,则会出现“找不到文件”运行时异常。如果您遇到这些错误,请查看 CMakeLists.txt 文件的这一部分,了解您的独特环境是否需要进行必要的更改。

创建文件夹和源文件
  1. 创建用于存放源文件的 hello_s3 目录和/或项目。

    注意

    要在 Visual Studio 中完成此示例,请执行以下操作:选择创建新项目,然后选择 CMake 项目。将项目命名为 hello_s3CMakeLists.txt 文件中会使用此项目名称。

  2. 在该文件夹中,添加一个包含以下代码的 hello_s3.cpp 文件,该代码将报告您拥有的 Amazon S3 存储桶。

    #include <aws/core/Aws.h> #include <aws/s3/S3Client.h> #include <iostream> #include <aws/core/auth/AWSCredentialsProviderChain.h> using namespace Aws; using namespace Aws::Auth; /* * A "Hello S3" starter application which initializes an Amazon Simple Storage Service (Amazon S3) client * and lists the Amazon S3 buckets in the selected region. * * main function * * Usage: 'hello_s3' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. int result = 0; { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; // You don't normally have to test that you are authenticated. But the S3 service permits anonymous requests, thus the s3Client will return "success" and 0 buckets even if you are unauthenticated, which can be confusing to a new user. auto provider = Aws::MakeShared<DefaultAWSCredentialsProviderChain>("alloc-tag"); auto creds = provider->GetAWSCredentials(); if (creds.IsEmpty()) { std::cerr << "Failed authentication" << std::endl; } Aws::S3::S3Client s3Client(clientConfig); auto outcome = s3Client.ListBuckets(); if (!outcome.IsSuccess()) { std::cerr << "Failed with error: " << outcome.GetError() << std::endl; result = 1; } else { std::cout << "Found " << outcome.GetResult().GetBuckets().size() << " buckets\n"; for (auto &bucket: outcome.GetResult().GetBuckets()) { std::cout << bucket.GetName() << std::endl; } } } Aws::ShutdownAPI(options); // Should only be called once. return result; }
  3. 添加一个 CMakeLists.txt 文件,指定项目名称、可执行文件、源文件和链接库。

    # Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS s3) # Set this project's name. project("hello_s3") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # if you are building from the command line you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif () add_executable(${PROJECT_NAME} hello_s3.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES})

步骤 2:使用 CMake 构建

CMake 使用 CMakeLists.txt 中的信息来构建可执行程序。

建议您按照所用 IDE 的标准做法来构建此应用程序。

使用命令行构建应用程序
  1. 创建一个目录,cmake 将在其中构建您的应用程序。

    mkdir my_project_build
  2. 切换到构建目录并使用项目源代码目录的路径运行 cmake

    cd my_project_build cmake ../
  3. cmake 生成构建目录后,您可以使用 make(在 Windows 上为 nmake)或 MSBUILD(msbuild ALL_BUILD.vcxprojcmake --build . --config=Debug)来构建应用程序。

步骤 3:运行

运行此应用程序时,它会显示控制台输出,其中会列出 Amazon S3 存储桶的总数和每个存储桶的名称。

建议您按照所用 IDE 的标准做法来运行此应用程序。

注意

请记得登录!如果您使用 IAM Identity Center,请记住使用 AWS CLI aws sso login 命令登录。

通过命令行运行程序
  1. 切换到生成构建结果的 Debug 目录。

  2. 使用可执行文件的名称运行该程序。

    hello_s3

有关使用适用于 C++ 的 AWS SDK 的其他示例,请参阅使用适用于 C++ 的 AWS SDK 调用 AWS 服务的引导式示例