protobuf系列教程
protobuf 误装了其他版本之后,我之前的3.6.1,就找不到了,现在按照源码安装的方式,进行安装,成功
1.卸载
sudo apt-get remove libprotobuf-dev
which protoc
然后删除路径即可
2.安装
sudo apt-get install autoconf automake libtool curl make g++ unzip
git clone -b v3.6.1 https://github.com/protocolbuffers/protobuf.git
cd protobuf
git submodule update --init --recursive
./autogen.sh
./configure
make
make check
sudo make install
sudo ldconfig
protoc --version 输出版本号成功
例子
person.proto syntax = "proto3"; package tutorial; message Person { int32 id = 1; string name = 2; string email = 3; } message PersonList { repeated Person persons = 1; }
protoc --cpp_out=./ person.proto
test.cpp
#include <iostream> #include <string> #include <sstream> #include <map> #include "person.pb.h" // set the person's info void SetPersonInfo(const tutorial::Person& infoPerson, tutorial::Person* pPerson) { pPerson->set_id(infoPerson.id()); pPerson->set_name(infoPerson.name()); pPerson->set_email(infoPerson.email()); } // print the persons void ListAllPerson(const tutorial::PersonList& listPerson) { for (int i = 0; i < listPerson.persons_size(); i++) { const tutorial::Person& person = listPerson.persons(i); std::cout << "ID: " << person.id() << std::endl; std::cout << "name: " << person.name() << std::endl; std::cout << "e-mail: " << person.email() << std::endl; std::cout << "----------------------------------------\n"; } } int main(int argc, char* argv[]) { GOOGLE_PROTOBUF_VERIFY_VERSION; tutorial::Person person; person.set_id(666); person.set_name("Mark"); person.set_email("mark@example.com"); // serialize to io-stream std::stringstream ss; person.SerializeToOstream(&ss); std::string strData = ss.str(); std::cout << "Data:" << strData << "\n"; // deserialize from io-stream if (!person.ParseFromIstream(&ss)) { std::cerr << "Failed to parse person.pb." << std::endl; return -1; } std::cout << "ID: " << person.id() << std::endl; std::cout << "name: " << person.name() << std::endl; std::cout << "e-mail: " << person.email() << std::endl; // list data tutorial::PersonList listPerson; SetPersonInfo(person, listPerson.add_persons()); tutorial::Person person1; person1.set_id(8468); person1.set_name("Test"); person1.set_email("test@example.com"); SetPersonInfo(person1, listPerson.add_persons()); // serialize to io-stream std::stringstream ssList; listPerson.SerializeToOstream(&ssList); std::cout << "List:" << ssList.str() << "\n"; std::cout << "--------------------Deserialize------------------\n"; tutorial::PersonList listDeserialize; listDeserialize.ParseFromIstream(&ssList); ListAllPerson(listDeserialize); std::cout << "\nFinished\n"; getchar(); return 0; }
CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3) project(protobuf_tutorial) set(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}") find_package(Protobuf REQUIRED) include_directories( include ${PROTOBUF_INCLUDE_DIRS} ) add_library(person_protobuf person.pb.cc) add_executable(test test.cpp) target_link_libraries( test person_protobuf ${PROTOBUF_LIBRARIES} )