락프리(Lock-Free) 알고리즘 이해하기

멀티스레드 프로그래밍 환경에서 동시성 제어는 성능과 직결되는 매우 중요한 문제입니다. 이번 글에서는 전통적인 락 기반 동시성 제어의 한계를 극복하기 위해 등장한 락프리(Lock-Free) 알고리즘에 대해 알아보고, 그 개념과 구현 방법, 그리고 장단점을 살펴보겠습니다. 락프리 알고리즘이란? **락프리(Lock-Free)**는 이름 그대로 “자물쇠(Lock) 없이” 여러 스레드가 동시에 데이터를 처리하는 기술입니다. 쉽게 비유하자면 회전문과 같습니다. 락(Lock): 한 번에 한 명만 들어갈 수 있는 화장실입니다. 누군가 안에 있으면 밖에서 열쇠를 받을 때까지 마냥 기다려야 합니다. 락프리(Lock-Free): 여러 사람이 동시에 지나갈 수 있는 회전문입니다. 가끔 문이 꽉 차서 한 바퀴 더 돌아야 할 수도 있지만, 멈추지 않고 계속 움직일 수 있습니다. 락프리는 시스템 전체가 멈추는 일(Deadlock) 없이, 누군가는 반드시 작업을 완료한다는 것을 보장합니다. ...

December 7, 2025 · Byung Kyu KIM

C++ std::format, std::print 사용법과 컴파일러 호환성

C++20 std::format과 C++23 std::print: 현대적인 문자열 포매팅 C++20과 C++23은 문자열 포매팅을 현대화한 std::format과 std::print를 도입하며, 기존의 printf나 std::cout에 비해 안전하고 직관적인 API를 제공합니다. 이 글에서는 두 기능의 사용법, 컴파일러 호환성, 그리고 지원되지 않는 환경에서 fmt 라이브러리 사용 방법을 다룹니다. 왜 새로운 포매팅 API가 중요한가? 기존 C++ 문자열 포매팅 방법(printf, std::stringstream, std::cout)은 다음과 같은 단점이 있습니다: 안전성 부족: printf는 타입 안정성을 보장하지 않아 런타임 오류 발생 가능. 복잡성: std::stringstream은 장황하고 성능 오버헤드 존재. 가독성: std::cout은 연속적인 << 연산으로 코드가 길어짐. std::format(C++20)과 std::print(C++23)는 Python의 str.format에서 영감을 받아 타입 안전성, 가독성, 성능을 개선했습니다. fmt 라이브러리는 이를 보완하며, 최신 표준을 지원하지 않는 환경에서도 동일한 경험을 제공합니다. ...

May 22, 2025 · Byung Kyu KIM

C++ 메모리 할당기 - tcmalloc, jemalloc

멀티스레드 최적화 힙 메모리 할당기: tcmalloc, jemalloc 이글 UPDATE : https://cdecl.tistory.com/304 왜 멀티스레드 메모리 할당기가 중요한가? 기본 메모리 할당기(glibc의 malloc, Windows의 HeapAlloc)는 범용성을 목표로 설계되었지만, 멀티스레드 환경에서는 다음과 같은 문제로 성능이 저하됩니다: 락 경합(Lock Contention): 다중 스레드가 동시에 메모리를 할당/해제할 때 락으로 인한 대기 시간 증가. 메모리 단편화(Memory Fragmentation): 빈번한 할당/해제로 메모리 사용 효율 저하. ABI 호환성 문제: 서로 다른 컴파일러나 표준 라이브러리 간 메모리 관리 방식 차이로 인한 런타임 오류. tcmalloc, jemalloc, mimalloc은 스레드별 캐싱, 효율적인 메모리 관리, ABI 안정성을 고려한 설계로 이러한 문제를 해결합니다. 이들은 웹 브라우저(Chrome, Firefox), 데이터베이스(MySQL, RocksDB), 고성능 서버에서 널리 사용됩니다. ...

