目录
方法一:使用 CMake 的 FetchContent(推荐)
1. 准备工作:安装 spdlog
首先,我们需要将 spdlog
添加到你的 Qt 项目中。spdlog
是一个头文件库,你可以通过以下几种方式来获取它:
方法一:使用 CMake 的 FetchContent(推荐)
如果你的 Qt 项目使用 CMake 构建,这是最简单的方法。
# 在你的 CMakeLists.txt 文件中添加以下内容
cmake_minimum_required(VERSION 3.14)
project(MyQtApp)
set(CMAKE_CXX_STANDARD 17)
# 引入 Qt
find_package(Qt5 COMPONENTS Widgets REQUIRED)
# 使用 FetchContent 下载 spdlog
include(FetchContent)
FetchContent_Declare(
spdlog
GIT_REPOSITORY https://github.com/gabime/spdlog.git
GIT_TAG v1.11.0 # 选择一个稳定的版本
)
FetchContent_MakeAvailable(spdlog)
# 添加可执行文件
add_executable(MyQtApp main.cpp mainwindow.cpp mainwindow.h mainwindow.ui)
# 链接 Qt 和 spdlog
target_link_libraries(MyQtApp PRIVATE Qt5::Widgets spdlog::spdlog)
方法二:手动下载并添加到项目中
- 前往 spdlog 的 GitHub 仓库。
- 下载最新的 release 版本(ZIP 文件)。
- 将
spdlog/include
文件夹复制到你的项目目录中(例如,放在external/spdlog
)。 - 在你的
CMakeLists.txt
中添加如下内容:
# 添加 spdlog 的包含路径
include_directories(${CMAKE_SOURCE_DIR}/external/spdlog/include)
# 假设你不需要构建 spdlog 库,而是作为头文件库使用
add_executable(MyQtApp main.cpp mainwindow.cpp mainwindow.h mainwindow.ui)
# 链接 Qt
target_link_libraries(MyQtApp PRIVATE Qt5::Widgets)
2. 在 Qt 项目中集成 spdlog
假设你已经将 spdlog
添加到项目中,接下来我们来配置和使用它。
a. 初始化 spdlog
在你的 Qt 项目的入口处( main.cpp
),初始化 spdlog
:
// main.cpp
#include <QApplication>
#include "mainwindow.h"
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
// 初始化 spdlog
try {
// 创建一个同时输出到控制台和文件的 logger
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();