如何将编译的Protobuf导出到静态库C++

发布于 2025-02-05 15:23:02 字数 64 浏览 1 评论 0原文

我想制作一个包含.cc和.h文件的静态库,这些库是从Protoc编译器生成的,以与其他项目链接,我正在使用C ++

I want to make a static library containing .cc and .h files that are generated from protoc compiler to link with it from other project, I'm using C++

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

も让我眼熟你 2025-02-12 15:23:02

而不是手动使用ProtoC,您可以让CMAKE编译原始文件。为此,您将在与原始文件的同一文件夹中使用cmakelists.txt(我在此处使用一个称为proto的单独文件夹)。而且此cmakelists.txt看起来像:

# Proto files
set(proto
    test.proto
    # maybe others
)

# Generated sources
set(proto_srcs
    ${CMAKE_BINARY_DIR}/proto/test.pb.cc
    # maybe others
)

# Generated headers
set(proto_hdrs
    ${CMAKE_BINARY_DIR}/proto/test.pb.h
    # maybe others
)

add_custom_command(
    OUTPUT ${proto_srcs} ${proto_hdrs}
    COMMAND protoc
    ARGS --cpp_out ${CMAKE_BINARY_DIR}/proto
        -I ${CMAKE_SOURCE_DIR}/proto
        ${proto} 
    DEPENDS ${proto}
)

add_library(protos
    ${proto_srcs}
    ${proto_hdrs}
)
target_link_libraries(protos
    libprotobuf
)

因此,您需要看到需要指定要编译的proto文件(第一个set)。然后,您需要指定生成的CC和H文件的名称(第二和第三set)。然后,我们使用自定义命令自动生成您使用ProtoC手动做的事情。

最后,我们使用protos_lib.a创建一个libprotos.a(静态库)文件,用add_library,然后将ProtoBuf依赖关系与targe> target_link_libraries链接。

希望有帮助,让我知道您是否需要更多细节。

Instead of using protoc manually you can let CMake compile the proto files. To do so you will have CMakeLists.txt in the same folder as you proto files (I use a separate folder called proto here). and this CMakeLists.txt will look like:

# Proto files
set(proto
    test.proto
    # maybe others
)

# Generated sources
set(proto_srcs
    ${CMAKE_BINARY_DIR}/proto/test.pb.cc
    # maybe others
)

# Generated headers
set(proto_hdrs
    ${CMAKE_BINARY_DIR}/proto/test.pb.h
    # maybe others
)

add_custom_command(
    OUTPUT ${proto_srcs} ${proto_hdrs}
    COMMAND protoc
    ARGS --cpp_out ${CMAKE_BINARY_DIR}/proto
        -I ${CMAKE_SOURCE_DIR}/proto
        ${proto} 
    DEPENDS ${proto}
)

add_library(protos
    ${proto_srcs}
    ${proto_hdrs}
)
target_link_libraries(protos
    libprotobuf
)

So as you can see you need to specify the proto files that you want to compile (first set). Then you need the specify the name of the generated cc and h file (second and third set). And then we use the custom command to generate automatically what you have been doing manually with protoc.

Finally, we create a libprotos.a (static library) file called protos_lib.a with the add_library and link the protobuf dependency with target_link_libraries.

Hope that helps, let me know if you need more details.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文