May 15, 2025 · Byung Kyu KIM

C++ 언어의 ABI 이슈 및 호환성 가이드

C++ 언어의 ABI 이슈 및 호환성 가이드 1. ABI란 무엇인가? ABI(Application Binary Interface)는 컴파일된 바이너리 코드(오브젝트 파일, 라이브러리, 실행 파일 등)가 서로 상호작용할 수 있도록 정의된 규칙입니다. C++에서는 이름 맹글링, 호출 규약, 객체 레이아웃, 예외 처리 등이 포함됩니다. C++의 복잡한 기능(클래스, 템플릿, 예외 처리 등)으로 인해 ABI 이슈는 특히 중요하며, 서로 다른 컴파일러나 환경 간 호환성 문제를 자주 일으킵니다. 2. C++ ABI의 주요 이슈 C++는 언어의 복잡성으로 인해 다양한 ABI 이슈가 발생합니다. 아래는 주요 이슈와 구체적인 예입니다. ...

May 1, 2025 · Byung Kyu KIM

모던 CMake 기본 가이드

모던 CMake 기본 가이드: 타겟 중심의 현대적인 빌드 시스템 1. Makefile 대비 CMake의 장점 크로스 플랫폼 지원 Makefile은 Unix 계열 시스템에 특화되어 있지만, CMake는 Windows, Linux, macOS 등 다양한 플랫폼 지원 Visual Studio, Ninja, Unix Makefiles 등 다양한 빌드 시스템 생성 가능 타겟 중심의 의존성 관리 명확한 의존성 전파 (PUBLIC, PRIVATE, INTERFACE) 자동 헤더 의존성 추적 현대적인 패키지 관리 (find_package) 향상된 IDE 지원 Visual Studio, CLion 등과 완벽한 통합 자동 완성 및 인텔리센스 지원 CMake 프리셋 지원 2. 모던 CMake의 특징 기존 CMake와의 주요 차이점 타겟 중심 접근: 전역 변수 대신 특정 타겟에 한정하여 빌드 옵션을 지정합니다. 개선된 의존성 관리: 빌드 의존성 문제를 해결하고 불필요한 참조를 줄입니다. 새로운 명령어 도입: target_link_libraries, target_include_directories 등의 새로운 명령어를 사용합니다. PUBLIC, PRIVATE 키워드를 통한 세밀한 의존 관계 설정 CMake 3.0.0부터 모던 CMake의 기본 기능 지원 CMake 3.12+ 버전부터 “More Modern CMake” 기능 제공 CMake 3.15+ 버전 사용 권장 타겟 중심 접근 # 안티패턴 (사용하지 말 것) include_directories(include) add_definitions(-DSOME_DEFINE) link_directories(lib) # 모던 패턴 (권장) add_executable(myapp src/main.cpp) target_include_directories(myapp PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ) target_compile_definitions(myapp PRIVATE SOME_DEFINE ) target_link_directories(myapp PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/lib ) 범위와 전파 # 라이브러리 설정 add_library(mylib SHARED src/lib.cpp include/lib.h ) target_include_directories(mylib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include # 헤더는 공개 PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src # 구현은 비공개 ) # 실행 파일에서 라이브러리 사용 add_executable(myapp src/main.cpp) target_link_libraries(myapp PRIVATE mylib) # 자동으로 include 경로 전파 범위(Scope)와 전파(Propagation)의 개념 CMake에서 범위는 특정 설정(컴파일 옵션, include 디렉토리 등)이 어디에 적용될지를 나타냅니다. 전파는 이러한 설정이 다른 타겟(target)으로 전달되는 방식을 정의합니다. ...

November 15, 2024 · Byung Kyu KIM

C++ Lambda 표현식

