반응형
본 문서는 'OpenSource 뜯어보기'라는 프로젝트의 일환으로.
fmt라는 C++ formatting library를 설치, 실행 등 사용하는 방법에 대해 정리해보았습니다. 해당 라이브러리는 python처럼 print를 할 수 있게 도와주는 라이브러리로 C++20 부터는 std::format으로 사용할 수 있으니 참고하시기 바랍니다.
💡 본 문서는 'OpenSource 사용하기'라는 프로젝트의 일환으로.
gRPC라는 c++ RPC library를 설치, 실행 등 사용하는 방법과 더불어, library 내 구조, 소스 분석 및 패턴 분석까지 다룰 예정이니 해당 오픈소스에 관심이 있다면 봐두길 권장합니다.
1. 오픈소스의 목적
1.1 '{fmt} C++ formatting library'란?
- Simple format API with positional arguments for localization
- Implementation of C++20 std::format
- Format string syntax similar to Python's format
- Fast IEEE 754 floating-point formatter with correct rounding, shortness and round-trip guarantees
- Safe printf implementation including the POSIX extension for positional arguments
- Extensibility: support for user-defined types
- High performance: faster than common standard library implementations of (s)printf, iostreams, to_string and to_chars, see Speed tests and Converting a hundred million integers to strings per second
- Small code size both in terms of source code with the minimum configuration consisting of just three files, core.h, format.h and format-inl.h, and compiled code; see Compile time and code bloat
- Reliability: the library has an extensive set of tests and is continuously fuzzed
- Safety: the library is fully type safe, errors in format strings can be reported at compile time, automatic memory management prevents buffer overflow errors
- Ease of use: small self-contained code base, no external dependencies, permissive MIT license
- Portability with consistent output across platforms and support for older compilers
- Clean warning-free codebase even on high warning levels such as -Wall -Wextra -pedantic
- Locale-independence by default
- Optional header-only configuration enabled with the FMT_HEADER_ONLY macro
See the documentation for more details.
See the benchmark for compare with iostream, printf
1.2 'fmt: C++ formatting library' 추가 정보
Git: https://github.com/fmtlib/fmt
- Note that master is generally a work in progress, and you probably want to use a tagged release version.
Lisence: MIT License: Copyright (c) 2012 - present, Victor Zverovich
2. 환경 구축
using CMake (FetchContent)
FetchContent_Declare(
fmt
GIT_REPOSITORY https://github.com/fmtlib/fmt.git
GIT_TAG master
)
FetchContent_MakeAvailable(fmt)
add_library(fmtlib main.cpp)
target_link_libraries(fmtlib PUBLIC fmt::fmt)
add_executable(fmtexe main.cpp)
fmt::format은 C++20을 사용한다면 std::format으로 standard library에 포함되었으니 참고바랍니다.
3. 간단한 사용
간단한 사용 (in fmt library)
Example
std::string s = fmt::format("The answer is {}.", 42);
The fmt::format function returns a string “The answer is 42.”. You can use fmt::memory_buffer to avoid constructing std::string:
auto out = fmt::memory_buffer();
format_to(std::back_inserter(out),
"For a moment, {} happened.", "nothing");
auto data = out.data(); // pointer to the formatted data
auto size = out.size(); // size of the formatted data
The fmt::print function performs formatting and writes the result to a stream:
fmt::print(stderr, "System error code = {}\n", errno);
Header
<fmt/core.h> | lightweight subset of formatting API |
<fmt/format.h> | full API = core.h + compile-time format checks, iterators, user-def. types, … |
<fmt/args.h> | core.h + dynamic format arguments |
<fmt/chrono.h> | format.h + date and time formatting |
<fmt/compile.h> | format.h + format string compilation |
<fmt/color.h> | format.h + terminal color and text style |
<fmt/os.h> | format.h + file output, system APIs |
<fmt/ostream.h> | format.h + std::ostream support |
<fmt/printf.h> | format.h + printf formatting |
<fmt/ranges.h> | format.h + formatting support for ranges and tuples |
<fmt/xchar.h> | format.h + wchar_t support |
간단한 사용 (in C++20 standard library)
#include <format>
#include <cassert>
int main() {
std::string message = std::format("The answer is {}.", 42);
assert( message == "The answer is 42." );
}
fmt library cheat sheets
참고
- [Github] fmtlib/fmt: https://github.com/fmtlib/fmt
- {fmt} A modern formatting library: https://fmt.dev/latest/index.html
- [stackoverflow] cmake add fmt library: https://stackoverflow.com/questions/66531225/cmake-add-fmt-library
- [cpp reference] cpp reference format library: https://en.cppreference.com/w/cpp/utility/format
반응형
'Study: Software(SW) > SW: Opensource' 카테고리의 다른 글
한국에 거주하는 사람들을 위한 개발자 컨퍼런스 정리 (많은 PR 부탁드립니다!) (0) | 2022.09.18 |
---|---|
[Opensource] C++ 라이브러리 추천! : cppreference.com (0) | 2022.09.11 |
[C++] C++ Json 라이브러리 변경: JsonCpp to Nlohmann/json... (0) | 2022.08.10 |
[OpenSource 사용하기] googleMock(gMock): C++ Mocking Library for googletest (0) | 2022.07.16 |
[OpenSource 사용하기] nlohmann/json: c++ json library (feat. Modern C++) (0) | 2022.07.05 |