提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、编译protobuf
下载protobuf 21.9
https://github.com/protocolbuffers/protobuf/releases

cmake编译protobuf
解压好下载的压缩包,在protobuf-3.21.9文件夹内创建visualstudio文件夹
打开cmakegui
source code选择protobuf的cmake文件夹
build the binaries选择刚刚创建的visualstudio文件夹
单击左下角的configure
第一个下拉框选择visual studio 17 2022,其他默认,点击finish

勾选想要的配置选项后点击generate

打开vs2022
点击visualstudio文件夹内的protobuf.sln进入vs
选择好配置,debug或release都行

右击ALL_BUILD选择重新生成(我这里生成的为debug版本)

进入到visualstudio文件夹的Debug文件夹内
然后在protobuf文件夹内创建一个vs_test文件夹 (取名随意),里面再创建一个bin和include文件夹
然后复制Debug文件夹内的所有文件到bin里面

复制protobuf文件夹下src里的google文件夹到include文件夹内

二、配置vs
右击项目选择属性

在VC++中添加包含目录,为vs_test的include文件夹

再添加库目录,为vs_test下的bin文件夹

并在链接器的输入选项中添加附加依赖项
libprotobufd.lib
libprotocd.lib

C/C++的预处理器选项中添加预处理器定义PROTOBUF_USE_DLLS

点击确定并应用
三、添加环境变量
新建系统变量PROTOBUF_HOME

系统变量Path中添加%PROTOBUF_HOME%

四、测试
在项目目录中创建test.proto文件,并写入以下内容
(新建文本文件并修改后缀即可)
syntax = "proto3";
message Test
{
string name = 1;
}
右击项目所在文件夹空白处选择在终端中打开
并输入,protoc --cpp_out=. ./test.proto

添加生成的.cc和.h文件到项目中

选择添加现有项,添加上述两个文件

测试代码
#include <iostream>
#include "test.pb.h"
int main()
{
Test test;
test.set_name("Hello World");
std::string str;
//序列化到字符串str
test.SerializeToString(&str);
std::cout << "序列化到字符串:" << str << std::endl;
//从字符串中解析
Test test2;
test2.ParseFromString(str);
std::cout << "从字符串解析:" << test.name() << std::endl;
return 0;
}


1495

被折叠的 条评论
为什么被折叠?