C++14, C++17, C++20 버전별 Lambda 표현 정리 The Evolutions of Lambdas in C++14, C++17 and C++20 https://www.fluentcpp.com/2021/12/13/the-evolutions-of-lambdas-in-c14-c17-and-c20/{:target="_blank"} 해당 글을 참고하여 예제 자체 작성 C++14 Default parameters #include <iostream> using namespace std; int main() { auto fn = [](int a, int b = 0) { return a + b; }; cout << fn(1) << endl; // 1 cout << fn(1, 2) << endl; // 3 } Template parameters #include <iostream> #include <string> #include <vector> using namespace std; int main() { auto fn = [](auto && c) { return c.size(); }; vector<int> v = {1, 2, 3}; cout << fn(v) << endl; // 3 string s = "12345"; cout << fn(s) << endl; // 5 } Generalised capture #include <iostream> #include <string> using namespace std; int main() { string str = "string"; auto fn = [s = str + "_capture"s](string body) { cout << s << " : " << body << endl; }; fn("test"); // string_capture : test } Returning a lambda from a function #include <iostream> using namespace std; auto getAdd(int n) { return [n](int an) { return n + an; }; } int main() { auto fn = getAdd(10); cout << fn(20) << endl; } C++17 Constexpr #include <iostream> using namespace std; int main() { constexpr auto fn = [](int n){ return n + 10; }; static_assert(fn(10) == 20); // ok static_assert(fn(20) == 20); // error: static assertion failed } Capturing a copy of *this this 참조에 캡쳐가 아닌, *this 복사본 캡쳐 #include <iostream> #include <memory> #include <tuple> using namespace std; class item { public: item(int n = 0) : _value(n) {} auto test() { _value += 1; // copy capture auto fn1 = [*this] { return _value; }; auto fn2 = [self = *this] { return self._value; }; // ref capture auto fn3 = [this] { return _value; }; _value += 1; fn1(); // 11 fn2(); // 11 fn3(); // 12 return make_tuple(fn1, fn2, fn3); } private: int _value; }; int main() { auto it = make_shared<item>(10); auto tp = it->test(); it.reset(); cout << get<0>(tp)() << endl; cout << get<1>(tp)() << endl; cout << get<2>(tp)() << endl; // ref memory error } C++20 Template syntax for lambdas #include <iostream> #include <vector> using namespace std; int main() { auto fn = []<typename T>(vector<T> &v) { return v.size(); }; vector<int> v = {1, 2, 3, 4, 5}; cout << fn(v) << endl; } Lambda capture of parameter pack #include <iostream> #include <string> using namespace std; template <typename... Args> auto getAddFunc(Args&&... args){ // by ref [&...args = std::forward<Args>(args)] // by value return [...args = std::forward<Args>(args)] (auto && init) { return init + (args + ...); }; } int main() { auto fn = getAddFunc(1, 2, 3); cout << fn(10) << endl; // 16 auto fns = getAddFunc("this "s, "is "s, "sample"s); cout << fns("note: "s) << endl; // note: this is sample }

December 14, 2021 · Byung Kyu KIM

C++20 Modules - gnu c++ test

C++ Modules Test Example (g++) C++20 Modules C++20에 추가된 모듈 Modules 기능은 기존의 헤더 파일 #include로 인한 컴파일 시간 증가 문제를 해결하고, 필요한 로직(함수, 심볼)만을 내보내는(export) 방식을 통해 타 언어의 모듈 단위처럼 효율적인 라이브러리 관리를 지원합니다. Modules의 주요 장점 컴파일 시간 단축: 각 모듈은 한 번만 컴파일되며, 그 결과가 캐시됨 심볼 격리: 모듈 내부의 심볼은 명시적으로 export하지 않는 한 외부에서 접근 불가 순환 의존성 방지: 헤더 파일과 달리 명확한 의존성 그래프 형성 매크로 독립성: 모듈은 매크로의 영향을 받지 않아 더 안정적인 코드 작성 가능 일종의 PCH(Precompiled Header)의 기능을 포함한 표준적인 모듈 관리 기능입니다. 현재 컴파일러마다 (MSVC, g++, Clang) Standard Library 지원과 모듈 사용 방법이 약간 상이합니다. ...

