protobuf安装教程

    技术2022-07-10  139

    下载 protobuf 、cmake

    https://github.com/google/protobuf/releases protobuf如:protobuf-cpp-3.10.1.zip 并解压到D盘,得到protobuf-3.1.0文件夹 https://cmake.org/download/ cmake如:cmake-3.9.1-win64-x64.msi 双击安装

    编译

    打开cmake 1.D:\protobuf-3.1.0\cmake 2.D:\protobuf-3.1.0-build 是 点configure 再点configure 然后点击Generate, 如果成功,Open Project会亮,点击Open Project进入编译好的目录 生成解决方案

    新建工程

    新建一个vs工程,如在D盘新建ProtoTest空工程,同时在源文件下新建main.cpp 在VS工程下,即D:\ProtoTest下新建temp文件夹,将D:\protobuf-3.1.0-build\Debug下的libprotobufd.lib和proto.exe拷贝到temp文件夹中。 在temp文件夹下新建person.proto文件,添加以下内容:

    package tutorial; message Person { required int32 id = 1; required string name = 2; optional string email = 3; }

    tutorial是包名(也可以说是命名空间),没有第一行的话,就是没有命令空间的。 再添加一个批处理文件build.bat,内容为:

    protoc --cpp_out=./ person.proto

    双击批处理文件build.bat,会在当前目录下生成:person.pb.h和person.pb.cc文件, 将person.pb.h和person.pb.cc文件拷贝到D:\ProtoTest\ProtoTest下, 在源文件和头文件下右击将person.pb.h和person.pb.cc手动添加进来。 将D:\protobuf-3.1.0下src下的google文件夹拷贝到D:\ProtoTest

    配置VS

    在VS解决方案下的ProtoTest右击-属性 C/C++-常规-附加包含目录-D:\ProtoTest C/C++-预处理器-_SCL_SECURE_NO_WARNINGS C/C++-代码生成-运行库-多线程调试(/MTd) 链接器-常规-附加库目录-D:\ProtoTest\temp 链接器-输入-附加依赖项-libprotobufd.lib

    如果提示找不到头文件,可能是平台选错了。Win32和X64自查一下

    main.cpp

    #include <iostream> #include <fstream> #include <string> #include "person.pb.h" using namespace std; int main(int argc, char* argv[]) { GOOGLE_PROTOBUF_VERIFY_VERSION; tutorial::Person person; //将数据写到person.pb文件 person.set_id(123456); person.set_name("Mark"); person.set_email("mark@example.com"); fstream out("person.pb", ios::out | ios::binary | ios::trunc); person.SerializeToOstream(&out); out.close(); //从person.pb文件读取数据 fstream in("person.pb", ios::in | ios::binary); if (!person.ParseFromIstream(&in)) { cerr << "Failed to parse person.pb." << endl; exit(1); } cout << "ID: " << person.id() << endl; cout << "name: " << person.name() << endl; if (person.has_email()) { cout << "e-mail: " << person.email() << endl; } getchar(); return 0; }

    F5运行一下。

    参考链接: https://blog.csdn.net/program_anywhere/article/details/77365876 https://blog.csdn.net/hp_cpp/article/details/81561310

    Processed: 0.014, SQL: 9