mac下编译protobuf c++

来源:互联网 发布:上帝不会掷骰子 知乎 编辑:程序博客网 时间:2024/06/05 19:40

由于protobuf官网的文档是英文版的,并且并没有比较详细的说明(可能说得很清楚了,只是我这种英文渣看不懂),学习起来着实费了一翻功夫。

在此,记录一下学习过程,希望尽量详细。

一、编译过程需要的工具

1.protobuf源码,下载地址:https://github.com/google/protobuf/releases,看自己要先哪个版本,就选择对应的Source code,可以选择zip或者tar.gz格式。

2.g++(注意,一定是g++,gcc在链接c++的库时有时候是链接不到的),这个mac自带有,不用下载或者安装。

二、编译protobuf库

1.解压下载下来的protobuf文件,选一个比较幸运的文件夹(会增加你编译成功的概率哦,玩笑话:随便选啦)。

2.打开终端,cd到你解压出来的protobuf文件夹根目录(如:我下载的压缩包是3.2.0版本 解压出来会是protobuf-3.2.0,cd 你的目录/protobuf-3.2.0)。

3.依次执行下面的命令:

./autogen.sh

./configure

make

maek check

sudo make install

到此,编译步骤完毕。

上面的命令会把protobuf头文件放在/usr/local/include里的google文件夹;

protobuf库文件放在/usr/local/lib文件夹。

三、把test.proto文件编译成c++用的test.pb.cc和test.pb.h文件

编译test.proto文件有两个方式:

1.上面的几个命令已经把编译xxx.proto需要的脚本(protoc)放在了/usr/local/bin里,可以直接使用了;

2.在https://github.com/google/protobuf/releases里,我们选的Source code的同一个版本里有protobuf-版本号-osx-86_64.zip,下载解压,里面有个bin文件夹,里面的protoc和1里的protoc是一样的。

个人用的是第二种。

把编写好的test.proto文件移到这个bin文件夹里,和protoc同级。

test.proto文件。

syntax = "proto3";message Test {    string name = 1;    int32 age = 2;}


打开终端,cd到bin文件夹里,执行以下命令:

./protoc -I=./ --cpp_out=./ ./test.proto

注意,一定要是./protoc,如果是protoc会执行/usr/local/bin里的protoc,这样的话,如果你有其他版本的protobuf,就只会执行/usr/local/bin里的protoc,可能跟你想要的版本不一样。

三、写测试例子查看成果

1.新建test文件夹,在test文件夹里编写test.cpp文件

#include "stdio.h"#include "test.pb.h"int main(){Test *test = new Test();test->set_name("123");test->set_age(12345);printf("test  !!!!!\n");return 0;}
2.把刚刚编译出来的test.pb.cc和test.pb.h放在与test.cpp同级目录下

3.打开终端,cd到test目录下,执行g++ -o test test.cpp test.pb.cc -I /usr/local/include -L /usr/local/lib -lprotobuf,

生成test文件,执行test命令