You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bazel与Protobuf:如何指定特定版本的protoc工具

Fixing Protocol Buffer Version Mismatch in Bazel Build

Let's break down your problem and walk through the solution step by step:

Root Cause Analysis

First, let's decode those version numbers in the pre-generated and custom proto files:

  • The pre-generated files use checks for 3009000/3009002 — that translates to protoc 3.9.0/3.9.2, meaning these files were built with protoc 3.9.2.
  • Your custom-generated files reference 3017000 (protoc 3.17.0), which comes from the newer protobuf version pulled in by your grpc dependency (grpc 1.44.0 defaults to a recent protobuf release, likely 3.19.x).

The error you're seeing:

#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer headers.

Happens because:

  • Your custom proto code is being generated with a newer protoc (from the grpc-provided protobuf)
  • But your build links against the older protobuf headers required by the pre-generated files
  • This version mismatch triggers the guard clauses in the generated .pb.h files

Step-by-Step Fix

1. Lock Protobuf to the Required Version (3.9.2)

We need to force Bazel to use protobuf 3.9.2 (matching your pre-generated files) instead of the newer version pulled in by grpc. Add this before the grpc_deps() call in your WORKSPACE file:

# Pin protobuf to 3.9.2, matching the pre-generated files' protoc version
http_archive(
    name = "com_google_protobuf",
    sha256 = "9b1a5215d4d9e72d32d98485d9346587f6f2106e1472f7591e87f82d7a9f4e0e",
    strip_prefix = "protobuf-3.9.2",
    urls = [
        "https://github.com/protocolbuffers/protobuf/archive/v3.9.2.tar.gz",
    ],
)

2. Update grpc_deps to Skip Default Protobuf

Modify your grpc_deps() call to tell grpc not to pull its own protobuf version — we'll use our pinned 3.9.2 instead:

grpc_deps(
    omit_protobuf = True,
)

3. Verify the Protoc Version

Run these commands to confirm Bazel is using the correct protoc:

# Build the protoc binary from our pinned dependency
bazel build @com_google_protobuf//:protoc

# Check its version
bazel-bin/external/com_google_protobuf/protoc --version

You should see libprotoc 3.9.2 printed.

4. Rebuild Your Project

Clean your existing build artifacts and rebuild:

bazel clean
bazel build //your/target/path:your_target

Why This Works

  • By pinning protobuf to 3.9.2, we ensure both the protoc used to generate your custom proto code and the protobuf headers/libraries used during compilation match the version of your pre-generated files.
  • This eliminates the version mismatch that was triggering the #error guards in the generated .pb.h files.

内容的提问来源于stack exchange,提问作者slai-nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 19:03:15