DrawingProcess
드프 DrawingProcess
DrawingProcess
전체 방문자
오늘
어제
«   2025/06   »
일 월 화 수 목 금 토
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
  • 분류 전체보기 (964)
    • Profile & Branding (22)
      • Career (15)
    • IT Trends (254)
      • Conference, Faire (Experien.. (31)
      • News (187)
      • Youtube (19)
      • TED (8)
      • Web Page (2)
      • IT: Etc... (6)
    • Contents (97)
      • Book (66)
      • Lecture (31)
    • Project Process (94)
      • Ideation (0)
      • Study Report (34)
      • Challenge & Award (22)
      • 1Day1Process (5)
      • Making (5)
      • KRC-FTC (Team TC(5031, 5048.. (10)
      • GCP (GlobalCitizenProject) (15)
    • Study: ComputerScience(CS) (72)
      • CS: Basic (9)
      • CS: Database(SQL) (5)
      • CS: Network (14)
      • CS: OperatingSystem (3)
      • CS: Linux (39)
      • CS: Etc... (2)
    • Study: Software(SW) (95)
      • SW: Language (29)
      • SW: Algorithms (1)
      • SW: DataStructure & DesignP.. (1)
      • SW: Opensource (15)
      • SW: Error Bug Fix (43)
      • SW: Etc... (6)
    • Study: Artificial Intellige.. (149)
      • AI: Research (1)
      • AI: 2D Vision(Det, Seg, Tra.. (35)
      • AI: 3D Vision (70)
      • AI: MultiModal (3)
      • AI: SLAM (0)
      • AI: Light Weight(LW) (3)
      • AI: Data Pipeline (7)
      • AI: Machine Learning(ML) (1)
    • Study: Robotics(Robot) (33)
      • Robot: ROS(Robot Operating .. (9)
      • Robot: Positioning (8)
      • Robot: Planning & Control (7)
    • Study: DeveloperTools(DevTo.. (83)
      • DevTool: Git (12)
      • DevTool: CMake (13)
      • DevTool: NoSQL(Elastic, Mon.. (25)
      • DevTool: Container (17)
      • DevTool: IDE (11)
      • DevTool: CloudComputing (4)
    • 인생을 살면서 (64)
      • 나의 취미들 (7)
      • 나의 생각들 (42)
      • 여행을 떠나자~ (10)
      • 분기별 회고 (5)

개발자 명언

“ 매주 목요일마다 당신이 항상 하던대로 신발끈을 묶으면 신발이 폭발한다고 생각해보라.
컴퓨터를 사용할 때는 이런 일이 항상 일어나는데도 아무도 불평할 생각을 안 한다. ”

- Jef Raskin

맥의 아버지 - 애플컴퓨터의 매킨토시 프로젝트를 주도

인기 글

최근 글

최근 댓글

티스토리

hELLO · Designed By 정상우.
DrawingProcess

드프 DrawingProcess

[OpenSource 사용하기] fmt: C++ formatting library (feat. python styled print)
Study: Software(SW)/SW: Opensource

[OpenSource 사용하기] fmt: C++ formatting library (feat. python styled print)

2022. 8. 18. 17:11
반응형
본 문서는 '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

 

GitHub - fmtlib/fmt: A modern formatting library

A modern formatting library. Contribute to fmtlib/fmt development by creating an account on GitHub.

github.com

 

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
    'Study: Software(SW)/SW: Opensource' 카테고리의 다른 글
    • 한국에 거주하는 사람들을 위한 개발자 컨퍼런스 정리 (많은 PR 부탁드립니다!)
    • [Opensource] C++ 라이브러리 추천! : cppreference.com
    • [C++] C++ Json 라이브러리 변경: JsonCpp to Nlohmann/json...
    • [OpenSource 사용하기] googleMock(gMock): C++ Mocking Library for googletest
    DrawingProcess
    DrawingProcess
    과정을 그리자!

    티스토리툴바