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

Bazel中cc_binary如何添加对非源码/库的生成文件的构建依赖

解决方案

针对Bazel cc_binary规则需要依赖自定义生成的编译配置文件、链接脚本的需求,有两种成熟可行的方案:


方案1(推荐,适用于Bazel 4.0及以上版本)

使用cc规则原生提供的additional_compiler_inputs和additional_linker_inputs属性,这两个属性是专门用于添加编译、链接阶段的额外依赖文件,既不会被识别为源码/库文件,也不会被计入运行时依赖。
修改后的规则写法如下:

cc_binary(
    name = "bsp",
    srcs = ["src/rtos_main.c"],
    # 编译阶段依赖:保证编译执行前完成compiler_file的构建
    additional_compiler_inputs = [":compiler_file"],
    # 链接阶段依赖:保证链接执行前完成linkfile的构建
    additional_linker_inputs = [":linkfile"],
    copts = ["-@$(execpath :compiler_file)"],
    linkopts = ["$(execpath :linkfile)"],
)

注意:linkopts中不需要额外加./前缀,$(execpath)本身会返回文件相对于构建执行根目录的正确相对路径。


方案2(兼容旧版本Bazel)

如果使用的Bazel版本低于4.0,没有上述两个属性,可以把两个生成文件直接加入srcs属性,cc规则会自动将非源码/库类型的输入识别为构建前置依赖,配合no-ide标签避免IDE把生成文件误识别为业务源码:

cc_binary(
    name = "bsp",
    srcs = [
        "src/rtos_main.c",
        ":compiler_file",
        ":linkfile",
    ],
    copts = ["-@$(execpath :compiler_file)"],
    linkopts = ["$(execpath :linkfile)"],
    # 避免IDE解析生成文件
    tags = ["no-ide"],
)

内容的提问来源于stack exchange,提问作者Mohamed Mahrous

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 17:24:03