【问题标题】:Protobuf Compilation error while importing messages from other files从其他文件导入消息时 Protobuf 编译错误
【发布时间】:2020-07-20 13:09:04
【问题描述】:

我有 2 个 protobuf 文件文件 -

file1.proto

**package abcd.xyz**

message Msg1{
   uint32 id =1;
   string name = 2;
}

file2.proto

**package com.abcd.xyz**

import "abcd/xyz/Msg1.proto";

message Msg2{
   uint32 id =1;
   string name = 2;
   Msg1 msg = 3;
}

当我编译这个时,得到以下错误 -

 [exec] com/abcd/xyz/Msg2.proto:5: "abcd.xyz.Msg1" is resolved to "com.abcd.xyz.Msg1", which is not defined. The innermost scope is searched first in name resolution. Consider using a leading '.'(i.e., ".abcd.xyz.Msg1") to start from the outermost scope.

Msg1.proto 文件在多个地方使用,我无法更改它的包。

知道在不更改包名的情况下编译 Msg2.proto 文件需要做哪些更改吗?

【问题讨论】:

    标签: java protocol-buffers grpc


    【解决方案1】:

    这是我能够运行的示例,希望能帮助您解决问题。当我查看您的代码时,我注意到您导入了包,但没有在消息 Msg2 的定义中指定 Msg1 的包位置。为确保您理解我告诉您的内容,让我向您展示一个示例,您的代码在执行此操作后的外观:

    现在我有当前项目目录:

    testprotoc
     - test
        - file1.proto
     - xyz
        - file2.proto
    

    其中 testxyztestprotoc 主包的内部包。

    file1.proto 如下所示:

    syntax = "proto3";
    
    package testprotoc.test;
    
    message Msg1 {
       uint32 id =1;
       string name = 2;
    }
     
    

    因此,您指定协议缓冲区包和 protobuf 将使用的语法。然后我们有了file2.proto:

    syntax = "proto3";
    
    package testprotoc.xyz;
    
    import "test/file1.proto";
    
    message Msg2 {
       uint32 id =1;
       string name = 2;
       test.Msg1 msg = 3;
    }
    

    我们有相同的东西,语法,包,我们有进口。 内包的相对导入,不包括主包

    请务必注意我在使用时指定了消息定义的包。这就是你缺少的一点,这就是解决它的方法!

    【讨论】:

      猜你喜欢
      • 2021-03-17
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 2019-05-19
      • 1970-01-01
      • 2016-01-02
      • 2019-12-11
      • 1970-01-01
      相关资源
      最近更新 更多