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系列的。
一、安裝依賴
下面逐一安裝依賴:
mac下安裝:mac下使用brew安裝,如果讀者沒有安裝brew,請自行參考http://www.brew.sh。
sudo brew install autoconf automake libtool
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禁用掉,禁用方法如下:
重啓mac,按住command+R進入恢復模式
等待一段時間後,選擇恢復模式使用的語言,進入恢復模式
打開終端,輸入
csrutil disalble
,可以直接禁用Rootless。重啓mac。
需要注意,在構建完protobuffer和protobuf-c以後建議恢復Rootless,跟禁用方式相同,只不過把命令改成csrutil enable
即可。
下面介紹構建protobuffer,這裏使用2.6.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
執行./autogen.sh腳本,生成configure配置腳本。
執行./configure配置,注意最好指定一下安裝參數
./configure --prefix=/usr/local/protobuf --
libdir=/usr/lib執行
make
進行構建執行
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