Golang GC

Golang GC (가비지 컬렉터) 주요 내용 Golang GC : GOGC 유효하지 않는 메모리(Dangling Object)를 주기적으로 해제하는 기법 Java의 Parallel GC, G1GC 와 유사하나 구현 방식에서 차이가 있음 Stop-the-World 시간을 최소화하도록 설계됨 Tri-Color Algorithm 사용 동시성을 고려한 효율적인 메모리 관리 알고리즘 CMS (Concurrent Mark and Sweep) 방식 운영 Java 와 같은 Generation GC 기법이나 Compaction은 지원하지 않음 대신 더 효율적인 메모리 할당 전략을 사용 Compaction (압축, 재배치) 가 없음 재배치를 하지 않는 대신 TCMalloc를 통한 메모리 할당 관리 메모리 단편화를 최소화하고 빠른 할당을 지원 멀티쓰레드 최적화 힙 메모리 할당기 - tcmalloc. jemalloc{:target="_blank"} Tri-Color Algorithm 동작 원리 white, black, grey 세 가지 상태를 통한 메모리 관리 ...

December 1, 2021 · Byung Kyu KIM

Python asyncio

asyncio는 async/await 구문을 사용하여 동시성 코드를 작성하는 라이브러리입니다. 특히 I/O 작업이 많은 애플리케이션에서 높은 성능을 발휘합니다. asyncio : asynchronous io 처리 https://docs.python.org/ko/3/library/asyncio.html{:target="_blank"} Threading 동시성 제어는 GIL (Global interpreter lock) 제약에 의해 느리고, 복잡도는 그대로 가지고 있음 GIL은 Python 인터프리터가 한 번에 하나의 스레드만 실행할 수 있도록 제한하는 메커니즘 멀티스레드를 사용해도 CPU 연산의 실제 병렬 처리가 어려움 IO 병목에 의한 동시성을 관리하기 위한 도구로서 Coroutine을 통한 관리 네트워크 요청, 파일 읽기/쓰기 등 I/O 작업에서 효율적 코루틴은 스레드보다 가벼워서 수천 개의 동시 작업도 효율적으로 처리 가능 일반적인 Coroutine 코드 Coroutine으로 실행 되기는 하나, 비동기로 실행 되지는 않음 async def로 정의된 함수는 코루틴 함수가 됨 await는 다른 코루틴의 실행이 완료될 때까지 대기 asyncio.sleep()은 I/O 작업을 시뮬레이션하는 용도로 자주 사용됨 import asyncio from datetime import datetime def time_log(step): print(datetime.now().strftime('%H:%M:%S'), step) async def async_sleep(): await asyncio.sleep(2) time_log('async_sleep') async def async_execute(): time_log('start') await async_sleep() await async_sleep() time_log('end') def main(): asyncio.run(async_execute()) if __name__ == '__main__': main() [Running] set PYTHONIOENCODING=utf8 && python -u tempCodeRunnerFile.python 11:39:00 start 11:39:02 async_sleep 11:39:04 async_sleep 11:39:04 end 실행 결과를 보면 start -> 2초 대기 -> async_sleep -> 2초 대기 -> async_sleep -> end 순서로 순차 실행됨을 알 수 있습니다. ...

October 31, 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

CryotoPP Example

