

 AWS Cloud9 不再向新客户提供。 AWS Cloud9 的现有客户可以继续正常使用这项服务。[了解详情](https://aws.amazon.com/blogs/devops/how-to-migrate-from-aws-cloud9-to-aws-ide-toolkits-or-aws-cloudshell/)

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

# 的 C\$1\$1 教程 AWS Cloud9
<a name="sample-cplusplus"></a>

本教程使你能够在 AWS Cloud9 开发环境中运行 C\$1\$1 代码。该代码还使用 [适用于 C\$1\$1 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/welcome.html) 提供的资源，这是一个模块化、跨平台的开源库，您可以使用它连接到 Amazon Web Services。

按照本教程并创建此示例可能会导致您的 AWS 账户被扣款。其中包括可能对 Amazon EC2 和 Amazon S3 等服务收取的费用。有关更多信息，请参阅 [Amazon EC2 定价](https://aws.amazon.com/ec2/pricing/)和 [Amazon S3 定价](https://aws.amazon.com/s3/pricing/)。

**Topics**
+ [先决条件](#sample-cplusplus-prereqs)
+ [步骤 1：安装 g\$1\$1 和所需的开发软件包](#sample-cplusplus-install)
+ [第 2 步：安装 CMake](#install-cmake)
+ [步骤 3：获取并构建 SDK for C\$1\$1](#install-cmake)
+ [步骤 4：创建 C\$1\$1 和 CMake列表文件](#sample-cplusplus-sdk-code)
+ [步骤 5：构建并运行 C\$1\$1 代码](#build-and-run-cpp)
+ [步骤 6：清除](#sample-cplusplus-clean-up)

## 先决条件
<a name="sample-cplusplus-prereqs"></a>

在使用此示例之前，请确保您的设置满足以下要求：
+ **您必须拥有现有 AWS Cloud9 的 EC2 开发环境。**本示例假设您已经有连接到运行 Amazon Linux 或 Ubuntu Server 的 Amazon EC2 实例的 EC2 环境。如果您有不同类型的环境或操作系统，可能需要按照本示例的说明来设置相关的工具。有关更多信息，请参阅 [在中创建环境 AWS Cloud9](create-environment.md)。
+ **您已经打开了现有环境的 AWS Cloud9 IDE。**打开环境时，会在 Web 浏览器中 AWS Cloud9 打开该环境的 IDE。有关更多信息，请参阅 [在中打开环境 AWS Cloud9](open-environment.md)。

## 步骤 1：安装 g\$1\$1 和所需的开发软件包
<a name="sample-cplusplus-install"></a>

要构建和运行 C\$1\$1 应用程序，您需要一个实用工具，例如 `g++`，这是一个由 [GNU 编译器集合 (GCC)](https://gcc.gnu.org/) 提供的C\$1\$1 编译器。

您还需要为 `libcurl`、`libopenssl`、`libuuid`、`zlib` 添加标头文件（`-dev` 程序包），并为 Amazon Polly 支持添加 `libpulse`（可选）。

根据您使用的是 Amazon Linux/Amazon Linux 2 实例还是 Ubuntu 实例，安装开发工具的过程会略有不同。

------
#### [ Amazon Linux-based systems ]

你可以通过在 AWS Cloud9 终端中运行以下命令来检查是否已经`gcc`安装：

```
g++ --version
```

如果 `g++` 未安装，您可以轻松地将其安装为名为“开发工具”的软件包组的一部分。这些工具已添加到带有 `yum groupinstall` 命令的实例：

```
sudo yum groupinstall "Development Tools"
```

再次运行 `g++ --version` 以确认编译器已安装。

现在，使用系统的软件包管理器安装所需库的软件包：

```
sudo yum install libcurl-devel openssl-devel libuuid-devel pulseaudio-libs-devel
```

------
#### [ Ubuntu-based systems ]

你可以通过在 AWS Cloud9 终端中运行以下命令来检查是否已经`gcc`安装：

```
g++ --version
```

如果 gcc 未安装，则可以通过运行以下命令将其安装在基于 Ubuntu 的系统上：

```
sudo apt update
sudo apt install build-essential
sudo apt-get install manpages-dev
```

再次运行 `g++ --version` 以确认编译器已安装。

现在，使用系统的软件包管理器安装所需库的软件包：

```
sudo apt-get install libcurl4-openssl-dev libssl-dev uuid-dev zlib1g-dev libpulse-dev
```

------

## 第 2 步：安装 CMake
<a name="install-cmake"></a>

 您需要安装 `cmake` 工具，该工具可自动执行从源代码构建可执行文件的流程。

1. 在 IDE 终端窗口中，运行以下命令以获取所需的归档文件：

   ```
   wget https://cmake.org/files/v3.18/cmake-3.18.0.tar.gz
   ```

1. 从归档文件中提取文件并导航到包含解压缩文件的目录：

   ```
   tar xzf cmake-3.18.0.tar.gz
   cd cmake-3.18.0
   ```

1. 接下来，通过运行以下命令来运行引导程序脚本并安装 `cmake`：

   ```
   ./bootstrap
   make
   sudo make install
   ```

1. 通过运行以下命令以确认您已安装该工具：

   ```
   cmake --version
   ```

## 步骤 3：获取并构建 SDK for C\$1\$1
<a name="install-cmake"></a>

要为 C\$1\$1 设置 AWS SDK，您可以直接从源代码自己构建 SDK，也可以使用包管理器下载库。您可以在《*适用于 C\$1\$1 的 AWS SDK 开发人员指南*》的《[开始使用适用于 C\$1\$1 的 AWS SDK》中找到有关](https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/getting-started.html)可用选项的详细信息。

本示例演示了使用 `git` 来克隆开发工具源代码，以及使用 `cmake` 构建 SDK for C\$1\$1。

1. 在终端中运行以下命令，为您的 AWS Cloud9 环境克隆远程存储库并递归地获取所有 git 子模块：

   ```
   git clone --recurse-submodules https://github.com/aws/aws-sdk-cpp
   ```

1. 导航到新`aws-sdk-cpp`目录，创建一个用于构建 C\$1\$1 AWS SDK 的子目录，然后导航到该目录：

   ```
   cd aws-sdk-cpp
   mkdir sdk_build
   cd sdk_build
   ```

1. 
**注意**  
为节省时间，该步骤仅构建 适用于 C\$1\$1 的 AWS SDK的 Amazon S3 部分。如果要构建完整的开发工具包，请省略 `cmake` 命令中的 `-DBUILD_ONLY=s3`。  
构建完整的 SDK for C\$1\$1 可能需要一小时以上才能完成，具体取决于 Amazon EC2 实例或您自己的服务器上的可用计算资源。

   运行以下命令，使用 `cmake` 将 SDK for C\$1\$1 的 Amazon S3 部分构建到 `sdk_build` 目录下：

   ```
   cmake .. -DBUILD_ONLY=s3
   ```

1. 现在，运行 `make install` 命令，以便可以访问构建的开发工具包：

   ```
   sudo make install
   cd ..
   ```

## 步骤 4：创建 C\$1\$1 和 CMake列表文件
<a name="sample-cplusplus-sdk-code"></a>

在本步骤中，您将创建 `C++` 文件，该文件允许项目的用户与 Amazon S3 存储桶进行交互。

您还可以创建 `CMakeLists.txt` 文件，该文件提供了 `cmake` 用于构建您的 C\$1\$1 库的说明。

1. 在 AWS Cloud9 IDE 中，使用此内容创建一个文件，然后将该文件名`s3-demo.cpp`保存在环境的根目录 (`/`) 中。

   ```
   #include <iostream>
   #include <aws/core/Aws.h>
   #include <aws/s3/S3Client.h>
   #include <aws/s3/model/Bucket.h>
   #include <aws/s3/model/CreateBucketConfiguration.h>
   #include <aws/s3/model/CreateBucketRequest.h>
   #include <aws/s3/model/DeleteBucketRequest.h>
   
   // Look for a bucket among all currently available Amazon S3 buckets.
   bool FindTheBucket(const Aws::S3::S3Client &s3Client,
                      const Aws::String &bucketName) {
   
       Aws::S3::Model::ListBucketsOutcome outcome = s3Client.ListBuckets();
   
       if (outcome.IsSuccess()) {
   
           std::cout << "Looking for a bucket named '" << bucketName << "'..."
                     << std::endl << std::endl;
   
           Aws::Vector<Aws::S3::Model::Bucket> bucket_list =
                   outcome.GetResult().GetBuckets();
   
           for (Aws::S3::Model::Bucket const &bucket: bucket_list) {
               if (bucket.GetName() == bucketName) {
                   std::cout << "Found the bucket." << std::endl << std::endl;
   
                   return true;
               }
           }
   
           std::cout << "Could not find the bucket." << std::endl << std::endl;
       } else {
           std::cerr << "listBuckets error: "
                     << outcome.GetError().GetMessage() << std::endl;
       }
   
       return outcome.IsSuccess();
   }
   
   // Create an Amazon S3 bucket.
   bool CreateTheBucket(const Aws::S3::S3Client &s3Client,
                        const Aws::String &bucketName,
                        const Aws::String &region) {
   
       std::cout << "Creating a bucket named '"
                 << bucketName << "'..." << std::endl << std::endl;
   
       Aws::S3::Model::CreateBucketRequest request;
       request.SetBucket(bucketName);
   
       if (region != "us-east-1") {
           Aws::S3::Model::CreateBucketConfiguration createBucketConfig;
           createBucketConfig.SetLocationConstraint(
                   Aws::S3::Model::BucketLocationConstraintMapper::GetBucketLocationConstraintForName(
                           region));
           request.SetCreateBucketConfiguration(createBucketConfig);
       }
   
       Aws::S3::Model::CreateBucketOutcome outcome =
               s3Client.CreateBucket(request);
   
       if (outcome.IsSuccess()) {
           std::cout << "Bucket created." << std::endl << std::endl;
       } else {
           std::cerr << "createBucket error: "
                     << outcome.GetError().GetMessage() << std::endl;
       }
   
       return outcome.IsSuccess();
   }
   
   // Delete an existing Amazon S3 bucket.
   bool DeleteTheBucket(const Aws::S3::S3Client &s3Client,
                        const Aws::String &bucketName) {
   
       std::cout << "Deleting the bucket named '"
                 << bucketName << "'..." << std::endl << std::endl;
   
       Aws::S3::Model::DeleteBucketRequest request;
       request.SetBucket(bucketName);
   
       Aws::S3::Model::DeleteBucketOutcome outcome =
               s3Client.DeleteBucket(request);
   
       if (outcome.IsSuccess()) {
           std::cout << "Bucket deleted." << std::endl << std::endl;
       } else {
           std::cerr << "deleteBucket error: "
                     << outcome.GetError().GetMessage() << std::endl;
       }
   
       return outcome.IsSuccess();
   }
   
   #ifndef EXCLUDE_MAIN_FUNCTION
   // Create an S3 bucket and then delete it.
   // Before and after creating the bucket, and again after deleting the bucket,
   // try to determine whether that bucket still exists. 
   int main(int argc, char *argv[]) {
   
       if (argc < 3) {
           std::cout << "Usage: s3-demo <bucket name> <AWS Region>" << std::endl
                     << "Example: s3-demo my-bucket us-east-1" << std::endl;
           return 1;
       }
   
       Aws::SDKOptions options;
       Aws::InitAPI(options);
       {
           Aws::String bucketName = argv[1];
           Aws::String region = argv[2];
   
           Aws::Client::ClientConfiguration config;
   
           config.region = region;
   
           Aws::S3::S3Client s3Client(config);
   
           if (!FindTheBucket(s3Client, bucketName)) {
               return 1;
           }
   
           if (!CreateTheBucket(s3Client, bucketName, region)) {
               return 1;
           }
   
           if (!FindTheBucket(s3Client, bucketName)) {
               return 1;
           }
   
           if (!DeleteTheBucket(s3Client, bucketName)) {
               return 1;
           }
   
           if (!FindTheBucket(s3Client, bucketName)) {
               return 1;
           }
       }
       Aws::ShutdownAPI(options);
   
       return 0;
   }
   #endif  // EXCLUDE_MAIN_FUNCTION
   ```

1. 创建一个包含该内容的文件，并在您的环境的根目录 (`CMakeLists.txt`) 中将该文件保存为 `/`。通过使用该文件，您可以将您的代码生成为一个可执行文件。

   ```
   # A minimal CMakeLists.txt file for the AWS SDK for C++.
   
   # The minimum version of CMake that will work.
   cmake_minimum_required(VERSION 2.8)
   
   # The project name.
   project(s3-demo)
   
   # Locate the AWS SDK for C++ package.
   set(AWSSDK_ROOT_DIR, "/usr/local/")
   set(BUILD_SHARED_LIBS ON)
   find_package(AWSSDK REQUIRED COMPONENTS s3)
   
   # The executable name and its source files.
   add_executable(s3-demo s3-demo.cpp)
   
   # The libraries used by your executable.
   target_link_libraries(s3-demo ${AWSSDK_LINK_LIBRARIES})
   ```

## 步骤 5：构建并运行 C\$1\$1 代码
<a name="build-and-run-cpp"></a>

1. 在您已在其中保存 `s3-demo.cpp` 和 `CMakeLists.txt` 的环境根目录中，运行 `cmake` 来构建您的项目：

   ```
   cmake . 
   make
   ```

1. 您现在可以从命令行运行程序。在下面的命令中，将 `my-unique-bucket-name` 替换为 Amazon S3 存储桶的唯一名称，如有必要，将 `us-east-1` 替换为您想要创建存储桶的其他 AWS 区域的标识符。

   ```
   ./s3-demo my-unique-bucket-name us-east-1
   ```

   如果程序成功运行，则将返回类似于以下内容的输出：

   ```
   Looking for a bucket named 'my-unique-bucket-name'...
   
   Could not find the bucket.
   
   Creating a bucket named 'my-unique-bucket-name'...
   
   Bucket created.
   
   Looking for a bucket named 'my-unique-bucket-name'...
   
   Found the bucket.
   
   Deleting the bucket named 'my-unique-bucket-name'...
   
   Bucket deleted.
   
   Looking for a bucket named 'my-unique-bucket-name'...
   
   Could not find the bucket.
   ```

## 步骤 6：清除
<a name="sample-cplusplus-clean-up"></a>

为防止在您完成此示例后继续向您的 AWS 账户收费，请删除该环境。有关说明，请参阅[删除中的环境 AWS Cloud9](delete-environment.md)。