QT集成Protobuf

发布于:2024-03-01 ⋅ 阅读:(70) ⋅ 点赞:(0)

1.定义protobuf

package ImageRender;

message MessagePadding
{
  required int32 left = 1;
  required int32 top = 2;
  required int32 right = 3;
  required int32 bottom = 4;
}

2.通过protoc.exe编译proto文件
一般可以写一个bat来执行命令:

%~d0
cd %~p0

rem The following adds the paths of both tf.exe and MsBuild.exe.
set PATH="E:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\cmd";C:\Windows\Microsoft.NET\Framework\v4.0.30319;%PATH%

rem generate cpp code
"./protoc.exe"  --proto_path =./  --cpp_out=../ProtoInclude  ./xxxxx.proto

pause

错误解决

  1. 找不到生成的.h头文件
#设置pb生成的文件目录
set(PROJECT_PROTO_DIR ${PROJECT_SOURCE_DIR}/ProtoInclude)
message(STATUS "PROJECT_PROTO_DIR is ${PROJECT_PROTO_DIR}")

#定义头文件需要寻址的路径
include_directories(
        XXXXX
        ${PROJECT_PROTO_DIR}
        XXXXX
)
  1. 编译过程中出现LINK2019的问题:
    在这里插入图片描述

解决:
需要加入依赖的lib【libprotobuf64与libprotobuf-lite】,并把自动生成的cc文件引入到项目。

set(PB_CC_FILES
    ${PROJECT_SOURCE_DIR}/ProtoInclude/xxxxx.pb.cc
)

#把目录src和inc下面的所有文件作为变量存储
file(GLOB_RECURSE SRC_FILES "src/*")
file(GLOB_RECURSE INC_FILES "include/*")

add_executable(DemoApp1 ${SRC_FILES} ${INC_FILES} ${PB_CC_FILES})
target_link_libraries(DemoApp1
         XXXXX
        libprotobuf64
        libprotobuf-lite
)