CryptoPP https://www.cryptopp.com/{:target="_blank"} Crypto++ 사용하기, 예제{:target="_blank"} 암호화 지식 (개발자){:target="_blank"} 기존 작성한 내용(5.6 버전)의 최신화(8.5 버전) : 빌드 이슈 Package 설치 vcpkg 사용 : 8.5.0 $ ./vcpkg install cryptopp Computing installation plan... The following packages will be built and installed: cryptopp[core]:arm64-osx -> 8.5.0 ... The package cryptopp:arm64-osx provides CMake targets: find_package(cryptopp CONFIG REQUIRED) target_link_libraries(main PRIVATE cryptopp-static) 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 -Wall -O2) find_package(cryptopp CONFIG REQUIRED) target_link_libraries(main PRIVATE cryptopp-static) Build $ mkdir build && cd build $ cmake .. -DCMAKE_TOOLCHAIN_FILE=<PATH>/vcpkg/scripts/buildsystems/vcpkg.cmake $ build Example 기본 Flow - Encryption : StringSource -> StreamTransformationFilter(Encryptor) -> Base64Encoder(StringSink) - Decryption : StringSource -> Base64Decoder -> StreamTransformationFilter(Decryptor, StringSink) 과거 버전과의 이슈 std::byte의 표준화 이전에 작성된 라이브러리라, byte 타입 충돌 https://www.cryptopp.com/wiki/Modes_of_Operation{:target="_blank"} KEY, IV 를 정의하기 위해 CryptoPP::SecByteBlock 타입 사용 #include <iostream> #include <algorithm> using namespace std; #include <cryptopp/cryptlib.h> #include <cryptopp/base64.h> #include <cryptopp/aes.h> #include <cryptopp/seed.h> #include <cryptopp/des.h> #include <cryptopp/modes.h> #include <cryptopp/filters.h> template <class EncryptorType> std::string Encrypt(EncryptorType &encryptor, const std::string &PlainText) { std::string CipherText; CryptoPP::StringSource(PlainText, true, new CryptoPP::StreamTransformationFilter( encryptor, new CryptoPP::Base64Encoder(new CryptoPP::StringSink(CipherText), false) /* default padding */ ) ); return CipherText; } template <class DecryptorType> std::string Decrypt(DecryptorType &decryptor, const std::string &EncText) { std::string PlainText; CryptoPP::StringSource(EncText, true, new CryptoPP::Base64Decoder( new CryptoPP::StreamTransformationFilter( decryptor, new CryptoPP::StringSink(PlainText) ) ) ); return PlainText; } int main() { using namespace std; using AES = CryptoPP::AES; CryptoPP::SecByteBlock KEY(AES::DEFAULT_KEYLENGTH); CryptoPP::SecByteBlock IV(AES::DEFAULT_KEYLENGTH); // 임의 값 초기화 for (auto &c : KEY) c = 0; for (auto &c : IV) c = 0; CryptoPP::CBC_Mode<AES>::Encryption Encryptor { KEY, KEY.size(), IV }; CryptoPP::CBC_Mode<AES>::Decryption Decryptor { KEY, KEY.size(), IV }; try { string sText = "Plain Text"; string sEnc, sDec; sEnc = Encrypt(Encryptor, sText); cout << sText << " -> " << sEnc << endl; sDec = Decrypt(Decryptor, sEnc); cout << sEnc << " -> " << sDec << endl; } catch (exception &ex) { cerr << ex.what() << endl; } return 0; } $ ./main Plain Text -> MtiafY0csWZJZzsRNfE8cA== MtiafY0csWZJZzsRNfE8cA== -> Plain Text

August 28, 2021 · Byung Kyu KIM

GCC 설치 (`macOS`, `Windows`)