September 3, 2021 · Byung Kyu KIM

Httplib (cpp-httplib) Sample

Introduction https://github.com/yhirose/cpp-httplib{:target="_blank"} A C++11 single-file header-only cross platform HTTP/HTTPS library. This is a multi-threaded ‘blocking’ HTTP library header-only 라이브러리로 Server와 Client Http 지원 SSL을 위한 OpenSSL 필요 cpprestsdk비해 가볍고, 쉽게 사용 가능 Httplib package install (w/ vcpkg) https://github.com/microsoft/vcpkg{:target="_blank"} vcpkg 통해서 패키지 설치 header-only로 바로 사용가능하나 OpenSSL 필요시 패키지 설치가 용이 # --triplet=x64-windows-static $ vcpkg.exe install cpp-httplib openssl --triplet=x64-windows-static ... The package cpp-httplib:x64-windows-static is header only and can be used from CMake via: find_path(CPP_HTTPLIB_INCLUDE_DIRS "httplib.h") target_include_directories(main PRIVATE ${CPP_HTTPLIB_INCLUDE_DIRS}) The package openssl is compatible with built-in CMake targets: find_package(OpenSSL REQUIRED) target_link_libraries(main PRIVATE OpenSSL::SSL OpenSSL::Crypto) Json test https://github.com/nlohmann/json{:target="_blank"} $ vcpkg.exe install nlohmann-json --triplet=x64-windows-static The package nlohmann-json:x64-windows-static provides CMake targets: find_package(nlohmann_json CONFIG REQUIRED) target_link_libraries(main PRIVATE nlohmann_json nlohmann_json::nlohmann_json) Sample code HTTPS 호출을 위해 CPPHTTPLIB_OPENSSL_SUPPORT 매크로가 정의 되어 있어야 함 정의하지 않고 HTTPS 호출시 : 'https' scheme is not supported. using namespace std; std namespace 노출시 byte 타입 정의 모호함으로 인한 에러 발생 표준 라이브러리 보다 먼저 선언되던가 using namespace std;를 피해야 함 ‘byte’: 모호한 기호입니다. #define CPPHTTPLIB_OPENSSL_SUPPORT #include <httplib.h> #include <iostream> using namespace std; #include <nlohmann/json.hpp> using json = nlohmann::json; void HttpRequest() { httplib::Client cli("https://httpbin.org"); { auto resp = cli.Get("/get"); cout << "status: " << resp->status << endl; cout << resp->body << endl; } { auto resp = cli.Post("/post"); cout << "status: " << resp->status << endl; cout << resp->body << endl; auto js = json::parse(resp->body); cout << "User-Agent: " << js["headers"]["User-Agent"] << endl; } } int main() { try { HttpRequest(); } catch (exception &e) { cerr << e.what() << endl; } catch (...) { cerr << "catch ..." << endl; } return 0; } CMakeLists.txt cmake_minimum_required(VERSION 3.11) project(main) set(CMAKE_CXX_STANDARD 17) add_executable(main main.cpp) target_compile_options(main PRIVATE /MT) find_package(OpenSSL REQUIRED) target_link_libraries(main PRIVATE OpenSSL::SSL OpenSSL::Crypto) find_path(CPP_HTTPLIB_INCLUDE_DIRS "httplib.h") target_include_directories(main PRIVATE ${CPP_HTTPLIB_INCLUDE_DIRS}) find_package(nlohmann_json CONFIG REQUIRED) target_link_libraries(main PRIVATE nlohmann_json nlohmann_json::nlohmann_json) $ mkdir build && cd build # x64-windows-static $ cmake -G "Visual Studio 16 2019" -A x64 .. -DCMAKE_TOOLCHAIN_FILE=D:/Lib/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static Build & Run # build $ echo cmake --build . --config Release > make.bat $ make.bat # run $ Release\main.exe status: 200 { "args": {}, "headers": { "Accept": "*/*", "Cache-Control": "max-stale=0", "Host": "httpbin.org", "User-Agent": "cpp-httplib/0.9", "X-Amzn-Trace-Id": "Root=1-611dba9f-0bdb46bb04c05b410da75cf4", "X-Bluecoat-Via": "ce2cfae06b3f12b4" }, "origin": "xx.xx.xx.xx", "url": "https://httpbin.org/get" } status: 200 { "args": {}, "data": "", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Content-Length": "0", "Host": "httpbin.org", "User-Agent": "cpp-httplib/0.9", "X-Amzn-Trace-Id": "Root=1-611dba9f-091d99a41e5b3c023550162f", "X-Bluecoat-Via": "ce2cfae06b3f12b4" }, "json": null, "origin": "xx.xx.xx.xx", "url": "https://httpbin.org/post" } User-Agent: "cpp-httplib/0.9"

