Caffe-----ProtoBuffer ,How to use protobuffer in Ubuntu

本文详细介绍如何下载并安装Protobuf 2.5.0版本,包括配置环境变量及验证安装。通过一个简单的示例展示了如何创建.proto文件定义消息结构,并生成对应的C++代码,最后演示了数据的写入与读取过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Download Protobuffer

$wget http://protobuf.googlecode.com/files/protobuf-2.5.0.tar.gz 

unzip

$tar xvzf protobuf-2.5.0.tar.gz  


intstall

$./configure

$make

$make check

$make install

$vim ./profile

add

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

$source ./profile

$protoc --version


run a example

vim lm.helloworld.proto

i

package lm;
message helloworld{
        required int32 id=1;//ID
        required string str=2;//str
        optional int32 opt=3;//optional field

}

然后生成对应的cpp和h文件

protoc lm.helloworld.proto // --cpp_out=./out


$vim Writer.cpp

#include "lm.helloworld.pb.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
        lm::helloworld msg1;
        msg1.set_id(101);
        msg1.set_str("hello");

        fstream output("./log",ios::out|ios::trunc|ios::binary);
        if(!msg1.SerializeToOstream(&output)){
                cerr<<"Failed to write msg."<<endl;
                return -1;
        }
        return 0;
}

$g++ Writer.cpp lm.helloworld.pb.cc `pkg-config --cflags --libs protobuf` -o writer 


$vim Reader.cpp

#include "lm.helloworld.pb.h"
#include <fstream>
#include <iostream>
using namespace std;

void ListMsg(lm::helloworld &msg){
        cout<<msg.id()<<endl;
        cout<<msg.str()<<endl;
}
int main(){
        lm::helloworld msg1;
        {
                fstream input("./log",ios::in|ios::binary);
                if(!msg1.ParseFromIstream(&input)){
                        cerr<<"Failed to parse addresss book."<<endl;
                        return -1;

                }
        }
        ListMsg(msg1);
}

$g++ Reader.cpp lm.helloworld.pb.cc `pkg-config --cflags --libs protobuf` -o reader

$./writer

$./reader







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值