protobuf安装、编译和使用

protobuf使用简单示例

一.安装

首先下载protobuf的安装包,我这里使用的是protobuf-cpp-3.21.5.tar.gz

  1. 解压安装包

    tar -xzf protobuf-cpp-3.21.5.tar.gz
    
  2. 进入解压后的文件夹

    cd protobuf-3.21.5/
    
  3. 生成Makefile文件

    ./configure --prefix=/home/tdx/software/protobuf/protobuf-install
    
  4. 执行make编译

    make
    make check
    
  5. 安装

    make install
    

    ​ 可以看到在/home/tdx/software/protobuf/protobuf-install目录下有bin、include和lib目录。可以把include目录下的文件都按照该目录结构和lib/libprotobuf.a复制到所需要的目录中去,这样就可以开始写示例程序了。

二.编写示例程序

​ 创建一个protobuf_demo目录,将/home/tdx/software/protobuf/protobuf-install目录中的include和lib/libprotobuf.a拷贝到该目录下(注:lib目录下只保留libprotobuf.a静态库,不要留有动态库,否则后面链接会出现问题)。

  1. 编写Mymessage.proto代码
package Im;
message Content{
	required int32  id = 1;     //ID
  	required string str = 2;    //str
	optional int32  opt = 3;    //optional field
}
  1. 编写Writer.cpp代码
#include <iostream>
#include <fstream>
#include "Mymessage.pb.h"
using namespace std;
int main(){
	Im::Content msg1;
	msg1.set_id(101);
	msg1.set_str("zhangsan");
	fstream output("./log", ios::out | ios::trunc | ios::binary);
	if(!msg1.SerializeToOstream(&output)){
		cerr << "Failed to write msg." << endl;
		return -1;
	}
	return 0;
}
  1. 编写Reader.cpp代码
#include <iostream>
#include <fstream>
#include "Mymessage.pb.h"
using namespace std;
void ListMsg(const Im::Content &msg){
	cout << msg.id() << endl;
	cout << msg.str() << endl;
}

int main(){
	Im::Content msg1;
	fstream input("./log", ios::in | ios::binary);
	if(!msg1.ParseFromIstream(&input)){
		cerr << "Failed to parse address book." << endl;
		return -1;
	}
	ListMsg(msg1);
	return 0;
}
  1. 编写Makefile文件
INC=/home/tdx/Desktop/study/protobuf_demo/include
LIB=/home/tdx/Desktop/study/protobuf_demo/lib

lib=protobuf

all:Writer Reader

Writer.o:Writer.cpp
    g++ -g -c Writer.cpp -I$(INC) -L$(LIB) -l$(lib)

Reader.o:Reader.cpp
    g++ -g -c Reader.cpp -I$(INC) -L$(LIB) -l$(lib)

Writer:Writer.o Mymessage.pb.o
    g++ -g -o Writer Writer.o Mymessage.pb.o -I$(INC) -L$(LIB) -l$(lib)

Reader:Reader.o Mymessage.pb.o
    g++ -g -o Reader Reader.o Mymessage.pb.o -I$(INC) -L$(LIB) -l$(lib)

Mymessage.pb.o:Mymessage.pb.cc
    g++ -g -c Mymessage.pb.cc -I$(INC) -L$(LIB) -l$(lib)

clean:Writer Reader Writer.o Reader.o Mymessage.pb.o
    rm -rf Writer Reader Writer.o Reader.o Mymeaasge.pb.o

​ 执行:

/home/tdx/software/protobuf/protobuf-install/bin/protoc -I=./ --cpp_out=./ Mymessage.proto

​ 此时会生成Mymessage.pb.h和Mymessage.pb.cc文件。再执行make命令,生成Writer和Reader文件。执行./Writer命令后,再执行./Reader命令,终端上输出:

101
zhangsan

参考:《后台开发 核心技术与实践》
​ 关于protobuf的详细应用查阅相关文档,未完待续......

posted @   muxisuibi  阅读(1460)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-08-23 linux中文件内核数据结构
点击右上角即可分享
微信分享提示