linux下使用protobuf - Go语言中文社区

linux下使用protobuf


首先推荐2个入门博客

blog1

blog2

安装与配置protobuf可以参考网上教程,很多很多

仿照blog1中的例子自己写一个protobuf

 1 首先写一个.proto文件

ackage lm;
message helloworld
{
        required int32 id=1;
        required string str=2;
        optional int32 opt=3;
}

文件名字是:lm.helloworld.proto

2 编译该文件

protoc -I=./ --cpp_out=./ lm.helloworld.proto

自动生成2个文件

lm.helloworld.pb.cc  
lm.helloworld.pb.h

3 编写写端函数writer.cpp

include "lm.helloworld.pb.h"
#include <string>
#include <algorithm>
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
        lm::helloworld msg1;
        msg1.set_id(101);
        string str("hello");
        msg1.set_str(str);

        fstream output("./log",ios::out | ios::trunc | ios::binary);

        if(!msg1.SerializeToOstream(&output))
        {
                cerr<<"Failed!!!"<<endl;
                return -1;
        }
        return 0;
}

编译writer.cpp

g++ writer.cpp lm.helloworld.pb.cc -o writer -lprotobuf

这个过程踩过的雷

(1)直接把windons上拷贝的代拷到linux下运行提示错误

主要问题是windows和Linux的换行符不同(windows是rn,而Linux是n)导致的。

解决方案,vim进入文件中,在命令行模式下设置::set ff=unix然后保存退出即可。参考博客

(2)编译的时候没有把所有的文件都放进去

g++ writer.cpp -o writer

这是错误的,应该把.cc文件也加进去。参考博客

(3)编译的时候链接不到google的相关库

参考博客

4 编写读端函数reader.cpp

#include "lm.helloworld.pb.h"
#include <iostream>
#include <fstream>
using namespace std;

void ListMsg(const lm::helloworld &msg)
{
        cout<<msg.id()<<endl;
        cout<<msg.str()<<endl;
}

int main()
{
        lm::helloworld msg1;
        fstream input("./log",ios::in | ios::binary);
        if(!msg1.ParseFromIstream(&input))
        {
                cerr<<"Failed!!!"<<endl;
                return -1;
        }
        ListMsg(msg1);
        return 0;
}

编译reader.cpp

g++ reader.cpp lm.helloworld.pb.cc -o reader -lprotobuf

5 运行,先运行writer 在运行reader

./writer
./reader

6 如果项目中用到protobuf报错,且报错信息为

protoc: error while loading shared libraries: libprotoc.so.9: cannot open shared obje

解决方案:

linux 敲击命令:export LD_LIBRARY_PATH=/usr/local/lib

 

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_40123329/article/details/98472340
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-07 21:06:45
  • 阅读 ( 1306 )
  • 分类:Linux

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