使用Visual Studio 2015编译protobuf

下载源码

笔者使用的protobuf版本是protobuf-cpp-3.0.0-alpha-1。下载链接

https://github-production-release-asset-2e65be.s3.amazonaws.com/23357588/d783a8d4-7fcb-11e4-9260-069534592d92?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20210125%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20210125T132804Z&X-Amz-Expires=300&X-Amz-Signature=f179410e88cf788003d158020862e5999ac36ccec31caff53c7b4ca2f5c7178e&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=23357588&response-content-disposition=attachment%3B%20filename%3Dprotobuf-cpp-3.0.0-alpha-1.zip&response-content-type=application%2Foctet-stream

编译源码

解压缩源码包。

目录结构如上所示。进入vsprojects目录中。打开protobuf.sln工程文件。工程结构如下图所示

主要编译libprotobuf、libprotoc以及protoc三个项目即可。

首先编译libprotobuf。需要改动两处。

1.右键项目属性。在C/C++的预处理器中的预处理器定义这一栏添加 _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS 宏定义。

2.根据自己的需要选择编译出来的版本。

关于运行库的版本的问题。可以参考https://blog.csdn.net/qq_33757398/article/details/82156956 此博客链接。

然后编译libprotoc  也需要进行如上两项改动。

编译完毕之后。同样在vsprojects目录中。会出现X64目录。<font color = red>因为笔者使用的是x64编译。所以是出现在x64目录下</font>

若是使用win32编译。那么应该是Debug目录中。如下所示。

进入X64里面的Debug目录。主要寻找三个文件即可。

libprotobuf.lib libprotoc.lib  protoc.exe

如果成功编译。目录中是应该有这三个文件的。至此、protobuf的编译就已经完成、

protobuf的使用

在你的工程目录中新建一个Test.proto 文件。文件内容如下:

syntax = "proto3";
package Test;
message UserAccount {
	string usrName = 2;
	string userPassword = 3;
}
 
message User {
	User user = 1;
}

然后启动cmd,目录切换到你的工程目录。然后将刚刚那三个文件拷贝到工程目录下。

然后输入cmd命令

protoc --cpp_out=./ Test.proto //注意./和文件名之间有个空格

回车运行。目录下生成 Test.pb.h  Test.pb.cc 文件。然后将它们加入到工程中去。

然后拷贝protobuf的头文件过来。

如上图所示,在解压目录中的src 目录中的google 目录。将protobuf 目录拷贝到工程目录下然后添加头文件包含目录下。然后将libprotobuf.lib 链接到工程目录中如下图所示

完成如上几部之后。


#include <QtWidgets/QApplication>
#include <string>
#include <iostream>
#include "Test.pb.h"
int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	Test::UserAccount account1;
	account1.set_usrname("testUser");
	account1.set_userpassword("testUserPassWord");

	std::string serializeToStr;
	account1.SerializeToString(&serializeToStr);
	std::cout << "Serialization:" << std::endl;
	std::cout << serializeToStr << std::endl;

	Test::UserAccount account2;
	if (!account2.ParseFromString(serializeToStr))
	{
		std::cerr << "failed to parse student." << std::endl;
		return -1;
	}
	std::cout << "Deserialization:" << std::endl;
	std::cout << account2.usrname() << std::endl;
	std::cout << account2.userpassword() << std::endl;

	google::protobuf::ShutdownProtobufLibrary();
	return a.exec();
}

然后运行。发现控制台输出 

至此,完结。

猜你喜欢

转载自blog.csdn.net/weixin_39308337/article/details/113145877