简体   繁体   English

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

[英]How To Export Compiled Protobuf to Static Library C++

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

Instead of using protoc manually you can let CMake compile the proto files.您可以让 CMake 编译 proto 文件,而不是手动使用 protoc。 To do so you will have CMakeLists.txt in the same folder as you proto files (I use a separate folder called proto here).为此,您将 CMakeLists.txt 与 proto 文件放在同一个文件夹中(我在这里使用了一个名为 proto 的单独文件夹)。 and this CMakeLists.txt will look like:这个 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
)

So as you can see you need to specify the proto files that you want to compile (first set ).如您所见,您需要指定要编译的 proto 文件(第一set )。 Then you need the specify the name of the generated cc and h file (second and third set ).然后您需要指定生成的 cc 和 h 文件的名称(第二和第三set )。 And then we use the custom command to generate automatically what you have been doing manually with protoc.然后我们使用自定义命令自动生成您使用 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 .最后,我们使用 add_library 创建一个名为 protos_lib.a 的libprotos.a (静态库)文件,并将 protobuf 依赖target_link_librariesadd_library链接。

Hope that helps, let me know if you need more details.希望对您有所帮助,如果您需要更多详细信息,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM