1. 创建proto文件
touch test.proto
2. 往proto文件添加内容
syntax = "proto3";
message Person
{
string name = 1;
int32 age = 18;
}
第一行表示使用proto3语法进行编译
第2-6行表示结构体内容。
3. 使用protoc对test.proto编译
protoc --cpp_out=. test.proto
其中--cpp_out表示编译后的cpp和h文件的输出目录,如果是其他语言,只需要改变cpp即可;
.表示当前目录;
后面的test.proto表示编译的源文件
整个编译语法是这样子的:
protoc -I$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/test.proto
//比如说,在当前目录下,有一个test.proto文件,使用protoc编译之后
//将cpp文件和h文件放在当前目录下
protoc -I. --cpp_out=. ./test.proto
编译成功之后,在当前目录下就会存在.cpp文件和.h文件。
4. 创建CPP文件简单使用编译好的.h文件
touch verify.cc
往里面添加内容:
#include <cstdio>
#include <iostream>
#include <string>
#include "test.pb.h"
using namespace std;
int main()
{
Person person;
person.set_name("lisi");
person.set_age(30);
string data;
if (person.SerializeToString(&data))//注意SerializeToString函数首字母全大写
{
cout << "Serialized data : " << data << endl;
}
return 0;
}
5. 编译verify.cc
g++ verify.cc -o verify
你会发现,报错了,错误信息如下:
/usr/bin/ld: /tmp/cccz9klh.o: in function `main':
/home/ubuntu/CodePractice/linux_protobuf/test.cc:14: undefined reference to `google::protobuf::MessageLite::SerializeToString(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >*) const'
/usr/bin/ld: /home/ubuntu/CodePractice/linux_protobuf/test.cc:19: undefined reference to `Person::~Person()'
/usr/bin/ld: /home/ubuntu/CodePractice/linux_protobuf/test.cc:19: undefined reference to `Person::~Person()'
/usr/bin/ld: /tmp/cccz9klh.o: in function `google::protobuf::internal::ArenaStringPtr::Set(char const*, google::protobuf::Arena*)':
/usr/local/include/google/protobuf/arenastring.h:402: undefined reference to `google::protobuf::internal::ArenaStringPtr::Set(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, google::protobuf::Arena*)'
/usr/bin/ld: /tmp/cccz9klh.o: in function `Person::Person()':
/home/ubuntu/CodePractice/linux_protobuf/test.pb.h:59: undefined reference to `Person::Person(google::protobuf::Arena*, bool)'
collect2: error: ld returned 1 exit status
解决方法:
g++ verify.cc test.pb.cc -o app -lprotobuf -std=c++11 -lpthread
6. 运行app
./app
//输出
//lisi