vcpkgでAWS SDK for C++をインストールする

vcpkgを利用してAWS SDK for C++をインストールし、AWSのサンプルコードをビルド・実行してみました
2021.03.27

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

こんにちは、CX事業本部のうらわです。

AWS SDK for C++はGitHubリポジトリからソースコードをダウンロードしビルドする方法だけではなく、vcpkgでもインストールできます。

本記事ではvcpkgでAWS SDK for C++を利用する例をご紹介します。

環境

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.15.7
BuildVersion:   19H15


$ make --version
GNU Make 3.81
Copyright (C) 2006  Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.

This program built for i386-apple-darwin11.3.0


$ cmake --version
cmake version 3.18.4


$ gcc --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.29)
Target: x86_64-apple-darwin19.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

vcpkgとは

vcpkg は、C および C++ のライブラリのクロスプラットフォームのコマンドライン パッケージ マネージャーです。 これにより、Windows、Linux、macOS のサードパーティー ライブラリが簡単に取得およびインストールできます。

Microsoftが開発しているC/C++のパッケージマネージャーです。AWS SDK for C++開発ドキュメントでもvcpkgを利用したSDKのインストール方法が紹介されています。

今回はDynamoDBのSDKをインストールしてC++のコードをビルドし実行するところまで実施します。

Macにvcpkgをインストールする

Microsoftの公式ドキュメントに手順が記載されています。前提条件も記載されています。

Prerequisites for macOS:

  • macOS developer tools
  • On macOS 10.14 or below, you will also need:
    • Homebrew
    • g++ version 6 or greater

vcpkgではプロジェクトディレクトリごとにvcpkgをクローンしてパッケージを独立して管理・利用できます。 さっそく、お試し用のディレクトリを作成しGitHubからvcpkgをクローンします。

$ mkdir aws-sdk-vcpkg-test
$ cd aws-sdk-vcpkg-test
$ git clone https://github.com/microsoft/vcpkg.git

つづいて、ブートストラップコマンドを実行します。

The bootstrapper configures vcpkg with the locations of the compiler, tools, and standard libraries.

$ ./vcpkg/bootstrap-vcpkg.sh

以上でvcpkgを利用する準備は完了です。

AWS SDK for C++をインストールする

以下のコマンドでaws関連のパッケージを検索できます。インストールできるAWS SDKが一覧で表示されます。

$ ./vcpkg/vcpkg search aws
aws-c-common         0.4.56           AWS common library for C
aws-c-event-stream   0.1.6            C99 implementation of the vnd.amazon.event-stream content-type.
aws-checksums        0.1.9            Cross-Platform HW accelerated CRC32c and CRC32 with fallback to efficient SW i...
aws-lambda-cpp       0.2.6            C++ Runtime for AWS Lambda.
aws-sdk-cpp          1.8.126#7        AWS SDK for C++
aws-sdk-cpp[access-management]        C++ SDK for the AWS access-management service
aws-sdk-cpp[accessanalyzer]           C++ SDK for the AWS accessanalyzer service
aws-sdk-cpp[acm]                      C++ SDK for the AWS acm service
aws-sdk-cpp[acm-pca]                  C++ SDK for the AWS acm-pca service
# 省略
aws-sdk-cpp[worklink]                 C++ SDK for the AWS worklink service
aws-sdk-cpp[workmail]                 C++ SDK for the AWS workmail service
aws-sdk-cpp[workmailmessageflow]      C++ SDK for the AWS workmailmessageflow service
aws-sdk-cpp[workspaces]               C++ SDK for the AWS workspaces service
aws-sdk-cpp[xray]                     C++ SDK for the AWS xray service

今回はDynamoDBを利用するため、DynamoDBのパッケージをインストールします。インストール時のコマンドはAWSの公式ドキュメントに記載があります。

# すべてのパッケージをインストールする場合
# かなり時間がかかるためやめておく
$ ./vcpkg/vcpkg install "aws-sdk-cpp[*]" --recurse

# 個別のパッケージをインストールする
$ ./vcpkg/vcpkg install "aws-sdk-cpp[dynamodb]" --recurse

後者のコマンドでDynamoDBのパッケージをインストールします。結構時間がかかります。完了すると以下のようにCMakeLists.txtに記載する必要のあるコード例が表示されます。

# 省略

Total elapsed time: 2.716 min

The package aws-sdk-cpp:x64-osx provides CMake targets:

    find_package(AWSSDK CONFIG COMPONENTS core dynamodb kinesis s3 REQUIRED)
    target_include_directories(main PRIVATE ${AWSSDK_INCLUDE_DIRS})
    target_link_libraries(main PRIVATE ${AWSSDK_LIBRARIES})

vcpkgでインストールしたAWS SDKを利用する

AWS のコードサンプルを元に、まずはCMakeLists.txtを作成します。

CMakeLists.txt

