Google_Protobuf协议——Protobuf工具使用

工具安装好后,就需要编写protobuf文件,让protobuf工具编译成源码,然后将源码放入工程文件中使用。protobuf文件的后缀为.proto

编写Protobuf文件

测试文件test.proto

//确定支持的protobuf语法
syntax = "proto3";

//包名,命名空间
package zxtest.prototest;

//枚举
enum Recode {
    SUCCESS = 0;
    ERROR = 1;
};

//内容结构体
message TestSend {
    string sname        = 1;
    uint32 u32number    = 2;
    bool   isReady      = 3;
}

//回应结构体
message TestReceive {
    Recode enumcode     = 1;
    string srename      = 2;
}

编译Protobuf文件

安装protobuf工具的目的就是需要编译protobuf文件,并且提供protobuf运行所需要的头文件和库文件。

此次仅仅是用工具编译成CPP的文件和java文件,其余的支持语法都可以编译。

编译成CPP文件

linux环境     :protoc --proto_path=./ --cpp_out=./ ./test.proto
windows环境   :protoc.exe --proto_path=.\ --cpp_out=.\ .\ test.proto

编译后的文件

ghost@ghost-machine:/mnt/hgfs/share/protobuftest$ protoc --cpp_out=./ test.proto 
ghost@ghost-machine:/mnt/hgfs/share/protobuftest$ ls
test.pb.cc  test.pb.h  test.proto

Linux构建protobuf的Makefile文件

DIR = $(shell pwd)

CC = protoc
PROTO_TYPE = --cpp_out

INC = --proto_path=$(DIR)
SRC = $(wildcard $(DIR)/*.proto)
OBJ = $(patsubst %.proto,%.pb.cc,$(SRC))

OUT = $(PROTO_TYPE)=$(DIR)


all:$(OBJ)

%.pb.cc:%.proto
    $(CC) $(INC) $(OUT) $<

.PHONY:clean
clean:
    rm -rf $(DIR)/*.pb.*

工程源码加入Protobuf

将头文件和库文件分别加入VS工程或Makefile工程中。

Linux

引用静态库:

LIB += /usr/local/lib/libprotobuf.a

引用动态库:

LD_LIB += -L/usr/local/lib -lprotobuf

Windows

Debug

引用静态库
引用动态库

Release

引用静态库
引用动态库

头文件包含

#include "test.pb.h"

命名空间

using namespace zxtest;

猜你喜欢

转载自blog.csdn.net/zxng_work/article/details/78943054