
测试环境:
windows10 x64
vs2019
cmake==3.26.3
protobuf==3.15.0
configure,然后点击 renerate,生成好后点击 open projectprotobuf_BUILD_SHARED_LIBS:需选中该选项,则可编译动态链接库CMAKE_INSTALL_PREFIX:程序编译完成后安装的路径,默认在C盘,要求VS2019有管理员权限。protobuf_WITH_ZLIB:取消选中该选项
生成CMAKE_INSTALL_PREFIX 目录下获得对应的 lib/dll 文件以及头文件。${CMAKE_INSTALL_PREFIX}/bin 目录添加到环境变量 PATH 中,这样才能在命令行中使用 protoc 命令。

protobuf_demo 的空项目。person.proto,并生成 C++ 原文件。 person.proto 如下所示protoc --cpp_out=./ person.proto,生成了 person.pb.h 和 person.pb.ccperson.pb.h 中添加 #define PROTOBUF_USE_DLLS,不然编译会报错syntax = "proto3";
package tutorial;
message Person {
string name = 1;
int32 id = 2;
string email = 3;
}#include "person.pb.h"
#include <iostream>
int main() {
tutorial::Person person;
person.set_id(1);
person.set_email("john@gmail.com");
person.set_name("John");
std::cout << person.SerializePartialAsString() << std::endl;;
return 0;
}
C:\Program Files (x86)\protobuf项目 -> 属性 -> VC++目录 - > 包含目录:设置头文件路径为 C:\Program Files (x86)\protobuf\include项目 -> 属性 -> VC++目录 -> 库目录:设置lib文件路径 C:\Program Files (x86)\protobuf\lib项目 -> 链接器 -> 输入 -> 附加依赖项 中添加 libprotobufd.libC:\Program Files (x86)\protobuf\bin 添加到系统路径 PATH 中
*.ph.h 最前面添加 #define PROTOBUF_USE_DLLSfind_package 引入)
cmake 配置文件find_package(Protobuf) 以及 Protobuf_INCLUDE_DIRS 和 Porotuf_LIBRARIES 引入头文件和库文件。C:\Program Files (x86)\protobuf 中,find_package 以及各种参数都能正常使用。find_package 失败。find_package 引入 Protobuf,就需要手动将 protobuf 的头文件路径、链接文件路径等手动引入 CMakeLists.txt 中。Protobuf_INCLUDE_DIRS 和 Protobuf_LIBRARIES 两个参数。D:/vs/protobuf-3.20.1/vs_x64_out,那么CMakeLists.txt 文件形式可以参考下面# 一般引入方法(二选一)
find_package(Protobuf)
# 手动引入方法(二选一)
SET(Protobuf_INSTALL_DIR D:/vs/protobuf-3.20.1/vs_x64_out)
include_directories("${Protobuf_INSTALL_DIR}/include")
link_directories("${Protobuf_INSTALL_DIR}/lib")
SET(Protobuf_LIBRARIES libprotobufd libprotocd)
# 公用代码
include_directories(${Protobuf_INCLUDE_DIRS})
add_executable (protoc_demo protoc_demo.cpp person.pb.cc)
target_link_libraries(protoc_demo ${Protobuf_LIBRARIES})