0.環境
window10,C++
1.準備
1.1 下載protobuff:https://github.com/protocolbuffers/protobuf/releases , 我下載的是3.10
1.2 安裝cmake: https://cmake.org/download/
1.3 cmake我下載的是目前最新的3.16,編譯生成的protobuff,發現加進項目時報錯: 未發現<google/protobuf/port_def.inc>,浪費了很多時間找問題,最終下了3.14版本沒有出現該問題。
2.編譯protobuff
2.1 解壓protobuff
2.2 Browse Source選擇protobuff的cmake目錄
2.3 Browse Build選擇存放路徑
2.4 點擊左下角的 "Configure" 進行相應的配置
2.5 點擊"Generate",生成項目
2.6 點擊"Open Project",打開項目編譯,主要編譯2個項目即可:libprotobuf, protoc
2.7 生成libprotobfd.lib和protoc.exe
3.測試驗證
3.1 新建一個myprotobuff.proto的文本文件
syntax = "proto3";
package tutorial; //包名,命名空間
message Person {
int32 id = 1;
string name = 2;
string email = 3;
}
3.2 編譯,生成c++的頭文件和源文件
protoc myprotobuff.proto --cpp_out=.
syntax:proto協議,默認使用的是2
--cpp_out:生成位置
3.3 項目中使用
3.3.1 包含目錄
3.3.2 添加庫
3.3.3 把頭文件,源文件加載進項目
3.3.4 代碼
#include "stdafx.h"
#include "myprotobuff.pb.h"
int main()
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
tutorial::Person person;
person.set_id(123456);
person.set_name("Mark");
person.set_email("[email protected]");
std::string out = person.SerializeAsString();
std::string data;
person.SerializeToString(&data);
std::cout << "string : " << out <<", data : " << data << std::endl;
tutorial::Person p;
p.ParseFromString(out);
std::cout << "id = " << p.id() << ", name = " << p.name() << ", email : " << p.email() << std::endl;
return 0;
}
3.3.5 結果