两个好用的C++库

liminjun

最近在学习envoy 的源码,发现里面引用的JSON解析和日志记录的库挺好用的,这里简单记录一下

库源码地址

简单调用

环境基于wsl的ubuntu22.04环境

库函数安装

1
2
sudo apt install libspdlog-dev
sudo apt install nlohmann-json3-dev

spdlog库调用

这里使用cmake管理工程

1
2
3
4
5
6
7
8
9
10
11
12
cmake_minimum_required(VERSION 3.15)

project(cpp_test)

#/usr/lib/x86_64-linux-gnu/cmake
find_package(spdlog REQUIRED)
find_package(FMT REQUIRED)

add_executable(main main.cpp)

target_link_libraries(main spdlog)
target_link_libraries(main fmt::fmt)

测试代码(直接拷贝的例子)

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
#include "spdlog/spdlog.h"

int main(int argc, char const *argv[])
{
// change log pattern
spdlog::set_pattern("[%H:%M:%S %z] [%n] [%^---%L---%$] [thread %t] %v");

spdlog::info("Welcome to spdlog!");
spdlog::error("Some error message with arg: {}", 1);

spdlog::warn("Easy padding in numbers like {:08d}", 12);
spdlog::critical("Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}", 42);
spdlog::info("Support for floats {:03.2f}", 1.23456);
spdlog::info("Positional args are {1} {0}..", "too", "supported");
spdlog::info("{:<30}", "left aligned");

spdlog::set_level(spdlog::level::debug); // Set global log level to debug
spdlog::debug("This message should be displayed..");

// Compile time log levels
// define SPDLOG_ACTIVE_LEVEL to desired level
SPDLOG_TRACE("Some trace message with param {}", 42);
SPDLOG_DEBUG("Some debug message");
return 0;
}

文档地址:https://github.com/gabime/spdlog/wiki/1.-QuickStart

使用还是比较简单的,也能满足90%的日志打印需求

nlohman-json库调用

测试代码(也是直接拷贝的例子)

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
31
32
33
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;

int main(int argc, char const *argv[])
{
json ex1 = json::parse(R"(
{
"pi": 3.141,
"happy": true
}
)");

assert(ex1["pi"] == 3.141);

json ex2 = R"(
{
"pi": 3.141,
"happy": true
}
)"_json;

assert(ex2["pi"] == 3.141);

json ex3 = {
{"happy", true},
{"pi", 3.141},
};

assert(ex3["pi"] == 3.141);

return 0;
}

文档地址:Overview - JSON for Modern C++ (nlohmann.me)

使用也是非常简单,后面有空对比下几个json解析库的性能

  • Title: 两个好用的C++库
  • Author: liminjun
  • Created at: 2023-05-16 11:59:20
  • Updated at: 2023-05-16 12:20:29
  • Link: https://olldbg.github.io/2023/05/16/两个好用的C-库/
  • License: This work is licensed under CC BY-NC-SA 4.0.