2. 使用
$ cd protobuf-2.4.1 $ ./configure; $ make $ make check $ make install
此处需要注意,在ubuntu下,需要添加共享库路径:
export LD_LIBRARY_PATH=/usr/lib/local
目录./protobuf-2.4.1/examples下有一个例子,功能简单,一个程序使用使用pb定义的类型写数据到一个文件,另一个程序读取该文件。
目标语言为c++的编译方式如下:
$ make cpp protoc --cpp_out=. --java_out=. --python_out=. addressbook.proto pkg-config --cflags protobuf # fails if protobuf is not installed -pthread -I/usr/local/include c++ add_person.cc addressbook.pb.cc -o add_person_cpp `pkg-config --cflags --libs protobuf` pkg-config --cflags protobuf # fails if protobuf is not installed -pthread -I/usr/local/include c++ list_people.cc addressbook.pb.cc -o list_people_cpp `pkg-config --cflags --libs protobuf`
运行:
$ ./add_person_cpp test.txt test.txt: File not found. Creating a new file. Enter person ID number: 123456 Enter name: zxm Enter email address (blank for none): [email protected] Enter a phone number (or leave blank to finish): 12300000000 Is this a mobile, home, or work phone? home Enter a phone number (or leave blank to finish): $./list_people_cpp test.txt Person ID: 123456 Name: zxm E-mail address: [email protected] Home phone #: 12300000000
上述例子的分析可参考:http://code.google.com/apis/protocolbuffers/docs/cpptutorial.html
package tutorial; // message Person { required string name = 1; required int32 id = 2; optional string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; } repeated PhoneNumber phone = 4; } message AddressBook { repeated Person person = 1; }
说明:
required
: a value for the field must be provided, otherwise the message will be considered "uninitialized"
optional
: the field may or may not be set. If an optional field value isn't set, a default value is used.
required
. If at some point you wish to stop writing or sending a required field, it will be problematic to change the field to an optional field – old readers will consider messages without this field to be incomplete and may reject or drop them unintentionally. You should consider writing application-specific custom validation routines for your buffers instead. Some engineers at Google have come to the conclusion that usingrequired
does more harm than good; they prefer to use onlyoptional
andrepeated
. However, this view is not universal.