下载
下载protobuf和cmake到目录,路径不能包含中文
protobuf
vs2015用protobuf-3.5.1
vs2022用protobuf-3.11.2以上,我用3.17.2
3.17 https://github.com/protocolbuffers/protobuf/releases/tag/v3.17.2
3.5.1: https://github.com/google/protobuf/releases/download/v3.5.1/protobuf-all-3.5.1.zip
cmake: https://cmake.org 我用的是 https://cmake.org/files/v3.11/cmake-3.11.0-rc2-win64-x64.msi
编译
1、用camke生成vs2022的项目文件

打开vs2022的x64命令行(我这是生成64位的文件,如果需要生成32位的,打开对应32位命令行即可) ,因为里面编译参数里有一个CL链接器的数据-CMAKE_C_COMPILER,直接用命令行需要手动传入,用vs的命令行则自带这些环境变量。

使用 VS2022开发人员命令提示 进入 protobuf 的 cmake 目录
cd D:\Develop\protobuf\protobuf-3.17.2\cmake
mkdir build & cd build
mkdir release & cd release
cmake -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Release -Dprotobuf_BUILD_TESTS=OFF -DCMAKE_INSTALL_PREFIX=../../../../install ../..

2、接着用vs下面的nmake继续编译项目文件为lib和exe
nmake
nmake install


ps:如果要编译debug版本,和上面一样,在build下面建立debug目录
mkdir debug & cd debug
cmake -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX=../../../../install ../..
nmake
nmake install
编译完成后的文件

使用
nmake install生成后的文件

包含proto.exe,include文件,libprotobuf.lib,libprotobuf-lite.lib,libprotoc.lib
接下来我们要用相同版本的proto.exe把user.proto数据输出为c++文件,
把user.prot放到同目录
protoc.exe --cpp_out=. user.proto

如果user.proto是在其他文件夹,咱们可以创建一个bat来快速生成
echo "以下命令,会编译.proto,生成c++的文件"
D:\Projects\VC\protobuf\install\bin\protoc.exe --cpp_out=. user.proto
pause
把生成的数据结构文件
user.pb.cc,user.pb.h,还有proto的include和lib文件复制到你的项目中就可以了。

在项目配置中把proto加入包含目录

代码
#include "user.pb.cc"
test(){
protoUser::User user;
user.set_name("jack");
printf("user:%s",user.name().c_str());
}
网友评论