Google Protocol Buffer在vs2010下配置

1、从这里下载protobuf-2.6.1.tar.gz到桌面,并解压,解压后的文件夹为protobuf-2.6.1。(我的桌面为C:UsersmclDesktop)

2 、进入文件夹protobuf-2.6.1vsprojects,用vs2010打开其中的sln文件,然后生成解决方案(然后这个vs就可以关闭了)。 之后在protobuf-2.6.1vsprojectsDebug下会有一个protoc.exe,并且还有一些其他的lib文件等。

3、在你vc的lib文件夹下新建一个google文件夹,然后将protobuf-2.6.1vsprojectsDebug下的全部文件都拷贝进去。

4、将C:UsersmclDesktopprotobuf-2.6.1src文件夹下的google文件夹拷贝到vs的include文件夹下。

5、新建一个vs工程,比如我在桌面上新建了一个GoogleProtoStudy的工程,然后将protobuf-2.6.1examples下面的Makefile文件拷贝到GoogleProtoStudyGoogleProtoStudy下(注意这个文件夹下应该有有vcxproj,filters等文件)。这个时候那个protobuf-2.6.1的文件夹可以全部删掉了。

6、接着在GoogleProtoStudyGoogleProtoStudy文件夹下新建一个person.proto的文件,内容如下:

package tutorial;

message Person {
   optional string dim=1;
   repeated int32 num=2;
}

message Student{
   optional Person p=1;
}

  

7、在工程的属性->配置属性->链接器->输入,在右侧的“附加依赖项”中输入libprotobuf.lib,libprotoc.lib(注意分两行,每行一个)。然后在属性->配置属性->链接器->常规,在右侧的“附加库目录”中加入刚才vc目录下lib下那个google文件夹的路径,比如我的是"D:vs2010VClibgoogle"。

8、然后新建一个main.cpp,在其中写上如下代码:(注意把所有的目录改成你相关的目录)。然后运行,就会把刚才的person.proto编译成一个.h文件和一个.cpp文件。

#include <iostream>  
#include <string>
 
using namespace std;  
 
 
void trans()
{
	std::string S="D:\vs2010\VC\lib\google\protoc.exe 
	               -I=C:\Users\mcl\Desktop\GoogleProtoStudy\GoogleProtoStudy 
		       --cpp_out=C:\Users\mcl\Desktop\GoogleProtoStudy\GoogleProtoStudy 
	               C:\Users\mcl\Desktop\GoogleProtoStudy\GoogleProtoStudy\person.proto";
	system(S.c_str());
}
 
int main()  
{  
	trans(); system("pause");  return 0;
}  

  

9、把刚才生成的文件加入到工程中,就可以使用了。

#include <iostream>  
#include <string>
#include "person.pb.h"  

using namespace std;  
using namespace tutorial;  


void trans()
{
	std::string S="D:\vs2010\VC\lib\google\protoc.exe 
				  -I=C:\Users\mcl\Desktop\GoogleProtoStudy\GoogleProtoStudy 
				  --cpp_out=C:\Users\mcl\Desktop\GoogleProtoStudy\GoogleProtoStudy 
				  C:\Users\mcl\Desktop\GoogleProtoStudy\GoogleProtoStudy\person.proto";
	system(S.c_str());
}

int main()  
{  
	//trans(); 

	Person a;
	a.add_num(1);
	a.add_num(4);
	a.add_num(5);
	a.set_dim("hello world");
	
	for(int i=0;i<a.num_size();i++) cout<<a.num(i)<<endl; //输出1 4 5
	cout<<a.dim()<<endl; //输出 hello world

    Student b;
    b.set_allocated_p(&a);

	Person* A=b.mutable_p();
	cout<<A->dim()<<endl; //输出 hello world

	system("pause");  
	return 0;
}  

  

原文地址:https://www.cnblogs.com/jianglangcaijin/p/6498444.html