编译protobuf
首先下载protobuf源代码
使用cmake,配置相关路径和配置
注意选择生成动态链接库,在windows上最好勾选动态链接库,否则会出现很多麻烦
点Generate,生成VS的工程文件。
然后打开vs,选择release或debug
点击解决方案直接右键选择生成解决方案即可。
注意:debug生成的库在Qt中只能在debug下使用,release生成的库只能在release下使用
Qt中使用Protobuf
编写.proto文件,使用protoc.exe编译成.h和.cc文件
将生成的.h和.cc文件复制到项目目录下
在项目根目录下新建protobuf目录,然后进入protobuf下创建include和lib目录,include目录包括protobuf源代码下的src下的google整个文件夹,lib下包括你VS编译后生成的.lib和.dll文件,在你的cmake设置的输出目录下的Debug或者release目录下,如下:
现在,创建一个Qt的widget项目,右键点击添加库
将你lib下的libprotobuf加入,include下位头文件声明
可以看到在.pro中加入了以下配置
# ==========protobuf==========
win32: LIBS += -L$$PWD/protobuf/lib/ -llibprotobuf
INCLUDEPATH += $$PWD/protobuf/include
DEPENDPATH += $$PWD/protobuf/include
然后编译时候根据你的库是release还是debug选择性编译
简单的案例
.proto 文件
syntax = "proto3";
package tutorial;
message Person {
required int32 id = 1;
required string name = 2;
optional string email = 3;
}
.pro
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = protoTest
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES +