VS2010下编译ProtocolBuffer 及使用
库及测试项目下载: http://download.youkuaiyun.com/detail/yaoyuanyylyy/7580975
1. 从http://code.google.com/p/protobuf/downloads/list上下载protobuf-2.5.0.zip。
2. 解压并打开目录下的protobuf-2.5.0\vsprojecs\protobuf.sln工程,生成解决方案。在dubug或release目录下会生成几个.lib文件和.exe文件。(对于每个版本应该使用两次“生成解决方案”,因为其中有一些依赖项目,两次后,便可编译所有的项目)要使用的库文件包括:libprotobuf.lib、libprotoc.lib、libprotobuf-lite.lib,另外还有一个protoc.exe文件。其他还包括了一些测试程序。
3. 执行extract_includes.bat 文件,生成include文件夹。
4. 新建一个文件夹protobuf,在其中新建lib文件夹,在lib中新建debug和release两个文件夹,将相应的库和protoc.exe拷贝到其中;将vsprojects下面的include文件夹拷贝到protobuf中。在protobuf文件夹下面新建examples文件夹,在examples中定义user.proto文件:(protobuf文件夹可放在任何地方)
package Test;
message userninfo
{
required string name = 1;
required string mail = 2;
required string time = 3;
optional string status = 4;
}
5. 打开命令行窗口进入到protobuf\lib\debug目录下,输入命令:(也可以是release目录)
protoc -I=..\..\examples --cpp_out=..\..\examples ..\..\examples\user.proto
则可以在examples目录下生成两个文件:user.pb.cc、user.pb.h。
6. 打开VS2010,新建win32项目非空控制台程序Test1,解决方案名称为PBufTest。在属性配置中添加库目录和包含目录(在C/C++ → 常规→附加包含目录" E:\protobuf\include";在连接器→常规→附加库目录:"E:\protobuf\lib\debug";Release版本类似。
7. 将user.pb.h和user.pb.cc复制到项目目录下,并在VS中添加到项目中,编辑PBufTest.cpp文件并测试(注意:在user.pb.cc文件上单击右键,将“属性→C/C++→预编译头”的“预编译头”设为“不使用预编译头”):
8. 代码:
// PBufTest.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include "user.pb.h"
#pragma comment(lib, "libprotobuf.lib")
using namespace Test;
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
userninfouser1;
user1.set_name("yaoyuan");
user1.set_mail("123456789@qq.com");
user1.set_time("2014-9-7");
user1.set_status("test");
fstreamoutPuts;
outPuts.open("./users",ios::out | ios::trunc | ios::binary);
if(!user1.SerializePartialToOstream(&outPuts))
{
cerr<<"写用户信息失败"<<endl;
return-1;
}
outPuts.close();
userninfouser2;
fstreaminPuts;
inPuts.open("./users",ios::in | ios::binary);
if(!user2.ParseFromIstream(&inPuts))
{
cerr<<"Failedto parse userinfo!"<<endl;
return-1;
}
cout<<"username:"<<user2.name()<<endl;
cout<<"usermail:"<<user2.mail()<<endl;
cout<<"usertime:"<<user2.time()<<endl;
cout<<"userstatus:"<<user2.status()<<endl;
inPuts.close();
system("pause");
return0;
}