c++ protobuf 练习

c++ protobuf 练习

    • 安装proto buffer
    • 创建两个proto文件
    • 编译测试
    • 编译及运行结果

安装proto buffer

后续补上…

创建两个proto文件

  1. stu.proto (单个字段模式)
message stu
{
 optional  string name = 1;
 optional  int32 age = 2;
 optional  string addr = 3;
}
  1. stu_bat.prot (数组模式)
message student
{
 optional  string name = 1;
 optional  int32 age = 2;
 optional  string addr = 3;
}

message students
{
 repeated  student list = 1;
}
  1. 执行指令生成c++头文件,和cc文件
    protoc.exe --cpp_out=. *.proto
    生成四个文件:
    stu.pb.cc
    stu.pb.h
    stu_bat.pb.cc
    stu_bat.pb.h

编译测试

  1. 将生成的四个cpp代码拷贝到一个文件夹,进行测试
  2. 同目录下写测试代码如下:
#include
#include"stu.pb.h"
#include"stu_bat.pb.h"
using namespace std;


void fun1(){
	GOOGLE_PROTOBUF_VERIFY_VERSION;
	stu st;
	st.set_name("zzm");
	st.set_age(21);
	st.set_addr("hangzhou");
	string data_asset = st.SerializeAsString();
	cout<set_name("zzm");
	st->set_age(21);
	st->set_addr("hangzhou");
	
	auto st1 = sts.add_list();
	st1->set_name("tom");
	st1->set_age(19);
	st1->set_addr("SH");
	string data_asset = sts.SerializeAsString();
	cout<

编译及运行结果

  1. 执行指令:
    g++ *.cpp *.cc -std=c++11 -lprotobuf
    c++ protobuf 练习_第1张图片

你可能感兴趣的:(c++ protobuf 练习)