社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
首先推荐2个入门博客
安装与配置protobuf可以参考网上教程,很多很多
仿照blog1中的例子自己写一个protobuf
ackage lm;
message helloworld
{
required int32 id=1;
required string str=2;
optional int32 opt=3;
}
文件名字是:lm.helloworld.proto
protoc -I=./ --cpp_out=./ lm.helloworld.proto
自动生成2个文件
lm.helloworld.pb.cc
lm.helloworld.pb.h
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的相关库
#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
./writer
./reader
protoc: error while loading shared libraries: libprotoc.so.9: cannot open shared obje
解决方案:
linux 敲击命令:export LD_LIBRARY_PATH=/usr/local/lib
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!