目录
1.源码下载
github下载源码 GitHub - protocolbuffers/protobuf: Protocol Buffers - Google's data interchange format
2.编译步骤
./autogen.sh
如果出错的话 apt-get install这些:
autoconf
automake
ibtool
make
g++
unzip
交叉编译的话
PATH 是你工具链所在的路径
$ ./configure --host=arm-linux CC=/PATH/aarch64-linux-gnu-gcc CXX=/PATH/aarch64-linux-gnu-g++ --prefix=/home/protobuf/install
$ make -j;make install
3.验证 & 测试
在/home/protobuf/install 下有 bin include lib 三个文件夹 分别表示 可执行文件、头文件、生成的库
cd home/protobuf/install
cd bin
protoc --version //查看 protoc是不是arm64 版本 如果是交叉编译成功 但是得测试一下
测试用例
helloworld.proto
syntax = "proto3";
package lm;
message helloworld
{
int32 id = 1; // ID
string str = 2; // str
}
person.proto
syntax="proto3";
package tutorial;
message Person
{
string name = 1;
int32 id = 2;
string email = 3;
enum PhoneType
{
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber
{
string number = 1;
PhoneType type = 2;
}
repeated PhoneNumber phone = 4;
}
message AddressBook
{
repeated Person person =1;
}
protoc -I=./ --cpp_out=./ helloworld.proto
protoc -I=./ --cpp_out=./ person.proto
会自动生成文件:
helloworld.pb.h
helloworld.pb.cc
person.pb.h
person.pb.cc
CMakeLists.txt (参考的 暂不明确此处用处)
cmake_minimum_required(VERSION 2.8)
project(pbtest)
#set(SRC .)
#查找当前目录下的所有源文件,并将名称保存到DIR_SRCS变量
aux_source_directory(. DIR_SRCS)
add_executable(${PROJECT_NAME} ${DIR_SRCS})
TARGET_LINK_LIBRARIES(${PROJECT_NAME} protobuf)
main.cpp
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>
#include <pthread.h>
#include <fstream>
#include "helloworld.pb.h"
using namespace std;
#define BUFFSIZE 1024
int main()
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
//eg1, write file
lm::helloworld msg1;
msg1.set_id(1001);
msg1.set_str("hello world");
fstream output("./log", ios::out | ios::trunc | ios::binary);
if (!msg1.SerializeToOstream(&output)) {
cerr << "Failed to write msg." << endl;
return -1;
}
output.close();
cout << msg1.id() << endl;
cout << msg1.str() << endl;
//eg2, read file
lm::helloworld msg2;
fstream input("./log", ios::in | ios::binary);
if (!input)
{
cerr << "open file failed!\n";
return -1;
}
if (!msg2.ParseFromIstream(&input)) {
cerr << "Parse file failed!" << endl;
return -1;
}
input.close();
cout << msg2.id() << endl;
cout << msg2.str() << endl;
//eg3, write buf, protobuf序列化
lm::helloworld msg3;
msg3.set_id(1002);
msg3.set_str("good idea");
char buf[BUFFSIZE];
memset(buf, 0, BUFFSIZE);
msg3.SerializeToArray(buf, BUFFSIZE);
//eg4, read buf, protobuf反序列化
lm::helloworld msg4;
msg4.ParseFromArray(buf, BUFFSIZE);
cout << msg4.id() << endl;
cout << msg4.str() << endl;
// Optional: Delete all global objects allocated by libprotobuf.
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
测试用例参考:我个人的protobuf-3.5.2实践:安装与测试_libaineu2004的博客-CSDN博客
生成测试的可执行文件:g++ -g -Wall -std=c++11 main.cpp helloworld.pb.cc person.pb.cc -L/home/protobuf/install/lib -I/home/protobuf/install/include -lprotobuf -lpthread
注意: 这是是交叉编译的 arm64 的可执行文件 在x86平台不可运行