1:下載:
壓縮文件中包含 protobuf-2.5.0.tar.gz 和 protoc-2.5.0-win32.zip,protobuf-2.5.0.tar.gz是protobuf的源文件,protoc-2.5.0-win32.zip是一個protoc.exe應用文件,用於把傳輸類編譯成.h和.cc文件。把 protoc-2.5.0-win32.zip 解壓後的目錄添加到系統的環境變量中。打開cmd,輸入protoc -h 有相應的提示,表示成功。
2:編譯
(1):打開protobuf-2.5.0的解壓文件的vsprojects中工程文件protobuf.sln,編譯:libprotobuf 有錯誤:
1>..\src\google\protobuf\io\zero_copy_stream_impl_lite.cc(121): error C3861: “min”: 找不到標識符
1>..\src\google\protobuf\io\zero_copy_stream_impl_lite.cc(168): error C3861: “max”: 找不到標識符
1>..\src\google\protobuf\io\zero_copy_stream_impl_lite.cc(195): error C3861: “min”: 找不到標識符
則在文件中添加:#include <algorithm>頭文件
(2):修改vs2013的編譯強制copy檢查,若不修改,編譯對象文件的時候,會報_Copy_Imp的錯誤,修改libprotobuf工程下的repeated_field.h文件,修改如下:
namespace internal {
template <typename Element, bool HasTrivialCopy>
void ElementCopier<Element, HasTrivialCopy>::operator()(
Element to[], const Element from[], int array_size) {
std::copy(from, from + array_size, stdext::checked_array_iterator<Element*>(to, array_size));
//std::copy(from, from + array_size, to);
}
(3):最後一個個編譯工程,生成libprotobuf.lib,libprotobuf-lite.lib,libprotoc.lib,lite-test.exe,protoc.exe,test_plugin.exe,tests.exe
3:添加測試工程文件:
新建控制檯文件testprotobuf.sln工程
新建protobuf_lib文件夾,把上面編譯的lib文件copy到這個文件下。
新建protobuf_src文件夾,把protobuf-2.5.0的源文件下的src文件夾下的所有文件copy到此文件夾下。
新建Person.proto文件,內容如下:
- package Test;
- message Person
- {
- required string name = 1;
- required int32 id = 2;
- optional string email = 3;
- }
打開cmd,輸入命令:
protoc -I=E:\work\testProtobuf --cpp_out=E:\work\testProtobuf E:\work\testProtobuf\Person.proto
把相應的目錄換成.proto文件所在的目錄即可,完成後會生成兩個文件:Person.pb.h,Person.pb.cc,然後添加到工程中。
4:添加源文件的頭文件。
添加lib,【屬性】-【鏈接器】-【輸入】-【附加依賴項】把上面的三個lib添加進來
在包含lib所在的庫文件:【屬性】-【鏈接器】-【常規】-【附加庫本目錄】:$(SolutionDir)\protobuf_lib
添加測試源碼:
- #include "stdafx.h"
- #include "..\Person.pb.h"
- #include <iostream>
- #include <fstream>
- int _tmain(int argc, _TCHAR* argv[])
- {
- GOOGLE_PROTOBUF_VERIFY_VERSION;
- Test::Person person;
- person.set_id(123);
- person.set_name("abc");
- person.set_email("[email protected]");
- std::cout << "Before:" << std::endl;
- std::cout << "ID:" << person.id() << std::endl;
- std::cout << "name:" << person.name() << std::endl;
- std::cout << "email:" << person.email() << std::endl;
- std::string str;
- person.SerializeToString(&str);
- Test::Person person2;
- person2.ParseFromString(str);
- std::cout << "After:" << std::endl;
- std::cout << "ID:" << person2.id() << std::endl;
- std::cout << "Name:" << person2.name() << std::endl;
- std::cout << "Email:" << person2.email() << std::endl;
- system("pause");
- return 0;
- }
結果如下: