Qiitaからの移植です。
はじめに
C++ Advent Calendar 2018 6日目の記事です。
同アドベントカレンダーの24日目の記事執筆に向けてC++ REST SDKを試してみようと思ったのですが、導入に苦労しました。アドベントカレンダーの6日目が空いていたので、カレンダーを埋めるネタとしてメモを残しておきます。
自分の環境
- OSは macOS High Sierra バージョン 10.13.6
- Homebrew 1.8.4 でパッケージ管理
- CLion使いなのでCMakeでビルド
C++ REST SDKを導入
C++ REST SDKはHomebrewで簡単にインストールできます。
$ brew install cpprestsdk
インストール後、次のコードからプログラムをビルドしようとしました。
#include <iostream> #include <cpprest/http_client.h> #include <cpprest/filestream.h> int main() { auto url = U("https://h6ak.net"); // U(x) is a macro defined in cpprestsdk. std::string output_file_name = "output.html"; auto file_buffer = std::make_shared<concurrency::streams::streambuf<uint8_t>>(); concurrency::streams::file_buffer<uint8_t>::open(output_file_name, std::ios::out) .then([=](concurrency::streams::streambuf<uint8_t> out_file) -> pplx::task<web::http::http_response> { *file_buffer = out_file; // Create an HTTP request. web::http::client::http_client client(url); return client.request(web::http::methods::GET); }) .then([=](web::http::http_response response) -> pplx::task<size_t> { // Write the response body into the file buffer. std::cout << "Response status code: " << response.status_code() << std::endl; return response.body().read_to_end(*file_buffer); }) .then([=](size_t){ // Close the file buffer. return file_buffer->close(); }) .wait(); // Wait for the entire response body to be written into the file. return 0; }
内容は自分のWebサイトのhtmlを取得するというものです。サンプルコードを参考にしてコーディングしました。
最初はREADME.mdに従って、CMakeList.txtを
cmake_minimum_required(VERSION 3.12) project(myproj) set(CMAKE_CXX_STANDARD 11) find_package(cpprestsdk REQUIRED) add_executable(myproj main.cpp) target_link_libraries(myproj PRIVATE cpprestsdk::cpprest)
にしましたが1、ビルドできませんでした。その後いろいろ検索しながら試行錯誤を繰り返し、最終的に次のCMakeList.txtでビルドが成功しました。
cmake_minimum_required(VERSION 3.12) project(myproj) set(CMAKE_CXX_STANDARD 11) # Boost find_package(Boost COMPONENTS thread system REQUIRED) # OpenSSL set(OPENSSL_ROOT_DIR "/usr/local/opt/openssl") find_package(OpenSSL REQUIRED) find_package(cpprestsdk REQUIRED) add_executable(myproj main.cpp) target_link_libraries(myproj ${Boost_LIBRARIES} ${OPENSSL_LIBRARIES} cpprestsdk::cpprest )
めでたし、めでたし。
追記(2018/12/08) OpenSSLに対してもfind_package
が使えるので、そちらを使うようにしました。OPENSSL_ROOT_DIR
をsetしているのは、HomebrewのOpenSSLを使うためです。
-
cmake_minimum_required(VERSION 3.12)
とset(CMAKE_CXX_STANDARD 11)
は、CLionでプロジェクトを作成するときに自動的に書かれたものです。↩