Linux环境下Protobuf完整安装和使用教程

Linux环境下Protobuf完整安装和使用教程

原文地址:https://blog.csdn.net/yahohi/article/details/108310609

下载和安装

1、下载protobuf安装包

$ git clone https://github.com/protocolbuffers/protobuf.git

2、安装依赖库

$ cd protobuf/
$ ./autogen.sh
$ ./configure --prefix=/usr/local/protobuf
$ make
$ sudo make install
$ sudo ldconfig                  // 刷新共享库,很重要的一步

3、检查安装是否成功

$ protoc --version
环境配置

1、添加环境变量

sudo vim /etc/profile

添加:

export PATH=$PATH:/usr/local/protobuf/bin/
export PKG_CONFIG_PATH=/usr/local/protobuf/lib/pkgconfig/

2、然后,刷新环境变量:

source /etc/profile

3、按照上述方式修改~/.profile。

4、配置动态链接库路径

sudo vim /etc/ld.so.conf

添加:

/usr/local/protobuf/lib
一个例子
1、报文定义
syntax = "proto3";
message SearchResponse {
  message Result {
    string url = 1;
    string title = 2;
    int64  telephone = 3;
    repeated string snippets = 4;
  }
  repeated Result results = 1;
}
2、报文生成

执行如下命令:

protoc --cpp_out=./ testproto.proto

就会在该目录下生成如下文件:

testproto.pb.h
testproto.pb.cc
3、使用报文
#include <iostream>
#include "testproto.pb.h"
#include <string>
using namespace std;

int main()
{
    GOOGLE_PROTOBUF_VERIFY_VERSION;
    SearchResponse sr;
    
    SearchResponse_Result* result = sr.add_results();
    result->set_url("url ...");
    
    string str = sr.SerializeAsString();
    std::cout << str << endl;
    return 0;
}
4、编译程序
g++ -g -I/usr/local/ -I/usr/local/protobuf/ -I/usr/local/bin/ -I/usr/local/protobuf/include/google/protobuf/ -I/usr/local/protobuf/include/ -std=c++11 -MMD -MP -MF -lprotobuf -pthread -o testproto testproto.pb.o testproto.pb.cc

特别注意, -lprotobuf -pthread一定要添加!

5、常见问题:

问题1:

对‘google::protobuf::internal::VerifyVersion(int, int, char const*)’未定义的引用

解决方案:
在编译命令中添加**-lprotobuf**选项。

问题2:
编译通过,但运行时报错:

terminate called after throwing an instance of 'google::protobuf::FatalException'
  what():  CHECK failed: (scc->visit_status.load(std::memory_order_relaxed)) == (SCCInfoBase::kRunning): 

解决方案:
在编译命令中添加** -pthread**选项。