1、安装vs2015
2、 安装cmake https://cmake.org/download/
3、下载protobuff 3.1.0 https://github.com/google/protobuf/releases/
解压protobuf压缩包,在和protobuf同级目录下新建一个install文件夹,用作编译完成后方include ,lib等文件。
E:\path\install
E:\path\protobuf-3.1.0
从VS开发人员命令行工具进入protobuf目录,创建build目录
创建release版本的编译目录:
创建debug版本的编译目录:
创建生成visual stuido 工程的文件夹:
这一步需要注意的是,
以上3种不是必须都做。
通过以上3个步骤,可以见到在不同目录都生成了相应的makefile文件,接下来是执行nmake进行编译:
到此,release 和 debug版本都编译成功,vs可以使用了。
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
vs平台开发用sln生成库要注意两点:
第一:
solution目录下有生成sln文件,可以用vs打开生成库,但要注意位数,比如如果
=====================================================================================================================================
2.D:\protobuf-2.6.1\examples本来是有例子的,我们亲自实践下,动手自己在此目录下定义一个proto:
[plain] view plaincopy在CODE上查看代码片派生到我的代码片
package tutorial;
message Person {
required string name = 1;
required int32 age = 2;
optional string email = 3;
}
然后使用cmd运行protoc.exe生成我们的目标语言格式(c++).
通过命令行将.proto的文件生成为.cpp的文件官网上是这样写的
protoc -I=$SRC_DIR --cpp_out=$DST_DIR$SRC_DIR/addressbook.proto
-I=$SRC_DIR 是源文件目录
--cpp_out=$DST_DIR是目标文件目录,cpp_out表示输出为cpp文件
$SRC_DIR/addressbook.proto表示要转换的的文件,包括目录和文件名
源文件目录如果省略,就代表是当前目录
目标文件如果省略,就代表输出目录是当前目录
示例:省略版
protoc-2.4.1-win32>protoc.exe ./addressbook.proto --cpp_out=./
示例:完整版
cd D:\protobuf-2.6.1\vsprojects\Debug
D:\protobuf-2.6.1\vsprojects\Debug>protoc-I=D:\protobuf-2.6.1\examples --cpp_out=D:\protobuf-2.6.1\examplesD:\protobuf-2.6.1\examples\person.proto
然后可以看到,生成了person.pb.h和person.pb.cc的文件。
3.我们用vs2012新建一个空的项目,选择属性,配置一下:
点击配置属性 下的 C/C++ 的 常规,右边附加包含目录,导入这个路径D:\protobuf-2.6.1\src
点击链接器的常规,右边的附加库目录,导入这个路径D:\protobuf-2.6.1\vsprojects\Debug
三.开始一个最简单的项目
好了,一切配置好了,该写代码了,我们做一个最简单的输入输出。新建一个main.cpp,然后把之前生成的person.pb.h和person.pb.cc复制到项目里面,并添加到项目里面。
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
#include <iostream>
#include "person.pb.h"
using namespace std;
using namespace tutorial;
int main()
{
Person person;
person.set_name("flamingo");
person.set_age(18);
cout<<person.name()<<endl;
cout<<person.age()<<endl;
system("pause");
return 0;
}
有些人说可以正常运行,但是我这边不行,主要是
网上查找原因,终于发现,需要在代码里面加两行:
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
#pragma comment(lib,"libprotobuf.lib")
#pragma comment(lib,"libprotoc.lib")
就能正常跑了: