

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# AWS SDK for C\$1\$1 を使用したシンプルなアプリケーションの作成
<a name="build-cmake"></a>

 [CMake](https://cmake.org/) は、アプリケーションの依存関係を管理し、ビルド対象のプラットフォームに適した Makefile を生成するためのビルドツールです。CMake を使用して、 AWS SDK for C\$1\$1を利用するプロジェクトを作成・ビルドできます。

この例では、所有している Amazon S3 バケットをレポートします。この例を実行するために AWS アカウントに S3 バケットを所有している必要はありませんが、少なくとも 1 つある方が、処理内容をはるかに確認しやすくなります。バケットがまだない場合は、「*Amazon Simple Storage Service ユーザーガイド*」の「[バケットの作成](https://docs.aws.amazon.com/AmazonS3/latest/userguide/creating-bucket.html)」を参照してください。

## ステップ 1: コードを記述する
<a name="setting-up-a-cmake-project"></a>

この例は、1 つのソースファイル (`hello_s3.cpp`) と 1 つの `CMakeLists.txt` ファイルを含む 1 つのフォルダで構成されています。プログラムは Amazon S3 を使用してストレージバケット情報をレポートします。このコードは GitHub の [AWS コードサンプルリポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/hello_s3)でも入手できます。

`CMakeLists.txt` のビルド設定ファイルでは、多くのオプションを設定できます。詳細については、CMake のウェブサイトにある「[CMake チュートリアル](https://cmake.org/cmake-tutorial/)」を参照してください。

**注記**  
詳細解説: `CMAKE_PREFIX_PATH` の設定  
デフォルトでは、macOS、Linux、Android、およびその他の Windows 以外のプラットフォーム AWS SDK for C\$1\$1 上の は にインストール`/usr/local`され、Windows 上の は にインストールされます`\Program Files (x86)\aws-cpp-sdk-all`。  
 AWS SDK をこれらの標準ロケーションにインストールすると、CMake は必要なリソースを自動的に検出します。ただし、 AWS SDK をカスタムの場所にインストールする場合は、SDK の構築に起因する次のリソースの場所を CMake に伝える必要があります。  
`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_PREFIX_PATH` を設定しないと、CMake が `CMakeLists.txt` 内の `find_package(AWSSDK)` を処理しようとした際に、「Could not find AWSSDK」 (AWSSDK が見つかりませんでした) などのエラーでビルドが失敗します。

**注記**  
詳細解説: Windows ランタイムライブラリ  
プログラムを実行するには、実行可能ファイルのある場所に複数の DLL (`aws-c-common.dll`、`aws-c-event-stream.dll`、`aws-checksums.dll`、`aws-cpp-sdk-core.dll`) と、プログラムの構成要素に応じた特定の DLL が (この例では Amazon S3 を使用するため `aws-cpp-sdk-s3` も) 必要です。`CMakeLists.txt` ファイル内の 2 番目の`if`ステートメントは、この要件を満たすために、これらのライブラリをインストール場所から実行可能場所にコピーします。 `AWSSDK_CPY_DYN_LIBS`は、SDK の DLLs をインストール場所からプログラムの実行場所にコピー AWS SDK for C\$1\$1 する で定義されるマクロです。これらの DLL が実行可能ファイルのある場所に存在しない場合、「file not found」 (ファイルが見つかりません) というランタイム例外が発生します。このようなエラーが発生した場合は、`CMakeLists.txt` ファイルのこの部分を確認して、使用している環境に応じて調整してください。

**フォルダとソースファイルを作成するには**

1. ソースファイルを保持するための `hello_s3` ディレクトリ/プロジェクトを作成します。
**注記**  
Visual Studio でこの例を完了するには、**[新しいプロジェクトの作成]** を選択してから、**[CMake プロジェクト]** を選択します。プロジェクトに `hello_s3` という名前を付けます。このプロジェクト名は `CMakeLists.txt` ファイルで使用されます。

1. そのフォルダ内に、所有している Amazon S3 バケットをレポートする次のコードを含む `hello_s3.cpp` ファイルを追加します。

   ```
   #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 Identity Center を使用して認証する場合は、 コマンドを使用して AWS CLI `aws sso login`サインインすることを忘れないでください。

**コマンドラインからプログラムを実行するには**

1. ビルド結果が生成された Debug ディレクトリに移動します。

1. 実行可能ファイルの名前を使用してプログラムを実行します。

   ```
   hello_s3
   ```

を使用したその他の例については AWS SDK for C\$1\$1、「」を参照してください[AWS SDK for C\$1\$1 AWS のサービス を使用して を呼び出すためのガイド付き例](programming-services.md)。