【ProtoBuf】ProtoBuf 通过 proto 文件生成 cc/h 文件

9 篇文章 0 订阅
3 篇文章 1 订阅

本文简单介绍如何根据 protobuf 的 .proto 文件生成 C++ 使用的头文件和源文件。

参考:protobuf

目录

ProtoBuf 通过 proto 文件生成 cc/h 文件的步骤如下:

编译 protoc 可执行文件

Linux 端

先通过 protobuf 源文件编译出 protoc 可执行文件:

git clone https://github.com/protocolbuffers/protobuf.git
cd protobuf/
git checkout -b v2.6.1 origin/2.6.1-artifacts
wget https://codeload.github.com/google/googletest/tar.gz/release-1.5.0
tar -zxvf release-1.5.0
mv googletest-release-1.5.0/ gtest
./autogen.sh
./configure
make -j8
sudo make install

Mac 端

直接利用 brew 安装 protobuf :

brew search protobuf
brew install protobuf@3

安装完之后根据提示将环境变量添加到 ~/.bash_profile 中,然后就可以使用 protoc 生成 cc/h 文件了。

利用 protoc 生成 cc/h 文件

  1. 然后通过 proto 文件生成 cc/h 文件:
cd src
./protoc --proto_path=. --cpp_out=. ./Test.proto

如果 make install 失败,则直接使用全路径的 protoc 生成 cc/h 文件:

cd protobuf
./src/protoc --proto_path=. --cpp_out=. ./Test.proto
安装protobuf 1. 下载protobuf编译器:https://github.com/protocolbuffers/protobuf/releases 2. 安装protobuf编译器: ``` $ tar -xzvf protobuf-3.15.6.tar.gz $ cd protobuf-3.15.6/ $ ./configure $ make $ sudo make install $ sudo ldconfig ``` 3. 安装protobuf的Go语言支持: ``` $ go get github.com/golang/protobuf/protoc-gen-go ``` 该命令会从GitHub上下载并编译出protoc-gen-go可执行文件,该文件是一个protobuf插件,用于将proto文件生成Go语言代码。 使用protobuf 1. 编写proto文件 ```protobuf syntax = "proto3"; package example; message Person { string name = 1; int32 age = 2; repeated string hobbies = 3; } ``` 2. 使用protoc命令生成Go语言代码 ``` $ protoc --go_out=. example.proto ``` 该命令会在当前目录下生成example.pb.go文件,其中包含了protobuf定义的Person类型的Go语言结构体。 3. 在Go语言程序中使用protobuf ```go package main import ( "fmt" "example" "github.com/golang/protobuf/proto" ) func main() { p := &example.Person{ Name: "Alice", Age: 20, Hobbies: []string{"swimming", "reading"}, } data, err := proto.Marshal(p) if err != nil { fmt.Println("marshal error:", err) return } p2 := &example.Person{} err = proto.Unmarshal(data, p2) if err != nil { fmt.Println("unmarshal error:", err) return } fmt.Println("p2:", p2) } ``` 该程序使用protobuf将一个Person对象编码为二进制数据,然后解码成另一个Person对象。注意,该程序需要引入github.com/golang/protobuf/proto包,该包提供了protobuf的Go语言支持。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值