目录
前期准备
- VS2019
- Cmake(这里用的是3.21.0-rc1)
- Git
protobuf项目地址
压缩包下载(推荐)
官方教程地址
https://github.com/protocolbuffers/protobuf/blob/master/cmake/README.md
克隆源码
下载压缩包的跳过该流程
release_tag 替换为自己需要的版本,如3.17.x。想看有哪些分支,点击branches。
然后使用, Developer Command Prompt for VS 2019(VS2019的开发者cmd)克隆项目。使用VS2019开发者cmd能够防止出现找不到nmake的问题。
git clone -b [release_tag] https://github.com/protocolbuffers/protobuf.git
源码安装准备
1.创建install文件夹
# install文件与protobuf文件夹同级
mkdir install
2.安装编译源码需要的子模块
下载压缩包的不要执行git submodule update --init --recursive
# 进入protobuf的目录
cd protobuf
# git克隆下来的源码才有.git文件夹,下载压缩包的不需要执行该指令
git submodule update --init --recursive
3.进入cmake的目录
# 当前路径protobuf\cmake
cd cmake
Cmake配置
1.创建目录
当前已经进入了cmake目录
# 当前路径protobuf\cmake
# 创建并进入build目录
mkdir build
cd build
# 当前路径protobuf\cmake\build
# 创建并进入release目录
mkdir release
cd release
需要构建debug版本就创建debug文件夹,并在下一节CMAKE_BUILD_TYPE参数设置为Debug
2.使用Release配置
如果使用PowerShell可能会出现nmake指令无法找到的情况
# 当前路径protobuf\cmake\build\release
cmake -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../../../../install ../..
执行上述代码并等待编译配置构建成功
3.生成Visual Studio解决方案文件
# 当前路径protobuf\cmake\build\release
cd ..
# 当前路径protobuf\cmake\build
# 创建并进入solution目录
mkdir solution
cd solution
# 当前路径protobuf\cmake\build\solution
cmake -G "Visual Studio 16 2019" -DCMAKE_INSTALL_PREFIX=../../../../install ../..
执行上述代码等待结束
编译
进入protobuf\cmake\build\solution路径,用VS2019打开protobuf解决方案文件
修改为Release版本
右键ALL_BUILD解决方案,点击生成
编译成功后,文件在solution里面的Release文件夹
安装
右键INSTALL解决方案,点击生成
就会在与protobuf同级的install文件夹生成所有需要的文件
生成DLL
将生成VS解决方案文件的指令改成下面这个。
cmake -G "Visual Studio 16 2019" -DCMAKE_INSTALL_PREFIX=../../../../install -Dprotobuf_BUILD_SHARED_LIBS=ON ../..
该指令只是在原来的基础上添加了下面这个选项
-Dprotobuf_BUILD_SHARED_LIBS=ON
最终dll文件生成在install\bin目录下
问题合集
- 使用git clone下来的源码编译可能会出现field_access_listener is not able to link in VS20xx的问题
解决方法:直接下载压缩包,估计是因为google几个子模块版本更新了,压缩包里面包含了protobuf对应的google子模块版本,就没有这个问题。