macOS 및 Windows 에 GCC 설치하기 MAC OS brew : macOS 용 패키지 관리자 https://brew.sh/index_ko{:target="_blank"} brew 사용 gcc 설치 Command line tools 설치 xcode 없이 개발툴 설치 $ xcode-select --install clang 이 설치되고 gcc로 심볼링 링크 걸려 있음 $ gcc -v Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1 Apple clang version 12.0.5 (clang-1205.0.22.11) Target: arm64-apple-darwin20.6.0 Thread model: posix InstalledDir: /Library/Developer/CommandLineTools/usr/bin GCC (G++) 설치 # 특정 버전으로 설치 가능 $ brew search gcc ==> Formulae gcc gcc@5 gcc@8 libgccjit ghc ncc gcc@10 gcc@6 gcc@9 x86_64-elf-gcc scc gcc@4.9 gcc@7 i686-elf-gcc grc tcc ==> Casks gcc-arm-embedded # 기본(최신) 버전 설치 $ brew install gcc ==> Auto-updated Homebrew! Updated 1 tap (homebrew/core). ==> Updated Formulae Updated 1 formula. ==> Downloading https://ghcr.io/v2/homebrew/core/gcc/manifests/11.2.0 Already downloaded: /Users/cdecl/Library/Caches/Homebrew/downloads/210783e77b227b8210d559abfe3514cdb95c915619fa3f785ad212120d6a36f9--gcc-11.2.0.bottle_manifest.json ==> Downloading https://ghcr.io/v2/homebrew/core/gcc/blobs/sha256:23ec727fa684a9f65cf9f55d61d208486d5202fb6112585a01426a Already downloaded: /Users/cdecl/Library/Caches/Homebrew/downloads/8d1fae8a356d50aa911004b768eff64c241e170ce9be66e684b819fc4f67fc7c--gcc--11.2.0.arm64_big_sur.bottle.tar.gz ==> Pouring gcc--11.2.0.arm64_big_sur.bottle.tar.gz 🍺 /opt/homebrew/Cellar/gcc/11.2.0: 1,412 files, 339.5MB 심볼릭링크 설정 및 PATH 설정 $ cd /opt/homebrew/Cellar/gcc/11.2.0 $ ls -l ... -rwxr-xr-x 1 cdecl admin 1.7M 8 28 13:41 g++-11 -rwxr-xr-x 1 cdecl admin 1.7M 8 28 13:41 gcc-11 ... $ ln -s g++-11 g++ $ ln -s gcc-11 gcc .zshrc or .bashrc export PATH=/opt/homebrew/Cellar/gcc/11.2.0/bin:$PATH $ g++ -v Using built-in specs. COLLECT_GCC=g++ COLLECT_LTO_WRAPPER=/opt/homebrew/Cellar/gcc/11.2.0/libexec/gcc/aarch64-apple-darwin20/11.1.0/lto-wrapper Target: aarch64-apple-darwin20 Configured with: ../configure --prefix=/opt/homebrew/Cellar/gcc/11.2.0 --libdir=/opt/homebrew/Cellar/gcc/11.2.0/lib/gcc/11 --disable-nls --enable-checking=release --enable-languages=c,c++,objc,obj-c++,fortran --program-suffix=-11 --with-gmp=/opt/homebrew/opt/gmp --with-mpfr=/opt/homebrew/opt/mpfr --with-mpc=/opt/homebrew/opt/libmpc --with-isl=/opt/homebrew/opt/isl --with-zstd=/opt/homebrew/opt/zstd --with-pkgversion='Homebrew GCC 11.2.0' --with-bugurl=https://github.com/Homebrew/homebrew-core/issues --build=aarch64-apple-darwin20 --with-system-zlib --disable-multilib --with-native-system-header-dir=/usr/include --with-sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk Thread model: posix Supported LTO compression algorithms: zlib zstd gcc version 11.1.0 (Homebrew GCC 11.2.0) Windows chocolatey chocolatey : Windows 용 패키지 관리자 https://chocolatey.org/{:target="_blank"} choco 사용 gcc 설치 GCC (G++) 설치 패키지가 2개중에 하나 선택 mingw : https://community.chocolatey.org/packages/mingw{:target="_blank"} winlibs : https://community.chocolatey.org/packages/winlibs{:target="_blank"} winlibs가 버전이 높고 mingw는 버전인 올라가면서 posix thread가 문제가 있음 ...

August 27, 2021 · Byung Kyu KIM

Golang, Cgo

