

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

# 使用适用于 C\$1\$1 的 AWS SDK 创建简单应用程序
<a name="build-cmake"></a>

 [CMake](https://cmake.org/)是一种构建工具，用于管理应用程序的依赖关系和创建适合您正在构建的平台的 makefile。您可以使用 CMake 创建和生成项目 适用于 C\$1\$1 的 AWS SDK。

此示例报告您拥有的 Amazon S3 存储桶。在此示例中，您的 AWS 账户中不需要 Amazon S3 存储桶，但如果您至少有一个存储桶，那会更有趣。如果您还没有存储桶，请参阅《Amazon Simple Storage Service 用户指南》**中的[创建存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/creating-bucket.html)。

## 第 1 步：编写代码
<a name="setting-up-a-cmake-project"></a>

此示例由一个文件夹（包含一个源文件 [`hello_s3.cpp`]）和一个 `CMakeLists.txt` 文件组成。该程序使用 Amazon S3 来报告存储桶信息。此代码也可在上的[AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/hello_s3)中找到 GitHub。

可以在 `CMakeLists.txt` 构建配置文件中设置许多选项。有关更多信息，请参阅 CMake 网站上的[CMake教程](https://cmake.org/cmake-tutorial/)。

**注意**  
深度探索：设置 `CMAKE_PREFIX_PATH`  
默认情况下，macOS、Linux、安卓和其他非 Windows 平台 适用于 C\$1\$1 的 AWS SDK 上的，安装在 Windows 上`/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-stream`、`aws-c-common`、`aws-checksums`
要设置自定义安装路径，请执行以下操作：  

```
cmake -DCMAKE_PREFIX_PATH=/path/to/your/aws-sdk-installation /path/to/project/you/are/building
```
如果您未设置自定义安装，则在 CMake 尝试在中`CMAKE_PREFIX_PATH`进行处理时，您的构建将失败，并显示诸如 AWSSDK “找不到” 之类`find_package(AWSSDK)`的错误`CMakeLists.txt`。

**注意**  
深入探索：Windows 运行时库  
要运行您的程序，需要 DLLs 在程序的可执行文件位置放置几个：`aws-c-common.dll``aws-c-event-stream.dll`、`aws-checksums.dll`、`aws-cpp-sdk-core.dll`、，以及任何 DLLs 基于程序组件的特定内容（此示例还需要，`aws-cpp-sdk-s3`因为它使用了 Amazon S3）。`CMakeLists.txt`文件中的第二条`if`语句将这些库从安装位置复制到可执行位置，以满足此要求。 `AWSSDK_CPY_DYN_LIBS`是由定义的宏 适用于 C\$1\$1 的 AWS SDK ，用于将 SDK DLLs 从安装位置复制到程序的可执行位置。如果 DLLs 它们不在可执行文件位置，则会出现 “找不到文件” 的运行时异常。如果您遇到这些错误，请查看 `CMakeLists.txt` 文件的这一部分，了解您的独特环境是否需要进行必要的更改。

**创建文件夹和源文件**

1. 创建一个`hello_s3`目录 and/or 项目来保存您的源文件。
**注意**  
要在 Visual Studio 中完成此示例，请执行以下操作：选择 “**创建新项目**”，然后选择 “**CMake 项目**”。将项目命名为 `hello_s3`。`CMakeLists.txt` 文件中会使用此项目名称。

1. 在该文件夹中，添加一个包含以下代码的 `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;
   }
   ```

1. 添加一个 `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
<a name="building-with-cmake"></a>

CMake 使用中的信息`CMakeLists.txt`来生成可执行程序。

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

**使用命令行构建应用程序**

1. 创建一个目录，**`cmake`** 将在其中构建您的应用程序。

   ```
   mkdir my_project_build
   ```

1. 切换到构建目录并使用项目源代码目录的路径运行 **`cmake`**。

   ```
   cd my_project_build
   cmake ../
   ```

1. **`cmake`** 生成构建目录后，您可以使用 **`make`**（在 Windows 上为 **`nmake`**）或 MSBUILD（`msbuild ALL_BUILD.vcxproj` 或 `cmake --build . --config=Debug`）来构建应用程序。

## 步骤 3：运行
<a name="run-app"></a>

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

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

**注意**  
请记得登录！如果您使用 IAM 身份中心进行身份验证，请记住使用 AWS CLI `aws sso login`命令登录。

**通过命令行运行程序**

1. 切换到生成构建结果的 Debug 目录。

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

   ```
   hello_s3
   ```

有关使用的其他示例 适用于 C\$1\$1 的 AWS SDK，请参阅[AWS 服务 使用适用于 C\$1\$1 的 AWS SDK 进行调用的指导示例](programming-services.md)。