AWS SDK for C++를 사용하여 간단한 애플리케이션 생성 - AWS SDK for C++

AWS SDK for C++를 사용하여 간단한 애플리케이션 생성

CMake는 애플리케이션의 종속성을 관리하고 빌드 중인 플랫폼에 적합한 makefile을 생성하는 데 사용하는 빌드 도구입니다. CMake를 사용하여 AWS SDK for C++로 프로젝트를 생성하고 빌드할 수 있습니다.

이 예제에서는 사용자가 소유한 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 플랫폼에서 AWS SDK for C++는 /usr/local에 설치되고 Windows에서는 \Program Files (x86)\aws-cpp-sdk-all에 설치됩니다.

AWS SDK를 이러한 표준 위치에 설치하면 CMake가 필요한 리소스를 자동으로 찾습니다. 그러나 AWS SDK를 사용자 지정 위치에 설치하는 경우, SDK 빌드 결과 생성되는 다음 리소스를 찾을 수 있는 위치를 CMake에 알려야 합니다:

  • AWSSDKConfig.cmake: 프로젝트에서 AWS SDK 라이브러리를 찾고 사용하는 방법을 CMake에 알려주는 구성 파일입니다. 이 파일이 없으면 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)를 처리할 때 "AWSSDK를 찾을 수 없음"과 같은 오류가 발생하면서 빌드가 실패합니다.

참고

심층 분석: Windows 런타임 라이브러리

프로그램을 실행하려면 프로그램의 실행 위치에 aws-c-common.dll, aws-c-event-stream.dll, aws-checksums.dll, aws-cpp-sdk-core.dll 등의 여러 DLL이 필요할 뿐만 아니라 프로그램의 구성 요소에 따른 특정 DLL도 필요합니다. 이 예제에서는 Amazon S3를 사용하므로 aws-cpp-sdk-s3도 필요합니다. CMakeLists.txt 파일의 두 번째 if 문은 이 요구 사항을 충족시키기 위해 설치 위치에서 실행 파일 위치로 해당 라이브러리를 복사합니다. AWSSDK_CPY_DYN_LIBS는 AWS SDK for C++에서 정의한 매크로로, SDK의 DLL을 설치 위치에서 프로그램의 실행 가능한 위치로 복사합니다. 이러한 DLL이 실행 파일 위치에 없는 경우 '파일을 찾을 수 없음' 런타임 예외가 발생합니다. 이러한 오류가 발생할 경우 CMakeLists.txt 파일의 이 부분을 검토하여 고유한 환경에 필요한 변경 사항을 확인합니다.

폴더와 소스 파일을 생성하려면
  1. 소스 파일을 보관할 hello_s3 디렉터리 및/또는 프로젝트를 생성합니다.

    참고

    Visual Studio에서 이 예제를 완료하려면: 새 프로젝트 만들기를 선택한 다음 CMake 프로젝트를 선택합니다. 프로젝트 이름을 hello_s3로 지정합니다. 이 프로젝트 이름은 CMakeLists.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.vcxproj 또는 cmake --build . --config=Debug)를 사용하여 애플리케이션을 빌드할 수 있습니다.

3단계: 실행

이 애플리케이션을 실행하면 총 Amazon S3 버킷 수와 각 버킷의 이름을 나열하는 콘솔 출력이 표시됩니다.

IDE의 표준 관행에 따라 애플리케이션을 실행하는 것이 좋습니다.

참고

로그인하는 것을 잊지 마세요! IAM Identity Center를 사용하여 인증하는 경우 AWS CLI aws sso login 명령을 사용하여 로그인해야 합니다.

명령줄을 통해 프로그램을 실행하려면
  1. 빌드 결과가 생성된 디버그 디렉터리로 변경합니다.

  2. 실행 파일의 이름을 사용하여 프로그램을 실행합니다.

    hello_s3

AWS SDK for C++를 사용하는 추가 예제는 AWS SDK for C++를 사용하여 AWS 서비스를 호출하는 안내 예제 섹션을 참조하세요.