Я пытаюсь создать HTTP-клиент для API отдыха с помощью библиотеки cpprest-sdk: https://github.com/Microsoft/cpprestsdk
Я использую MacBook Pro с последней версией MacOs (10.14.2),
Я использую brew в качестве менеджера пакетов и установил boost с:
brew install boost
Варианты зависимостей:
clang: Apple LLVM версия 10.0.0 (clang-1000.11.45.5)
cmake: 3.13.2
повышение: стабильное 1.68.0 (в бутылках), HEAD
Сначала я попытался выполнить следующее:
https://github.com/Microsoft/cpprestsdk/wiki/How-to-build-for-Mac-OS-X
Поэтому я также установил cpprestsdk с boost:
boost, установите cpprestsdk
Затем я использовал код из учебника в одном файле main.cpp:
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams; // Asynchronous streams
int main(int argc, char* argv[])
{
auto fileStream = std::make_shared<ostream>();
// Open stream to output file.
pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
{
*fileStream = outFile;
// Create http_client to send the request.
http_client client(U("http://www.bing.com/"));
// Build request URI and start the request.
uri_builder builder(U("/search"));
builder.append_query(U("q"), U("cpprestsdk github"));
return client.request(methods::GET, builder.to_string());
})
// Handle response headers arriving.
.then([=](http_response response)
{
printf("Received response status code:%u\n", response.status_code());
// Write response body into the file.
return response.body().read_to_end(fileStream->streambuf());
})
// Close the file stream.
.then([=](size_t)
{
return fileStream->close();
});
// Wait for all the outstanding I/O to complete and handle any exceptions
try
{
requestTask.wait();
}
catch (const std::exception &e)
{
printf("Error exception:%s\n", e.what());
}
return 0;
}
И я создал файл сборки CMake CMakeLists.txt, как они описывают в README для cpprestsdk:
cmake_minimum_required(VERSION 3.13)
project(cpprest-example)
set(CMAKE_CXX_STANDARD 14)
find_package(cpprestsdk REQUIRED)
add_executable(cpprest-example main.cpp)
target_link_libraries(cpprest-example PRIVATE cpprestsdk::cpprest)
Сначала у меня возникла проблема с CMake, не определяющим openssl, поэтому я имелчтобы добавить два параметра env, как описано здесь:
CMake не может найти библиотеку OpenSSL
Затем он компилируется, но затем завершается ошибкой во время компоновки с ошибками:
Scanning dependencies of target cpprest-example
[ 50%] Building CXX object CMakeFiles/cpprest-example.dir/main.cpp.o
[100%] Linking CXX executable cpprest-example
Undefined symbols for architecture x86_64:
"boost::this_thread::interruption_point()", referenced from:
boost::condition_variable::wait(boost::unique_lock<boost::mutex>&) in main.cpp.o
boost::condition_variable::do_wait_until(boost::unique_lock<boost::mutex>&, boost::detail::real_platform_timepoint const&) in main.cpp.o
"boost::chrono::steady_clock::now()", referenced from:
bool boost::condition_variable::wait_for<long long, boost::ratio<1l, 1000l>, pplx::details::event_impl::wait(unsigned int)::'lambda0'()>(boost::unique_lock<boost::mutex>&, boost::chrono::duration<long long, boost::ratio<1l, 1000l> > const&, pplx::details::event_impl::wait(unsigned int)::'lambda0'()) in main.cpp.o
bool boost::condition_variable::wait_until<boost::chrono::steady_clock, boost::chrono::duration<long long, boost::ratio<1l, 1000000000l> >, pplx::details::event_impl::wait(unsigned int)::'lambda0'()>(boost::unique_lock<boost::mutex>&, boost::chrono::time_point<boost::chrono::steady_clock, boost::chrono::duration<long long, boost::ratio<1l, 1000000000l> > > const&, pplx::details::event_impl::wait(unsigned int)::'lambda0'()) in main.cpp.o
"boost::detail::get_current_thread_data()", referenced from:
boost::detail::interruption_checker::interruption_checker(_opaque_pthread_mutex_t*, _opaque_pthread_cond_t*) in main.cpp.o
"boost::system::detail::system_category_instance", referenced from:
boost::system::system_category() in main.cpp.o
"boost::system::detail::generic_category_instance", referenced from:
boost::system::generic_category() in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [cpprest-example] Error 1
make[1]: *** [CMakeFiles/cpprest-example.dir/all] Error 2
make: *** [all] Error 2
Странно то, что если я создаю кодовую базу cpprestsdk с помощью CMake, она работает нормально, и один из примеровс тем же кодом: https://github.com/Microsoft/cpprestsdk/tree/master/Release/samples/BingRequest
Этот пример проекта был успешно создан и работает нормально.
Я также попытался удалить cpprestsdk из brew и выполнил сборку CMake клонированного репозитория, а затемmsgstr "make -j4 && make install".Это устанавливает заголовки и библиотеки cpprestsdk локально, но в конце концов приводит к тем же ошибкам.
Похоже, что он не находит библиотеки boost, и я попытался использовать find_package (BOOST 1.68.0) и аналогичные вещи, нотерпит неудачу с теми же ошибками.
Кто-нибудь может увидеть, что я делаю неправильно?