网络库:libuv
- Qt 版本:5.14.2,使用 mingw 32 位编译器构建工程
- libuv 版本:v1.44.2: 2022.07.12, Version 1.44.2 (Stable)
- 下载libuv源码
- 当然可以直接将 include 和 src 文件夹扔到工程路径下直接构建项目,但是每次重构都很花时间,所以还是得学学 库链接 方式
- 按照文档使用
cmake进行编译,注意使用的编译器是 msvc 还是 mingw ,比如 QT 常用的是 mingw ,最好指定 mingw 进行编译( windows 下cmake默认使用 msvc ),神奇的是, msvc 编译出的 动态库 是能够套在 Qt Creator 的 mingw 下直接构建的。( 注意编译 32 还是 64 位的库,本教程为 32 位 )
$ mkdir -p build
# cd 进文件夹后,指定mingw编译器-> cmake -G"MinGW Makefiles" ..
$ (cd build && cmake .. -DBUILD_TESTING=ON) # generate project with tests
$ cmake --build . # add `-j <n>` with cmake >= 3.12
# 以下为附加内容,仅需执行上面三行
# Run tests:
$ (cd build && ctest -C Debug --output-on-failure)
# Or manually run tests:
$ build/uv_run_tests # shared library build
$ build/uv_run_tests_a # static library build
- 会在 build 文件夹下生成所需的文件:
libuv.dll和libuv.dll.a是动态链接需要的文件(libuv.dll.a是动态链接需要的静态库导引文件)libuv_a.a就是静态链接的库文件了
动态链接
- 步骤:将 include 文件夹和
libuv.dll和libuv.dll.a都扔到工程路径下(建个 .pri 文件进行管理)-> 写 .pri 文件 -> 添加库函数测试代码 -> 构建成功后将libuv.dll文件扔到 .exe 文件路径下 -> 运行 - 其实直接在 Qt Creator 右键工程,添加库,完成添加即可,但手写也行
INCLUDEPATH += \
$$PWD/libuv/include
DEPENDPATH += \
$$PWD/libuv/include
win32: LIBS += -L$$PWD/libuv/lib/ -luv.dll
- 最后记得将
libuv.dll文件扔到 .exe 文件路径下再运行
静态链接
- 静态库链接方式有所不同,需要特别注意,直接看 .pri 文件代码
INCLUDEPATH += \
$$PWD/libuv/include
DEPENDPATH += \
$$PWD/libuv/include
win32: LIBS += -L$$PWD/libuv/lib/ -luv_a
# 下面这些库是必要的,不加会报错,例如:uv-common.c:-1: error: undefined reference to `_imp__htons@4'
win32 {
LIBS += -lws2_32
LIBS += -lUserEnv
LIBS += -lIPHLPAPI
LIBS += -lPsapi
LIBS += -ladvapi32
LIBS += -lUser32
LIBS += -lGdi32
}
libuv_a.a是静态库文件- 注意:Qt Creator 在
Desktop_Qt_5_14_2_MinGW_32_bit-Debug下链接 64 位的库,会报错:
:-1: error: skipping incompatible D:\xiangmu\01_Qt\LQChat\SDK\libuv\lib/libuv_a.a when searching for -luv_a
测试代码
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
// QApplication a(argc, argv);
// MainWindow w;
cout << "print cout success!";
// w.show();
// return a.exec();
#if 1
/// \test 测试libuv库
uv_loop_t* loop = uv_default_loop();
uv_loop_init(loop);
printf("Now quitting.\n");
// 创建一个定时器
uv_timer_t timer;
uv_timer_init(loop, &timer);
timer.data = nullptr;
// 设置回调函数
uv_timer_start(&timer, [](uv_timer_t* handle) {
MYLOG << "Hello World!";
}, 0, 1000);
uv_run(loop, UV_RUN_DEFAULT); // 重中之重
return 0;
#endif
}