August 18, 2021 · Byung Kyu KIM

Vcpkg Basic

https://vcpkg.io/{:target="_blank"} Vcpkg helps you manage C and C++ libraries on Windows, Linux and MacOS. This tool and ecosystem are constantly evolving, and we always appreciate contributions! Introduction https://github.com/microsoft/vcpkg{:target="_blank"} MS에서 만든 C++ Library Package 관리 (Cross Platform) Vcpkg install Git 이 필요하고, bootstrap-vcpkg 실행으로 필요한 툴을 다운로드(빌드)하는 작업을 수행 vcpkg.exe 생성 $ git clone https://github.com/microsoft/vcpkg $ cd vcpkg # windows $ bootstrap-vcpkg.bat # linux $ ./bootstrap-vcpkg.sh Package search & install triplet : Target configuration set 설치시 triplet 을 지정하지 않으면 설치되어 있는 기본 C++ Toolset 으로 지정 Windows의 경우 x86-windows default 주요 Triplet list vcpkg help triplet $ vcpkg help triplet Available architecture triplets VCPKG built-in triplets: ... x64-windows-static x64-windows x86-windows ... VCPKG community triplets: ... x64-windows-static-md x86-windows-static-md x86-windows-static x64-mingw-dynamic x64-mingw-static x86-mingw-dynamic x86-mingw-static x64-linux ... Search vcpkg search # Package search $ vcpkg search fmt fmt 7.1.3#5 Formatting library for C++. ... The search result may be outdated. Run `git pull` to get the latest results. Install vcpkg install vcpkg search 에서 찾은 패키지를 triplet 을 지정하여 설치 설치가 완료되면 프로젝트 CMakeLists.txt 넣을 find_package 문 표시 # Package 별로 triplet 지정 $ vcpkg.exe install fmt:x64-windows-static nlohmann-json:x64-windows-static # triplet 공통 지정 $ vcpkg.exe install fmt nlohmann-json --triplet=x64-windows-static ... The package fmt provides CMake targets: find_package(fmt CONFIG REQUIRED) target_link_libraries(main PRIVATE fmt::fmt) # Or use the header-only version find_package(fmt CONFIG REQUIRED) target_link_libraries(main PRIVATE fmt::fmt-header-only) The package nlohmann-json:x64-windows-static provides CMake targets: find_package(nlohmann_json CONFIG REQUIRED) target_link_libraries(main PRIVATE nlohmann_json nlohmann_json::nlohmann_json) 설치된 리스트 vcpkg list # Package installed list $ vcpkg list benchmark:x64-mingw-static 1.5.5 A library to support the benchmarking of functio... benchmark:x64-windows-static 1.5.5 A library to support the benchmarking of functio... cpp-httplib:x64-mingw-static 0.9.1 A single file C++11 header-only HTTP/HTTPS serve... cpp-httplib:x64-windows-static 0.9.1 A single file C++11 header-only HTTP/HTTPS serve... fmt:x64-windows 7.1.3#5 Formatting library for C++. It can be used as a ... fmt:x64-windows-static 7.1.3#5 Formatting library for C++. It can be used as a ... nlohmann-json:x64-mingw-static 3.9.1 JSON for Modern C++ nlohmann-json:x64-windows-static 3.9.1 JSON for Modern C++ openssl:x64-mingw-static 1.1.1k#8 OpenSSL is an open source project that provides ... openssl:x64-windows-static 1.1.1k#8 OpenSSL is an open source project that provides ... vcpkg-cmake-config:x64-windows 2021-05-22#1 vcpkg-cmake:x64-windows 2021-07-30 zlib:x64-mingw-static 1.2.11#11 A compression library zlib:x64-windows-static 1.2.11#11 A compression library Integrate install vcpkg integrate install Windows Visual Studio에서 vcpkg 라이브러리를 별도 설정 없이 바로 사용 $ vcpkg integrate install Applied user-wide integration for this vcpkg root. All MSBuild C++ projects can now #include any installed libraries. Linking will be handled automatically. Installing new libraries will make them instantly available. CMake projects should use: "-DCMAKE_TOOLCHAIN_FILE=D:/Lib/vcpkg/scripts/buildsystems/vcpkg.cmake" vcpkg 명령어 # Vcpkg package management program version 2021-08-12-85ab112d5ee102bc6eac8cdbbfdd173a71374e04 $ vcpkg help Commands: vcpkg search [pat] Search for packages available to be built vcpkg install <pkg>... Install a package vcpkg remove <pkg>... Uninstall a package vcpkg remove --outdated Uninstall all out-of-date packages vcpkg list List installed packages vcpkg update Display list of packages for updating vcpkg upgrade Rebuild all outdated packages vcpkg x-history <pkg> (Experimental) Shows the history of CONTROL versions of a package vcpkg hash <file> [alg] Hash a file by specific algorithm, default SHA512 vcpkg help topics Display the list of help topics vcpkg help <topic> Display help for a specific topic vcpkg integrate install Make installed packages available user-wide. Requires admin privileges on first use vcpkg integrate remove Remove user-wide integration vcpkg integrate project Generate a referencing nuget package for individual VS project use vcpkg integrate powershell Enable PowerShell tab-completion vcpkg export <pkg>... [opt]... Exports a package vcpkg edit <pkg> Open up a port for editing (uses %EDITOR%, default 'code') vcpkg create <pkg> <url> [archivename] Create a new package vcpkg x-init-registry <path> Initializes a registry in the directory <path> vcpkg owns <pat> Search for files in installed packages vcpkg depend-info <pkg>... Display a list of dependencies for packages vcpkg env Creates a clean shell environment for development or compiling vcpkg version Display version information vcpkg contact Display contact information to send feedback ... 1. 내 프로젝트에서 사용 (CMake, find_package) CMakeLists.txt 에 find_package 내용 추가 CMakeLists.txt cmake_minimum_required(VERSION 3.11) project(main) set(CMAKE_CXX_STANDARD 17) add_executable(main main.cpp) if(MSVC) target_compile_options(main PRIVATE /MT) else() target_compile_options(main PRIVATE -Wall -O2) endif() find_package(fmt CONFIG REQUIRED) target_link_libraries(main PRIVATE fmt::fmt) find_package(nlohmann_json CONFIG REQUIRED) target_link_libraries(main PRIVATE nlohmann_json nlohmann_json::nlohmann_json) CMake 초기화 CMAKE_TOOLCHAIN_FILE 과 VCPKG_TARGET_TRIPLET 을 지정하여 초기화 CMAKE_TOOLCHAIN_FILE : vcpkg/scripts/buildsystems/vcpkg.cmake $ mkdir build && cd build # windows msvc $ cmake -G "Visual Studio 16 2019" -A x64 .. -DCMAKE_TOOLCHAIN_FILE=D:/Lib/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static # windows mingw $ cmake -G "MSYS Makefiles" .. -DCMAKE_TOOLCHAIN_FILE=D:/Lib/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-mingw-static # linux : VCPKG_TARGET_TRIPLET 지정안함, defualt 사용 $ cmake cmake .. -DCMAKE_TOOLCHAIN_FILE=~/lib/vcpkg/scripts/buildsystems/vcpkg.cmake Build # windows msvc : Release 모드 빌드 $ cmake --build . --config=Release # run $ Release\main.exe # mingw, linux $ make $ ./main 2. 내 프로젝트에서 사용 (라이브러리 수동으로 설정) CMake 수동 지정 : target_include_directories, target_link_directories, target_link_libraries 별도 지정 Makefile 사용 : -I -l -L 등의 옵션 추가 vcpkg/installed/triplet 디렉토리 참고 수동으로 include, lib 등 지정 사용 triplet/include : header files triplet/lib : static library triplet/bin : shared library $ tree vcpkg/installed -L 3 vcpkg/installed ├── vcpkg ... ├── x64-mingw-static │ ├── debug │ │ └── lib │ ├── include │ │ ├── benchmark │ │ ├── httplib.h │ │ ├── nlohmann │ │ ├── openssl │ │ ├── zconf.h │ │ └── zlib.h │ ├── lib │ │ ├── libbenchmark.a │ │ ├── libbenchmark_main.a │ │ ├── libcrypto.a │ │ ├── libssl.a │ │ ├── libzlib.a │ │ └── pkgconfig │ └── share │ ├── benchmark │ ├── cpp-httplib │ ├── nlohmann-json │ ├── nlohmann_json │ ├── openssl │ └── zlib ├── x64-windows │ ├── bin │ │ ├── fmt.dll │ │ └── fmt.pdb │ ├── debug │ │ ├── bin │ │ └── lib │ ├── include │ │ └── fmt │ ├── lib │ │ ├── fmt.lib │ │ └── pkgconfig │ └── share │ ├── fmt │ ├── vcpkg-cmake │ └── vcpkg-cmake-config └── x64-windows-static ├── debug │ ├── lib │ └── misc ├── include │ ├── benchmark │ ├── fmt │ ├── httplib.h │ ├── nlohmann │ ├── openssl │ ├── zconf.h │ └── zlib.h ├── lib │ ├── benchmark.lib │ ├── benchmark_main.lib │ ├── fmt.lib │ ├── libcrypto.lib │ ├── libssl.lib │ ├── ossl_static.pdb │ ├── pkgconfig │ └── zlib.lib ├── misc │ ├── CA.pl │ └── tsget.pl ├── share │ ├── benchmark │ ├── cpp-httplib │ ├── fmt │ ├── nlohmann-json │ ├── nlohmann_json │ ├── openssl │ └── zlib └── tools └── openssl