Cgo enables the creation of Go packages that call C code. Cgo https://pkg.go.dev/cmd/cgo{:target="_blank"} Golang에서 C 코드를 통합 할 수 있도록 만든 의사 패키지 C코드 - Go 파일 통합 예제 import "C" 바로 윗 부분의 주석 /* */ or // 으로 C코드 작성 C 함수, 변수 영역 접근시, C 의 패키지 명으로 접근 함수, 변수선언, #include 선행처리지시자 등 일반적인 C 코드 cgo Cheat Sheet : https://gist.github.com/zchee/b9c99695463d8902cd33{:target="_blank"} package main /* #include <stdio.h> // printf #include <stdlib.h> // free (C.free) void println(const char *s) { printf("%s\n", s); } */ import "C" import ( "fmt" "unsafe" ) func main() { s := C.CString("c lang println") C.free(unsafe.Pointer(s)) C.println(s) fmt.Println("golang println") } $ go mod init main $ go build $ ./main c lang println golang println C코드 통합 - 별도 파일(C/C++)로 구성 같은 디렉토리의 C/C++ file extention 의 경우 기본 gcc(g++)로 빌드 및 링크 별도 파일의 경우 C++ 코드도 작성이 가능하나, golang 에서는 C언어 (Name mangling) 방식만 지원 Name mangling: 컴파일러가 함수명이나 변수이름을 특정한 규칙으로 변경 C++의 경우는 함수 Overloading으로 인해 C언어와 규칙이 다름 extern "C": C언어 방식의 Name mangling으로 처리 $ tree ├── go.mod ├── main.go └── print.cpp package main // #include <stdlib.h> // free // void println(char *s); import "C" import ( "fmt" "unsafe" ) func main() { s := C.CString("cpp println") C.free(unsafe.Pointer(s)) C.println(s) fmt.Println("golang println") } #include <iostream> using namespace std; extern "C" void println(const char *s); void println(const char *s) { cout << s << endl; } $ go build $ ./main cpp println Static, Dynamic library link $ tree ├── go.mod ├── main.go └── native ├── print.cpp └── print.h // print.h #pragma once #ifdef __cplusplus extern "C" { #endif void println(const char *s); #ifdef __cplusplus } #endif // print.cpp #include <iostream> #include "print.h" void println(const char *s) { std::cout << s << std::endl; } #cgo LDFLAG: 컴파일러 라이브러리 링크 옵션 지정 #cgo CFLAGS: 컴파일러 컴파일 옵션 package main // #cgo LDFLAGS: -Lnative -lprint -lstdc++ // #include <stdlib.h> // #include "native/print.h" import "C" import ( "fmt" "unsafe" ) func main() { s := C.CString("cpp println") C.free(unsafe.Pointer(s)) C.println(s) fmt.Println("golang println") } Static link $ cd native $ g++ -c print.cpp $ ar -cr libprint.a print.o $ cd .. $ go build $ ./main cpp println golang println Dynamic Link $ cd native $ g++ -dynamic -fPIC -o libprint.so -c libprint.cpp $ cd .. $ go build # Mac : export DYLD_LIBRARY_PATH=$(pwd)/native $ export LD_LIBRARY_PATH=/root/cgo/native $ ./main cpp println golang println 의존성 확인 Linux $ ldd ./main linux-vdso.so.1 (0x0000ffff9446a000) libprint.so => /root/cgo/native/libprint.so (0x0000ffff94428000) libpthread.so.0 => /lib/aarch64-linux-gnu/libpthread.so.0 (0x0000ffff943f7000) libc.so.6 => /lib/aarch64-linux-gnu/libc.so.6 (0x0000ffff94281000) libstdc++.so.6 => /usr/lib/aarch64-linux-gnu/libstdc++.so.6 (0x0000ffff940a9000) /lib/ld-linux-aarch64.so.1 (0x0000ffff9443a000) libm.so.6 => /lib/aarch64-linux-gnu/libm.so.6 (0x0000ffff93ffe000) libgcc_s.so.1 => /lib/aarch64-linux-gnu/libgcc_s.so.1 (0x0000ffff93fda000) Mac $ otool -L ./main ./main: libprint.so (compatibility version 0.0.0, current version 0.0.0) /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 905.6.0) /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation (compatibility version 150.0.0, current version 1775.118.101) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1292.100.5) 예제 : char * 다루기 - string → *C.char : C.CString(string) // C.free(unsafe.Pointer(*C.char)) 메모리 해제 필수 - *C.char → string : C.GoString(*C.char) - []C.char' : byte slice → *C.char // buff := make([]byte, 128), (*C.char)(unsafe.Pointer(&buff[0])) - *C.char, C.int → string : C.GoStringN(*C.char, C.int) package main /* #include <stdlib.h> #include <string.h> */ import "C" import ( "fmt" "unsafe" ) func getptr(buff []byte) *C.char { return (*C.char)(unsafe.Pointer(&buff[0])) } func main() { buff := make([]byte, 128) s := C.CString("Hello") defer C.free(unsafe.Pointer(s)) C.strcpy(getptr(buff), s) fmt.Println(string(buff)) }

August 23, 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

Makefile Simple Template

Makefile 간단한 범용 버전 Makefile 현재 디렉토리 모든 .cpp 파일 빌드 CC = g++ CC_FLAGS = -std=c++11 -pedantic -Wall -O2 LD_LIBS = EXEC = main SOURCES = $(wildcard *.cpp) OBJECTS = $(SOURCES:.cpp=.o) # Main target $(EXEC): $(OBJECTS) $(CC) $(OBJECTS) -o $(EXEC) $(LD_LIBS) %.o: %.cpp $(CC) -c $(CC_FLAGS) $< -o $@ clean: rm -f $(EXEC) $(OBJECTS)

August 13, 2021 · Byung Kyu KIM