首页 > 解决方案 > CMake for Proto 图书馆

问题描述

我在两个不同的文件夹中有两个 Proto 文件,我正在尝试使用 CMake 来构建整个项目。

但是为了生成 protofile1,我有 protofile2 作为它的依赖项。我如何使用 CMake 做到这一点?

如何编译 proto 文件并使用 CMake(在文件夹 2 中)将其作为库提供?

文件夹结构:

|
|-folder1
---|-protofile1.proto
---|-library1.cc
|-folder2
---|-protofile2.proto
---|-library2.cc

文件夹 1 的 CMakeLists.txt

cmake_minimum_required(VERSION 3.3)
find_package(Protobuf REQUIRED)
protobuf_generate_cpp(protofile1_cc protofile1_header protofile1.proto)
target_link_libraries(protofile1_cc INTERFACE protofile2_lib) # is this correct?

add_library(library1 INTERFACE)
target_sources(library1 INTERFACE library1.cc)
target_link_libraries(library1 INTERFACE protofile1_cc)

文件夹 2 的 CMakeLists.txt

cmake_minimum_required(VERSION 3.3)
find_package(Protobuf REQUIRED)
# don't know how to do this
add_library(protofile2_lib INTERFACE) # is this correct?
target_sources(protofile2_lib INTERFACE protofile2.proto) # is this correct?

标签: c++cmakeprotocol-buffersproto

解决方案


protobuf_generate_cpp命令没有定义targets,但它定义了引用自动生成的源文件 ( , ) 的 CMake变量。这些变量应该用于通过. 您走在正确的轨道上,但您的 CMakeLists.txt 文件也应该调用处理。.cc.hadd_library()folder2protobuf_generate_cppprotofile2.proto

此外,如果您使用 CMake 来构建两者,则顶级 CMake(在 和 的父文件夹中folder1folder2可以找到 Protobuf,因此您不必找到它两次。这样的事情应该让您更接近所需的解决方案:

CMakeLists.txt(顶级):

cmake_minimum_required(VERSION 3.3)
find_package(Protobuf REQUIRED)
add_subdirectory(folder2)
add_subdirectory(folder1)

文件夹2/CMakeLists.txt

# Auto-generate the source files for protofile2.
protobuf_generate_cpp(protofile2_cc protofile2_header protofile2.proto)
# Use the CMake variables to add the generated source to the new library.
add_library(protofile2_lib SHARED ${protofile2_cc} ${protofile2_header})
# Link the protobuf libraries to this new library.
target_link_libraries(protofile2_lib PUBLIC ${Protobuf_LIBRARIES})

文件夹 1/CMakeLists.txt

# Auto-generate the source files for protofile1.
protobuf_generate_cpp(protofile1_cc protofile1_header protofile1.proto)
# Use the CMake variables to add the generated source to the new library.
add_library(library1 SHARED ${protofile1_cc} ${protofile1_header})
# Link proto2 library to library1.
target_link_libraries(library1 INTERFACE protofile2_lib)

推荐阅读