August 18, 2021 · Byung Kyu KIM

C++ REST SDK(cpprestsdk) Sample

Introduction https://github.com/Microsoft/cpprestsdk{:target="_blank"} Microsoft에서 만든 클라이언트, 서버용 C++ HTTP 통신 모듈이며, JSON URI, 비동기, 웹소켓, oAuth 등을 지원 C++11의 비동기, 병렬 프로그램 모델 지원 크로스 플랫폼 지원 등.. cpprestsdk package install (w/ vcpkg) https://github.com/microsoft/vcpkg{:target="_blank"} vcpkg 통해서 패키지 설치 # --triplet=x64-windows-static $ vcpkg.exe install cpprestsdk:x64-windows-static ... The package cpprestsdk:x64-windows-static provides CMake targets: find_package(cpprestsdk CONFIG REQUIRED) target_link_libraries(main PRIVATE cpprestsdk::cpprest cpprestsdk::cpprestsdk_zlib_internal cpprestsdk::cpprestsdk_brotli_internal) Sample code U("") 는 _T("") 와 비슷한, UNICODE 및 MBCS 환경의 문자열 타입을 스위칭 해주는 매크로. 허나 U는 _T와는 다르게 _WIN32 환경이면 기본으로 _UTF16_STRINGS으로 정의되어 있어 프로젝트의 문자집합의 세팅과 관계 없이 UNICODE와 같은 환경으로 동작 리눅스 환경에서는 다른 설정을 해주지 않는 이상 char, std::string으로 정의 utility::string_t은 std::string과 std::wstring을 스위칭 해주는 타입 대체적인 패턴은, 동기는 .get(), 비동기는 then().wait() 조합으로 사용 #include <iostream> using namespace std; #include <cpprest/http_client.h> #include <cpprest/filestream.h> using namespace utility; using namespace web; using namespace web::http; using namespace web::http::client; using namespace concurrency::streams; void HttpRequest() { http_client client(U("http://httpbin.org/get")); http_request req(methods::GET); // sync request auto resp = client.request(req).get(); wcout << resp.status_code() << " : sync request" << endl; wcout << resp.extract_string(true).get() << endl; // async request client.request(req).then([=](http_response r){ wcout << r.status_code() << " : async request" << endl; wcout << U("content-type : ") << r.headers().content_type() << endl; r.extract_string(true).then([](string_t v) { wcout << v << endl; }).wait(); }).wait(); // async request json client.request(req).then([=](http_response r){ wcout << r.status_code() << " : async request json" << endl; wcout << U("content-type : ") << r.headers().content_type() << endl; r.extract_json(true).then([](json::value v) { wcout << v << endl; }).wait(); }).wait(); } int main() { // wcout.imbue(locale("kor")); // windows only HttpRequest(); return 0; } CMakeLists.txt cmake_minimum_required(VERSION 3.11) project(main) add_executable(main main.cpp) target_compile_options(main PRIVATE /MT) find_package(cpprestsdk CONFIG REQUIRED) target_link_libraries(main PRIVATE cpprestsdk::cpprest cpprestsdk::cpprestsdk_zlib_internal cpprestsdk::cpprestsdk_brotli_internal) $ mkdir build && cd build # x64-windows-static $ cmake -G "Visual Studio 16 2019" -A x64 .. -DCMAKE_TOOLCHAIN_FILE=D:/Lib/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows-static Build & Run # build $ cmake --build . --config Release # run $ Release\main.exe 200 : sync request { "args": {}, "headers": { "Cache-Control": "max-stale=0", "Host": "httpbin.org", "User-Agent": "cpprestsdk/2.10.18", "X-Amzn-Trace-Id": "Root=1-611cbc68-27731b2a1cd55cbd682c517e", "X-Bluecoat-Via": "ce2cfae06b3f12b4" }, "origin": "xx.xx.xx.xx", "url": "http://httpbin.org/get" } 200 : async request content-type : application/json { "args": {}, "headers": { "Cache-Control": "max-stale=0", "Host": "httpbin.org", "User-Agent": "cpprestsdk/2.10.18", "X-Amzn-Trace-Id": "Root=1-611cbc68-27731b2a1cd55cbd682c517e", "X-Bluecoat-Via": "ce2cfae06b3f12b4" }, "origin": "xx.xx.xx.xx", "url": "http://httpbin.org/get" } 200 : async request json content-type : application/json {"args":{},"headers":{"Cache-Control":"max-stale=0","Host":"httpbin.org","User-Agent":"cpprestsdk/2.10.18","X-Amzn-Trace-Id":"Root=1-611cbc68-27731b2a1cd55cbd682c517e","X-Bluecoat-Via":"ce2cfae06b3f12b4"},"origin":"180.xx.xx.xx","url":"http://httpbin.org/get"}

August 17, 2021 · Byung Kyu KIM