C++高并发库系列(二):在Win下用MinGWQt来编译和使用libhv

    科技2022-07-13  132

    我个人主要使用MinGW/Qt,不喜欢VS(太臃肿),所以用qmake比较多,对CMake不是很了解,编译libhv时也费了些时间,现对编译libhv遇到的问题进行解决。

    一、编译

    1、下载并解压libhv 项目地址:https://github.com/ithewei/libhv.git 码云镜像:https://gitee.com/ithewei/libhv.git 2、安装CMake 3、使用CMake环境的命令行进入libhv跟目录 4、输入命令:

    md build cd build CMake -G "MinGW Makefiles" ../

    5、等待CMake创建好Makefiles后,开始编译:

    mingw32-make

    命令后也可以加上具体的模块名,默认是编译所有模块。 6、编译到一部分模块时会出现链接错误(找不到一些符号,比如socket、send、closesocket等) 找到并打开文件:build\unittest\CMakeFiles\模块名.dir\linklibs.rsp,在最后加上 -lwsock32 -lWs2_32 -liphlpapi,保存,重新编译即可。估计有那么三四个项目需要修改一下链接库。 至此,libhv编译成功,库文件在build\lib下。

    二、使用libhv库

    新建一个console工程,将libhv项目的build文件夹中的include和lib文件夹复制到你的工程目录下,在pro文件中加上 LIBS += -L$$PWD/lib -lhv,打开main.cpp,添加代码:

    #include "include/hv/hv.h" #include "include/hv/HttpServer.h" #include "ntsecapi.h" #include <QCoreApplication> #include <QDebug> #include <WS2tcpip.h> #include <windows.h> int main(int argc, char *argv[]) { HttpService service; service.base_url = "/v1/api"; service.POST("/echo", [](HttpRequest* req, HttpResponse* res) { res->body = req->body; return 200; }); http_server_t server; server.port = 8080; server.service = &service; http_server_run(&server); QCoreApplication a(argc, argv); return a.exec(); }

    编译,出错:inet_ntop was not declared in this scope

    看了下源码,其实是有这个函数的(ws2tcpip.h中),仅当宏 _WIN32_WINNT >= 0x600时才可用,而我们的宏_WIN32_WINNT默认时0x502,在sdkddkver.h中有各类值,0x502是_WIN32_WINNT_WS03,而0x600是WIN6、VISTA、WS08、LONGHORN,所以只要是WinServer08和VISTA及以上就可以使用。我们在main.cpp中第一行加入(我的是Win7): #define _WIN32_WINNT _WIN32_WINNT_WIN7 即可。编译通过。

    参考文章

    官网

    Processed: 0.015, SQL: 8