如何查询Bazel构建C/C++目标所使用的编译器标志?
查询Bazel构建C/C++目标的编译器标志
下面是几种实用的方法来获取Bazel构建C/C++目标时使用的编译器标志:
方法1:用bazel cquery精准查询
cquery可以直接查询目标的编译配置,结合Starlark输出格式能提取具体的编译器选项。比如要查询//path/to:target这个cc_binary或cc_library的编译器标志,执行:
bazel cquery //path/to:target --output=starlark --starlark:expr="target.files.to_list()[0].compilation_context().copts"
如果要包含系统默认的编译标志(比如来自cc_toolchain的选项),可以调整表达式:
bazel cquery //path/to:target --output=starlark --starlark:expr="target.files.to_list()[0].compilation_context().copts + target.files.to_list()[0].compilation_context().system_copts"
方法2:构建时打印完整编译命令
用bazel build加上--subcommands参数,构建过程中会输出每一步的完整命令,其中就包含所有编译器标志:
bazel build //path/to:target --subcommands
如果目标已经构建过,可以先清理再构建确保输出完整:
bazel clean && bazel build //path/to:target --subcommands
另外,--verbose_failures参数也能在编译失败时打印完整的编译命令,适合排查问题时使用。
方法3:生成编译数据库查看
Bazel可以生成标准的compile_commands.json文件,里面记录了每个源文件的编译命令和标志。执行以下命令生成:
bazel build //path/to:target --aspects @bazel_tools//tools/cpp:compile_commands_generator.bzl%compile_commands_generator --output_groups=compile_commands
生成的文件会在bazel-bin/compile_commands.json,打开后每个条目里的command字段就包含了完整的编译命令,从中可以提取编译器标志。
内容的提问来源于stack exchange,提问作者Sogartar
相关产品推荐
相关产品推荐

