protobuf windows Qt

0。编译环境: win10 x64   编译器 :mingw32  cmake 使用场景:Qt

1.准备工作:

1.下载 protobuf 最新的代码:https://github.com/google/protobuf/releases 

2.下载 cmake https://cmake.org/download/

然后点击configure按键,选择MinGW编译,默认的编译器即可,也就是QT自带的编译器,这样比较保险,如果本机还有别的MinGW版本,建议不要选,就选QT自带的编译器即可,如图所示。( 配置时要观察用的哪个 gcc 和g++ 是否为 qt自带的,此处我掉坑里了,编译器链接了我电脑上另一个版本的gcc 和 g++)

在这里插入图片描述

点击finish按键,开始配置。配置结束后,点击Grouped和Advance

在这里插入图片描述

 

点开protobuf列表,只勾选一个MSVC_STATIC_RUNTIME,如下图所示。


点击Generate生成,如图所示。


生成结束后,我们发现output330文件夹中出现了makefile文件,如图所示。


 

打开cmd,进入output330文件夹,输入mingw32-make命令,开始编译源代码,如下图所示

等待几分钟编译结束。

然后 mingw32-make  install  将库文件和头文件安装 到c盘下 我的是:C:\Program Files (x86)\protobuf

将生成的protobuf文件拷贝进  qt工程中

用 protoc --cpp_out=./ test.proto 生成文件,xx.pb.h  xx.pb.cc 

将生成的文件 加入进 qt工程中

2. 使用 protobuf 

.pro配置文件中的关键部分

win32: LIBS += -L$$PWD/protobuf/lib/ -lprotobuf
 
INCLUDEPATH += $$PWD/protobuf/include
DEPENDPATH += $$PWD/protobuf/include

test.protobuf 文件 内容

syntax = "proto2";
package mypb;
message helloworld
{
    required int32 id = 1;
    required string str = 2;
    optional int32 opt=3;
}

main .cpp 文件内容 :

#include"protobuf/test.pb.h"
using namespace std
int main(int argc, char *argv[])
{  
  QCoreApplication a(argc, argv);   
 //消息封装  
  mypb::helloworld in_msg;  
  {
        in_msg.set_id(888);
        in_msg.set_str("helloworld");
        std::fstream output("./hello.log", std::ios::out | std::ios::trunc | std::ios::binary);
        if (!in_msg.SerializeToOstream(&output)) {
            std::cerr << "failed to serialize in_msg" << std::endl;
            return -1;
        }
    }
 
    //消息解析
    mypb::helloworld out_msg;
    {
        std::fstream input("./hello.log", std::ios::in | std::ios::binary);
        if (!out_msg.ParseFromIstream(&input)) {
            std::cerr << "failed to parse" << std::endl;
            return -1;
        }
        std::cout << out_msg.id() << std::endl;
        std::cout << out_msg.str() << std::endl;
    }
 
 
    getchar();
 
    return a.exec();
}
 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值