Linux下protobuf的简单使用

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

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值