protobuf-c的使用(一)构建

protobuf很出名,是google开发的序列化库,很多公司都使用它作为接口的数据结构。地址:https://developers.google.com/protocol-buffers/ 
支持java、c++、go等多种语言,几乎所有主流语言都支持,但是官方没给出c语言的支持。经过一番寻找,找到了protobuf-c。在github中有很多protobuf c版本的实现,不过个人感觉还是这个protobuf-c更直接。其github地址:https://github.com/protobuf-c/protobuf-c 。 
在接下来的文章中,我会介绍protobuffer的结构和语法。同时说明protobuf-c的使用。在这篇文章中,先来试试构建protobuf-c。

在构建protobuf-c之前,我们需要安装一些依赖库:autoconf、automake、protobuffer、libtool,当然也需要一些基本的系统依赖(如:gcc-c++等)。autoconf、automake和libtool可以直接使用apt-get、yum、brew等安装。protobuffer虽然也可以使用libprotobuf,不过还是推荐源码安装。这里有一些坑,我会在下面逐一说明。注意安装环境这里只介绍mac和linux,linux采用debian系列的。

一、安装依赖

下面逐一安装依赖:

  1. mac下安装:mac下使用brew安装,如果读者没有安装brew,请自行参考http://www.brew.sh

    sudo brew install autoconf automake libtool

    这里写图片描述


linux下安装:debian系列使用apt-get安装,rhel系列使用yum安装。
sudo apt-get install automake autoconf libtool

这里写图片描述

二、构建protobuffer

构建protobuffer其实mac和linux上没任何区别,但是需要注意在mac El Capitan 版本中加入了Rootless,不能使用root对/usr/include进行增删改。在构建protobuffer和protobuf-c的时候会将一些c的头文件写到/usr/include下,方便调用。所以我们需要把Rootless禁用掉,禁用方法如下:

  1. 重启mac,按住command+R进入恢复模式

  2. 等待一段时间后,选择恢复模式使用的语言,进入恢复模式

  3. 打开终端,输入csrutil disalble,可以直接禁用Rootless。

  4. 重启mac。

需要注意,在构建完protobuffer和protobuf-c以后建议恢复Rootless,跟禁用方式相同,只不过把命令改成csrutil enable即可。 
下面介绍构建protobuffer,这里使用2.6.1:

  1. 从 https://github.com/google/protobuf/releases/tag/v2.6.1 下载2.6.1的源码包:protobuf-2.6.1.tar.gz解压

    tar zxvf protobuf-2.6.1.tar.gz

  2. 执行./autogen.sh脚本,生成configure配置脚本。

    这里写图片描述

  3. 执行./configure配置,注意最好指定一下安装参数 
    ./configure --prefix=/usr/local/protobuf -- 
    libdir=/usr/lib
     
    这里写图片描述

  4. 执行make进行构建 
    这里写图片描述

  5. 执行sudo make install安装 
    这里写图片描述

三、构建protobuf-c

注意如果在构建protobuf-c之前没有安装protobuf的话,生成protobuf-c的configure文件肯定会报如下错误!!

configure: error: Package requirements (protobuf >= 2.6.0) were not 
met:No package ‘protobuf’ found

构建protobuf-c其实跟protobuffer几乎没任何区别,也是通过autogen.sh脚本生成configure配置脚本,然后执行make和install。但是需要注意的是protobuf-c在构建的时候不会自动把相关头文件拷贝到/usr/include下,需要手动拷贝。

https://github.com/protobuf-c/protobuf-c.git 克隆下protobuf-c源码。

git clone https://github.com/protobuf-c/protobuf-c.git

与构建protobuffer一样,分别执行:

./autogen.sh

这里写图片描述

./configure --prefix=/usr/local/protobuf-c --libdir=/usr/lib/

注意prefix不要与protobuffer一样,会覆盖protobuffer

这里写图片描述

make

这里写图片描述

sudo make install1

这里写图片描述

最后把头文件拷贝到/usr/include下

sudo cp -r /usr/local/protobuf-c/include/protobuf-c /usr/include


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章