windows 系统:
1.下载proto3压缩包
https://github.com/google/protobuf/releases
直接解压到一个路径即可,把bin文件夹添加到系统path里面。cmd运行protoc --version
2.新建一个demo.proto文件,cd进入文件目录,protoc --cpp_out=. demo.proto 。即可生成.cc和.h文件
Linux系统:
Ubuntu16.04下我的安装过程如下:
先卸载proto2
ubuntu16.04有了proto2,需要先卸载,否则会导致版本冲突
sudo git clone https://github.com/google/protobuf.git
cd protobuf
sudo git submodule update --init --recursive
sudo ./autogen.sh
sudo ./configure
sudo make
sudo make check
sudo make install
sudo ldconfig # refresh shared library cache.
安装时间有点长
ubuntu@ubuntu-Super-Server:/usr/protobuf/protobuf$ sudo ldconfig
ubuntu@ubuntu-Super-Server:/usr/protobuf/protobuf$ protoc --version
libprotoc 3.9.0
使用:
发现:
game.proto:13:32: Interpreting non ascii codepoint 227. 这是由于编码问题,我们重新写一下对应的行就好了。写个脚本用于批量转换:
#!/bin/bash
dir="."
cd $dir
for file in $(ls $dir | grep .proto)
do
echo $file
protoc --cpp_out=$dir $file
done
echo "done"
对于每一个message,protobuf生成的内容主要包括:
class rsp_login : public ::google::protobuf::MessageLite
{
public:
//每一个message类都包含以下方法供你检测或操作
void CopyFrom(const rsp_login& from);
void MergeFrom(const rsp_login& from);
void Clear(); //清除所有字段内容,并置为空状态
bool IsInitialized() const; //检测所有required 是否初始化
int ByteSize() const; //类所占字节数
//整形变量只提供获取、修改、清除
void clear_ret();
::google::protobuf::int32 ret() const;
void set_ret(::google::protobuf::int32 value);
//自定义类类型user_info
bool has_user_info() const;
void clear_user_info();
const ::pt::obj_user_info& user_info() const;
//自定义类型,并没提供set方法,而是通过mutable_接口返回user_info的指针,可根据此指针进行赋值操作
::pt::obj_user_info* mutable_user_info();
//返回user_info字段指针,将所有权移交给此指针,并将user_info字段置为empty状态
::pt::obj_user_info* release_user_info();
//使用set_allocated要小心,传入的参数需要显示allocate,设置后函数内部维护此指针
void set_allocated_user_info(::pt::obj_user_info* user_info);
//record为repeated的类数组类型
int record_size() const;
void clea