CMake for Proto libraires

CMake for Proto libraires

本文关键字:libraires Proto for CMake      更新时间:2023-10-16

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

  • protofile1 具有 protofile2 作为依赖项。
  • Library1 具有原型文件1,因为它是我可以使用protobuf_generate_cpp生成的依赖项。

但是为了生成原型文件1,我有原型文件2,因为它是依赖关系。如何使用 CMake 执行此操作?

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

文件夹结构:

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

CMakeLists.txt for folder1

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 for folder2

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命令不定义目标,但它定义引用自动生成的源文件的 CMake变量(.cc.h(。这些变量应该用于通过add_library()定义目标。您走在正确的轨道上,但 CMakeLists.txtfolder2中的文件也应该调用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)

文件夹2/CMake列表.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/CMake列表.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)