Protocol Buffers 學習筆記

1、安裝
ubuntu下的安裝很簡單(雖然要安裝幾個包):
具體參見:[url]https://github.com/google/protobuf/blob/master/src/README.md[/url]
從github下載了源碼後:
$ sudo apt-get install autoconf automake libtool curl make g++ unzip
$ ./autogen.sh
$ ./configure
$ make
$ make check
$ sudo make install
$ sudo ldconfig # refresh shared library cache.


[color=red]只編譯靜態庫:[/color]
./configure --disable-shared



2、編譯
.proto文件編譯:
protoc addressbook.proto --cpp_out .  # 用於生成C++頭文件和.cc文件
protoc addressbook.proto --python_out . #用於生成python相應的文件

注意: 可以通過 -I 參數更改搜索路徑, 所有文件的路徑必須爲絕對路徑,,
比如官方給的例子(除了上面那種所有文件都在當前文件夾的情況):
protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/addressbook.proto

c++文件編譯:
下面命令中的pkg-config --cflags --libs protobuf會生成proto buff所需的編譯選項(頭文件目錄,-pthread等)
c++ my_program.cc my_proto.pb.cc `pkg-config --cflags --libs protobuf`


3、教程
python版:[url]https://developers.google.com/protocol-buffers/docs/pythontutorial[/url]
可以print(proto)來看proto實例的內容
C++版:[url]https://developers.google.com/protocol-buffers/docs/cpptutorial[/url]
每個proto類都有一個DebugString()方法,用於返回供人看的內容

完成編譯命令:
#只能用g++ 用gcc不行!
echo compile c++ part
protoc addressbook.proto --cpp_out .
g++ writeAddress.cc addressbook.pb.cc -o write.out `pkg-config --cflags --libs protobuf`
g++ readAddress.cc addressbook.pb.cc -o read.out `pkg-config --cflags --libs protobuf`

echo use ./write.out add.txt to generate address file
echo use ./read.out add.txt to read address file

echo compile python part
protoc addressbook.proto --python_out .
echo use python writeAddress.py add.txt to generate address file
echo use python readAddress.py add.txt to read address file


官方教程中有一些錯誤,,完整的代碼(包含編譯用的shell命令)見附件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章