使用conan安装并使用Spdlog

发布时间 2023-12-15 11:51:13作者: 料峭春风吹酒醒

Introduce

Very fast, header-only/compiled, C++ logging library.

https://github.com/gabime/spdlog.git

Install

Header-only version

复制include文件夹到你的项目中,并使用C++11。

$ git clone https://github.com/gabime/spdlog.git
$ cd spdlog && mkdir build && cd build
$ cmake .. && make -j

在CMake项目中使用spdlog

# CMakeLists.txt
# Copyright(c) 2019 spdlog authors Distributed under the MIT License (http://opensource.org/licenses/MIT)

cmake_minimum_required(VERSION 3.11)
project(spdlog_examples CXX)

if(NOT TARGET spdlog)
    # Stand-alone build
    find_package(spdlog REQUIRED)
endif()

# ---------------------------------------------------------------------------------------
# Example of using pre-compiled library
# ---------------------------------------------------------------------------------------
add_executable(example example.cpp)
target_link_libraries(example PRIVATE spdlog::spdlog $<$<BOOL:${MINGW}>:ws2_32>)

# ---------------------------------------------------------------------------------------
# Example of using header-only library
# ---------------------------------------------------------------------------------------
if(SPDLOG_BUILD_EXAMPLE_HO)
    add_executable(example_header_only example.cpp)
    target_link_libraries(example_header_only PRIVATE spdlog::spdlog_header_only)
endif()

Conan Install

创建一个cmake项目,并添加官方例子,这里删减了一部分

#include "spdlog/spdlog.h"
#include "spdlog/cfg/env.h"  // support for loading levels from the environment variable
#include "spdlog/fmt/ostr.h" // support for user defined types

int main(int, char *[])
{
    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("{:>8} aligned, {:<8} aligned", "right", "left");
    spdlog::shutdown();
	  return 0;
}

编写一个最简化的CMakeLists.txt

cmake_minimum_required(VERSION 3.15)
project(spdlogDemo CXX)
add_executable(${PROJECT_NAME} src/main.cpp)

有序项目引用了第三方库spdlog,需要再在CMakeLists.txt中配置依赖,这里使用conan安装spdlog。详情可以参考conan.id

首先创建一个conanfile.txt

[requires]
spdlog/1.12.0
[generators]
CMakeDeps
CMakeToolchain

然后使用conan安装依赖

cd project_folder
conan install . --output-folder=build --build=missing

之后在cmake的过程中使用conan的工具链

cd build
cmake .. -DCMAKE_TOOLCHAIN_FILE=conan_toolchain.cmake -DCMAKE_BUILD_TYPE=Release
cmake --build . --config=Release

此时构建会出问题的,这毋庸置疑,因为还没有将可执行程序链接到spdlog库以及头文件路径也没有设置。

对CMakeLists.txt作出一些修改:

cmake_minimum_required(VERSION 3.15)
project(spdlogDemo CXX)
find_package(spdlog REQUIRED) # 1 查找spdlog
add_executable(${PROJECT_NAME} src/main.cpp)
target_link_libraries(${PROJECT_NAME} spdlog::spdlog) # 2 链接spdlog

需要注意的是,链接的目标spdlog::spdlog可以在cmake过程日志中查看到,如下:

编译成功后查看运行结果