PROTOBUF Installation and use

Source: Internet
Author: User
Tags class definition git clone
Download

git clone https://github.com/google/protobuf.git
CD Protobuf
$./autogen.sh

You may experience the following issues:/autogen.sh:40:autoreconf:not found
workaround: sudo apt-get install autoconf automake libtool

./configure–prefix=/usr
Make
Make check
Make install use

First, define a proto file:

Package LM; 
 Message HelloWorld 
 { 
    required int32     id = 1;  ID 
    Required String    str = 2;  Str 
    optional int32     opt = 3;  Optional field 
 }

Named as: Lm.helloworld.proto
In the current directory of the file, run the following command:

protoc-i=./--cpp_out=./Lm.helloworld.proto

Generate Lm.helloworld.pb.h and lm.helloworld.pb.cc two files, respectively, for the class definition and implementation file.

Second, then use the above two files, create a new write.cpp and Read.cpp file:
Write.cpp

#include "lm.helloworld.pb.h"
#include <iostream>
#include <fstream>

using namespace std;
int main (void)
{
    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;
}

Read.cpp

#include "lm.helloworld.pb.h"
#include <iostream>
#include <fstream>

using namespace std ;

int main (void)
{
    Lm::helloworld msg1;
    FStream input ("./log", Ios::in | ios::binary);
    if (!MSG1. Parsefromistream (&input))
    {
        cerr << "Failed to the parse address Book." << Endl;
        return-1;
    }

    cout << msg1.id () << Endl;
    cout << msg1.str () << Endl;
    return 0;
}

Third, compile the above two files

c++ write.cpp Lm.helloworld.pb.cc-lprotobuf-o write C + + read.cpp lm.helloworld.pb.cc- Lprotobuf-o Read 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.