# 依赖
sudo apt-get install build-essential
sudo apt install libtool autoconf make
sudo apt install make-guile
# 安装
cd protobuf-3.19.4
sudo ./autogen.sh
sudo ./configure
sudo make
sudo make check
sudo make install
sudo ldconfig # refresh shared library cache
# 检验
protoc --version
demozcm@vm:~/Documents/protobuf_test$ tree
.
├── pb
│ ├── msg.pb.cc
│ ├── msg.pb.h
│ ├── msg.proto
└── src
└── test_protobuf.cpp
syntax = "proto3";
package demo;
message People {
string name = 1;
int32 id = 2;
string email = 3;
}
# 编译出 pb.h pb.cc
protoc --cpp_out=. msg.proto
// 使用
#include#include"../pb/msg.pb.h"
#includeint main()
{
std::string data;
demo::People p;
p.set_name("zhang san");
p.set_id(101);
p.set_email("zhang@163.com");
p.SerializeToString(&data);
std::cout<<"serialize to string \n"<<"data size:"<
// 编译
g++ src/test_protobuf.cpp pb/msg.pb.cc -o test -lprotobuf
运行zcm@vm:~/Documents/protobuf_test$ ./test
serialize to string
data size:32
zhang sane�zhang@163.com
parse from string
People:
Name: zhang san
ID: 101
Email: zhang@163.com
makefile编译使用了makefile编译整个项目,shell脚本生成与清除pb,未统一
德化ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18980820575(备注:SSL证书合作)期待与您的合作!项目结构zcm@vm:~/Documents/protobuf_test$ tree
.
├── build
│ └── test
├── makefile
├── pb
│ ├── clean.sh
│ ├── create.sh
│ ├── msg.pb.cc
│ ├── msg.pb.h
│ ├── msg.proto
│ ├── people.pb.cc
│ ├── people.pb.h
│ └── people.proto
└── src
├── makefile
└── test_protobuf.cpp
项目总体Makefileall:
cd pb && ./create.sh
cd src && make
clean:
cd pb && ./clean.sh
cd src && make clean
pb生成脚本与清除脚本# create.sh
BASE_DIR=..
SCR_DIR=$BASE_DIR/pb
DES_DIR=$BASE_DIR/pb
protoc --proto_path=$SCR_DIR --cpp_out=$DES_DIR $SCR_DIR/*.proto
# clean.sh
BASE_DIR=..
# SCR_DIR=$BASE_DIR/pb
DES_DIR=$BASE_DIR/pb
rm -f $DES_DIR/*.h $DES_DIR/*.cc
生成可执行文件的Makefile.SUFFIXES: .sh .h .c .cc .cpp
# 命令
AR = ar
AR_FLAGS = crs
CXX = g++
CXXFLAGS = -std=c++11
# 地址变量
BASE_DIR = ..
BUILD_DIR = $(BASE_DIR)/build
INC_DIR = -I$(BASE_DIR)/pb
LIB_DIR =
# 依赖库
CLIBS = -lprotobuf
CLIBS +=
# 生成可执行文件
BIN = $(BUILD_DIR)/test
SERVER_SRCS = $(wildcard *.cpp $(BASE_DIR)/pb/*.cc)
SERVER_OBJS = $(patsubst %.cpp %.cc,%.o,$(SERVER_SRCS))
# make
all: build_dir bin
build_dir bin :$(BUILD_DIR) $(BIN)
$(BIN):$(SERVER_SRCS)
$(CXX) $(CXXFLAGS) $(INC_DIR) -o $@ $^ $(CLIBS)
$(BUILD_DIR):
@-mkdir -p $(BUILD_DIR)
# make clean
clean:
@-rm -rf $(BUILD_DIR)
运行zcm@vm:~/Documents/protobuf_test$ ./build/test
serialize to string
data size:32
zhang sane�zhang@163.com
parse from string
People:
Name: zhang san
ID: 101
Email: zhang@163.com
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