protobuf c++ 笔记

protobuf c++ 笔记

Jan 24, 2016
Coding
C++, Protobuf

protobuf的github 源码地址为 https://github.com/google/protobuf

本次使用的环境为ubuntu,参照官方教程

1. 编译源码 #

sudo apt-get install autoconf automake libtool curl #安装工具
git clone https://github.com/google/protobuf #下载源码

进入源码目录,打开autogen.sh脚本,找到下面这行代码,注释掉该行。(因为google被墙,会连接超时)

curl $curlopts -O https://googlemock.googlecode.com/files/gmock-1.7.0.zip

手动下载 gmock-1.7.0.zip 文件,放到当前目录,然后继续执行以下命令

./autogen.sh
./configure
make
make check
sudo make install
sudo ldconfig # refresh shared library cache.

2. 编写 proto 文件 #

//person.proto
message Person{
    required string name = 1;
    required uint32 age = 2;
    optional string country = 3;
}

3. 使用 protobuf compiler 编译 proto 文件 #

protoc --cpp_out=./ person.proto

指定编译出来的.h和.cc文件放在当前目录

4. main函数 #

#include <iostream>
#include <fstream>
#include "person.pb.h"

using namespace std;

int main()
{
    GOOGLE_PROTOBUF_VERIFY_VERSION;
    Person p;
    p.set_name("Andy");
    p.set_age(40);
    p.set_country("China");

    {
        cout<<"Save Data"<<endl;
        fstream output("data",ios::out|ios::trunc | ios::binary);
        if(!p.SerializeToOstream(&output)){
            cerr << "Failed to save"<<endl;
            return -1;
        }else{
            cout<<"Save OK"<<endl;
        }
    }

    {
        cout<<"Read Data"<<endl;
        Person p1;
        fstream input("data",ios::in | ios::binary);
        if(!p1.ParseFromIstream(&input)){
            cerr<<"Failed to read"<<endl;
            return -1;
        }

        cout<<"name:"<<p1.name()<<endl;
        cout<<"age:"<<p1.age()<<endl;
        cout<<"country:"<<p1.country()<<endl;
    }

    return 0;
}

5. makefile #

All: person.pb.cc main.cpp
    pkg-config --cflags protobuf # fails if protobuf is not installed
    g++ person.pb.cc main.cpp -I. -I../protobuf-master/src -o Demo `pkg-config --cflags --libs protobuf`

6. 编译运行 #

make
./Demo