VS2015+QT编译protobuf库

发布于:2025-09-04 ⋅ 阅读:(18) ⋅ 点赞:(0)

VS2015+QT编译protobuf库

虽然qt有QDataStream可以进行序列化,但其他框架如果读取QDataStream序列化的数据还需要特殊处理,所以选择一个通用的框架还是有必要,于是选择了protobuf。

下载

注意 protobuf版本,最新版本不支持VS2015
选择protobuf-3.15.0或者protobuf-3.7.0
protobuf-3.15.0
protobuf-3.7.0

编译过程

编译链:cmake version 3.31.0、VS2015
首先,下载好protobuf,如protobuf-3.7.0。
然后打开cmake,要先选择源码位置(CMakeLists.txt所在位置)以及输出位置,然后点configure会弹出编译链选项,选择VS2015,win32(我是32位的,64位的就选X64),点configure,会出现以下的选项,勾选生成动态库的选项,最后点generate就会在输出目录生成protobuf.sln。用VS2015打开protobuf.sln。
在这里插入图片描述

在这里插入图片描述
在VS2015生成库完成后,可以在输出目录下找到release目录(如果选择debug编译就是在debug目录)找到生成的protobuf库和protobuf生成器。如下图:在这里插入图片描述
接下来就是测试protobuf库和protobuf生成器了。首先,要先使用protobuf.exe生成protobuf消息序列类。命令如下,SRC_DIR就是 *.proto文件所在的位置,DST_DIR是最终生成类文件的位置。所以在生成类之前还需要写一个*.proto用于声明类。
命令:

protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto
./protoc.exe -I="." --cpp_out=./ person.proto

person.proto

syntax = "proto2";

package tutorial;

message Person {
  optional string name = 1;
  optional int32 id = 2;
  optional string email = 3;

  enum PhoneType {
    PHONE_TYPE_UNSPECIFIED = 0;
    PHONE_TYPE_MOBILE = 1;
    PHONE_TYPE_HOME = 2;
    PHONE_TYPE_WORK = 3;
  }

  message PhoneNumber {
    optional string number = 1;
    optional PhoneType type = 2 [default = PHONE_TYPE_HOME];
  }

  repeated PhoneNumber phones = 4;
}

message AddressBook {
  repeated Person people = 1;
}

调用命令:./protoc.exe -I=“.” --cpp_out=./ person.proto
会生成两个文件,就是类文件。如下:
在这里插入图片描述
接下来创建qt项目文件进行测试(VS2015-32位-Release),pro文件配置如下:
注意要定义PROTOBUF_USE_DLLS,这是动态库调用必需的,反正当前版本需要

DEFINES+=PROTOBUF_USE_DLLS
INCLUDEPATH += D:/protobuf/protobuf-3.7.0/src/
#LIBS += -LD:/protobuf/protobuf-cpp-3.15.0/protobuf-3.15.0/new_build/Release -llibprotobuf -llibprotoc -lgmock -lgmock_main -llibprotobuf-lite
# 简化后的LIBS配置(只保留必要的protobuf库)
LIBS += -LD:/protobuf/protobuf-3.7.0/cmake/newbuild/Release -llibprotobuf -llibprotobuf-lite

将生成的类文件也添加进入项目里面,然后选择清除、执行qmake、构建项目。编译通过,表明库编译成功 。

参考链接

官方文档
官方编译文档
protoc 编译 javalite protobuf编译器
vs2015 编译 protobuf


网站公告

今日签到

点亮在社区的每一天
去签到