首页 > 解决方案 > Cmake 3.1 +“Protobuf_IMPORT_DIRS”导入另一个.proto错误

问题描述

我对 CMAKE 还是很陌生,但我find_package(Protobuf Requried)习惯于编译我的 .proto 文件作为构建的一部分,我无法让导入工作,而且我真的很难过。

我在同一个目录中有 2 个 .proto 文件,名为“A.proto”和“B.proto”的“protobuf”

没有导入,它们编译得很好。

如果我将 A.proto 更改为对 B 的导入:

syntax = "proto3";
import "B.proto";


message MyMessage
{}

Protobuf_IMPORT_DIRS使用正确设置变量的 CMakeLists.txt 文件(我认为):

find_package(Protobuf REQUIRED)
set(Protobuf_IMPORT_DIRS ${Protobuf_IMPORT_DIRS} ${CMAKE_SOURCE_DIR}/protobuf) 

...

protobuf_generate(TARGET ${MY_PROJECT_NAME})

我在构建时得到了这个:

  Running cpp protocol buffer compiler on protobuf/A.proto
  B.proto: File not found.
  protobuf/A.proto:3:1: Import "B.proto" was not found or had errors.

任何帮助将不胜感激,因为我觉得我正在服用疯狂的药丸!:)

标签: cmakeprotocol-buffers

解决方案


所以我找到了答案,尽管它需要一些黑客攻击。基本上我只是阅读了所有与 Protobuf 相关的 CMAKE 文件,直到我弄明白为止。那里可能有更好的文档,但我找不到。

短篇故事:

如果你打电话PROTOBUF_GENERATE_CPP,它尊重设置一个Protobuf_IMPORT_DIRS变量。

但是,如果您protobuf_generate像我一样直接调用目标,则该变量将被忽略。

答案是protobuf_generate使用 IMPORT_DIRS 的参数进行调用,例如:

protobuf_generate(TARGET ${MY_PROJECT_NAME} IMPORT_DIRS protobuf)

IMPORT_DIRS 是一个多参数,您可以提供多个参数。

以下是相关代码:

function(protobuf_generate)
  include(CMakeParseArguments)

  set(_options APPEND_PATH)
  set(_singleargs LANGUAGE OUT_VAR EXPORT_MACRO PROTOC_OUT_DIR PLUGIN)
  if(COMMAND target_sources)
    list(APPEND _singleargs TARGET)
  endif()
  set(_multiargs PROTOS IMPORT_DIRS GENERATE_EXTENSIONS)

  cmake_parse_arguments(protobuf_generate "${_options}" "${_singleargs}" "${_multiargs}" "${ARGN}")

我希望这将在未来避免一些人头疼!


推荐阅读