自学内容网 自学内容网

linux protobuf的安装与使用

  首先,下载protobuf:

wget https://github.com/protocolbuffers/protobuf/releases/download/v21.11/protobuf-cpp-3.21.11.zip
 

然后,解压:

tar -xf protobuf-2.5.0.tar.gz

接着,安装protobuf

cd protobuf-3.21.11/
mkdir build
./configure --prefix=$PWD/build
make -j8
make check
make install

验证:

cd build/bin/
./protoc --version

使用:

1)定义.proto文件(contacts.proto)

syntax = "proto3";
package contacts;

message PeopleInfo {
    string name = 1;
    int32 age = 2;
}

2)用protoc编译器编译.proto文件

protoc --cpp_out=. contacts.proto

3)使用生成的API

#include <iostream>
#include <fstream>
#include <string>
#include "contacts.pb.h"

int main() 
{
    // Create a PeopleInfo message
    contacts::PeopleInfo person;
    person.set_name("John Doe");
    person.set_age(30);

    // Serialize to file
    std::string filename = "person.bin";
    std::ofstream output(filename, std::ios::binary);
    if (!person.SerializeToOstream(&output)) {
        std::cerr << "Failed to write person." << std::endl;
        return -1;
    }
    output.close();

    // Read from file and deserialize
    contacts::PeopleInfo person2;
    std::ifstream input(filename, std::ios::binary);
    if (!person2.ParseFromIstream(&input)) {
        std::cerr << "Failed to read person." << std::endl;
        return -1;
    }

    // Verify the data
    std::cout << "Name: " << person2.name() << std::endl;
    std::cout << "Age: " << person2.age() << std::endl;

    return 0;
}

4)编译

g++ main.cpp contacts.pb.cc -o main -L../lib/ -lprotobuf -I../include

5)运行

./main

觉得有帮助的话,打赏一下呗。。

           

需要商务合作(定制程序)的欢迎私信!! 


原文地址:https://blog.csdn.net/ckg3824278/article/details/144240409

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!