1、安装protobuf
brew install protobuf
安装目录为/opt/homebrew/Cellar/protobuf/21.12
2、新建proto文件
在proto_output目录下新建test.proto文件
syntax="proto2";
message Person
{
repeated PhoneNumber phoneNumbers = 1;
};
message PhoneNumber
{
required string number = 1;
};
3、编译proto文件
使用命令protoc --cpp_out=./ test.proto
会在当前目录 下生成两个文件:test.pb.cc和test.pb.h
4、使用
新建main.cpp文件
#include "test.pb.h"
#include <iostream>
using namespace std;
int main()
{
test::Person person;
for (int i = 0; i < 3; i++) {
test::PhoneNumber* phoneNumber = person.add_phonenumbers();
phoneNumber->set_number("123" + i);
}
test::Person person2;
for (int i = 0; i < person.phonenumbers_size(); i++) {
test::PhoneNumber* phoneNumber = person2.add_phonenumbers();
*phoneNumber = *person.mutable_phonenumbers(i);
}
person.clear_phonenumbers();
cout << person.phonenumbers_size(); << endl;
cout << person2.phonenumbers_size(); << endl;
return 0;
}
//输出为
0
3
编译使用如下命令
g++ main.cpp test.pb.cc -o main -I /opt/homebrew/Cellar/protobuf/21.12/include -L /opt/homebrew/Cellar/protobuf/21.12/lib -lprotobuf -std=c++11