cmake_minimum_required(VERSION 3.2)
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake CACHE STRING "Vcpkg toolchain file")
project(create-dynamodb-table)
set(CMAKE_CXX_STANDARD 17)

add_executable(main main.cpp)
find_package(AWSSDK CONFIG COMPONENTS dynamodb REQUIRED)
target_link_libraries(main PRIVATE ${AWSSDK_LIBRARIES})

CMAKE_TOOLCHAIN_FILEを設定しないとfind_packageでAWS SDKの探索に失敗します。

When using vcpkg as a submodule of your project, you can add the following to your CMakeLists.txt before the first project() call, instead of passing CMAKE_TOOLCHAIN_FILE to the cmake invocation.

set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake CACHE STRING "Vcpkg toolchain file")

This will still allow people to not use vcpkg, by passing the CMAKE_TOOLCHAIN_FILE directly, but it will make the configure-build step slightly easier.

main.cppAWSのサンプルコードをそのまま利用します。実行時に引数でテーブル名とリージョン名を受け取って新しいDynamoDBテーブルを作成するコードです。

main.cpp

/*
Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.

This file is licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License. A copy of
the License is located at

http://aws.amazon.com/apache2.0/

This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*/
#include <aws/core/Aws.h>
#include <aws/core/utils/Outcome.h> 
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
#include <aws/dynamodb/model/CreateTableRequest.h>
#include <aws/dynamodb/model/KeySchemaElement.h>
#include <aws/dynamodb/model/ProvisionedThroughput.h>
#include <aws/dynamodb/model/ScalarAttributeType.h>
#include <iostream>


/**
* Create an Amazon DynamoDB table.
*/
int main(int argc, char** argv)
{
    const std::string USAGE = "\n" \
        "Usage:\n"
        "    create_table <table> <optional:region>\n\n"
        "Where:\n"
        "    table - the table to create\n"
        "    region- optional region\n\n"
        "Example:\n"
        "    create_table HelloTable us-west-2\n";

    if (argc < 2)
    {
        std::cout << USAGE;
        return 1;
    }

    Aws::SDKOptions options;

    Aws::InitAPI(options);
    {
        const Aws::String table(argv[1]);
        const Aws::String region(argc > 2 ? argv[2] : "");

        Aws::Client::ClientConfiguration clientConfig;
        if (!region.empty())
            clientConfig.region = region;
        Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfig);

        std::cout << "Creating table " << table <<
            " with a simple primary key: \"Name\"" << std::endl;

        Aws::DynamoDB::Model::CreateTableRequest req;

        Aws::DynamoDB::Model::AttributeDefinition haskKey;
        haskKey.SetAttributeName("Name");
        haskKey.SetAttributeType(Aws::DynamoDB::Model::ScalarAttributeType::S);
        req.AddAttributeDefinitions(haskKey);

        Aws::DynamoDB::Model::KeySchemaElement keyscelt;
        keyscelt.WithAttributeName("Name").WithKeyType(Aws::DynamoDB::Model::KeyType::HASH);
        req.AddKeySchema(keyscelt);

        Aws::DynamoDB::Model::ProvisionedThroughput thruput;
        thruput.WithReadCapacityUnits(5).WithWriteCapacityUnits(5);
        req.SetProvisionedThroughput(thruput);

        req.SetTableName(table);

        const Aws::DynamoDB::Model::CreateTableOutcome& result = dynamoClient.CreateTable(req);
        if (result.IsSuccess())
        {
            std::cout << "Table \"" << result.GetResult().GetTableDescription().GetTableName() <<
                " created!" << std::endl;
        }
        else
        {
            std::cout << "Failed to create table: " << result.GetError().GetMessage();
        }
    }
    Aws::ShutdownAPI(options);
    return 0;
}

ここまで作成して、aws-sdk-vcpkg-testディレクトリは以下の状態です。

vcpkg/
CMakeLists.txt
main.cpp

ビルド・実行

一通り準備ができたのでmain.cppをcmakeでビルドします。

$ mkdir build
$ cd build
$ cmake .. -DCMAKE_BUILD_TYPE=Release
$ make

作成されたmainを実行してみます。成功すると以下のようにメッセージが表示され、AWSの指定したリージョンにテーブルが作成されます。

$ ./main aws-sdk-vcpkg-test-table ap-northeast-1
Creating table aws-sdk-vcpkg-test-table with a simple primary key: "Name"
Table "aws-sdk-vcpkg-test-table created!

おわりに

これまではGitHubのaws-sdk-cppをクローン・ビルドして利用していました。vcpkgであればAWS SDKに限らず必要なライブラリをまとめてインストールして利用できるため、積極的にvcpkgを使っていきたいと思います。

# 使いたいパッケージがインストールできるか検索してみる
$ ./vcpkg/vcpkg search nlohmann-json
nlohmann-json        3.9.1            JSON for Modern C++