为 Proto 图书馆员准备的 CMake

CMake for Proto libraires

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

但是为了生成 protofile1,我有 protofile2 作为它的依赖项。我如何使用 CMake 执行此操作?

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

文件夹结构:

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

CMakeLists.txt 文件夹 1

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)

CMakeLists.txt 文件夹 2

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?

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

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

CMakeLists.txt(顶级):

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

folder2/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})

folder1/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)