Protobuf 安装与使用
- 1 环境
- 2 安装 [apt安装]
- 2 安装 [源码安装]
- 1 依赖
- 2 下载 protobuf
- 3 解压
- 4 编译安装
- 5 配置环境
- 2 命令
- 查看版本
- 卸载
- 3 使用
- 书写 .proto 文件
- 编译 .proto 文件生成 cpp 文件
- 编写 cpp 文件
- 编译
- 运行
- 参考
1 环境
ubuntn 20.04
protobuf v3.6.1
2 安装 [apt安装]
2 安装 [源码安装]
1 依赖
需要git、g++、cmake 等
sudo apt-get update
sudo apt-get install autoconf automake libtool
2 下载 protobuf
选择版本 v3.6.1
网址:https://github.com/protocolbuffers/protobuf/releases/tag/v3.6.1
选择:protobuf-all-3.6.1.tar.gz
3 解压
拷贝到自己目录下解压
sudo tar -zxvf protobuf-all-3.6.1.tar.gz
4 编译安装
cd protobuf-3.6.1
sudo ./autogen.sh
#./configure --prefix=$INSTALL_DIR #--prefix指定安装目录 默认 /usr/local
sudo ./configure --prefix=/opt/protobuf
sudo make
sudo make check
sudo make install
5 配置环境
- 添加环境变量
vim /etc/profile
# 末尾加上如下两行
export PATH=$PATH:/opt/protobuf/bin/
export PKG_CONFIG_PATH=/opt/protobuf/lib/pkgconfig/
# 命令使生效
source /etc/profile
- 配置动态链接库【可不配置,编译时链接就行】
vim /etc/ld.so.conf# 加入
/opt/protobuf/lib# 动态库加载
sudo ldconfig
2 命令
查看版本
protoc --versioneg:libprotoc 3.6.1
卸载
sudo apt-get remove libprotobuf-dev
3 使用
书写 .proto 文件
如下命名规则方便理解
packageName.MessageName.proto
bp.test.proto
syntax = "proto3";package BP;message Test {int32 id = 1; // IDstring name = 2; // name
}message TestList {int32 id = 1;repeated Test tl = 2;
}
编译 .proto 文件生成 cpp 文件
写好 proto 文件之后就可以用 Protobuf 编译器将该文件编译成目标语言了。
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/XXX.protoeg:
protoc --cpp_out=./ bp.test.proto
生成两个文件【数据操作,序列化反序列化】
bp.test.pb.h ,定义了 C++ 类的头文件
bp.test.pb.cc ,C++ 类的实现文件
编写 cpp 文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "./bp.test.pb.h" int main() { BP::Test t; t.set_id(1); t.set_name("sen"); printf("%d - %s\n", t.id(), t.name().c_str()); BP::Test t2 = t; // 复制t到t2 t2.set_id(2); printf("%d - %s\n", t2.id(), t2.name().c_str());BP::Test t3; t3.set_id(3); t3.set_name("sen3"); printf("%d - %s\n", t3.id(), t3.name().c_str());BP::TestList list; list.set_id(007); list.add_tl()->CopyFrom(t2); // 复制t2到列表的第一个元素 printf("%d - %s\n", list.tl(0).id(), list.tl(0).name().c_str()); list.add_tl()->CopyFrom(t3); // 复制t3到列表的第二个元素 printf("%d - %s\n", list.tl(1).id(), list.tl(1).name().c_str()); return 0;
}
编译
g++ main.cpp bp.test.pb.cc -I /opt/protobuf/include -L /opt/protobuf/lib -lprotobuf -lpthread
注:
Protobuf编译时是否依赖lpthread主要取决于你的构建配置。在某些情况下,例如当你使用某些特定的编译器或选项来构建protobuf时,它可能会依赖lpthread。这主要是因为在某些情况下,protobuf会使用线程本地存储(Thread-local Storage,TLS),这需要lpthread库。
运行
./a.out1 - sen
2 - sen
3 - sen3
2 - sen
3 - sen3
参考
1、Ubuntn下安装protobuf和使用详解
2、在Ubuntu中安装Protobuf-2.5.0(详细)