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

如何在Meson构建系统中原生获取项目及外部库的Git信息?

Meson原生获取Git版本信息的解决方案

一、当前项目GITREF获取失败的问题修复

你之前的写法存在三个问题:

  • vcs_tag的command参数要求每个命令参数单独作为数组元素,不能将整行命令作为单个字符串传入
  • git命令拼写错误,你写成了git descibe,缺少字母r,正确写法为git describe
  • 未将生成的头文件依赖加入到最终构建目标的关联项中,Ninja不会主动生成未被引用的目标

正确写法如下:

  1. 保留infoBuild.h.in原有内容:
#define GITREF "BRANCHNAME"
  1. 调整meson.build中的vcs_tag写法,并关联到构建目标:
# 生成带Git版本的头文件
info_dep = vcs_tag(
  command: ['git', 'describe', '--all'],
  input: 'infoBuild.h.in',
  output: 'infoBuild.h',
  replace_string: 'BRANCHNAME'
)

# 将info_dep加入到你的二进制目标的源文件列表中
executable(
  '你的二进制程序名',
  sources: ['main.c', info_dep],
  # 其他原有编译参数保持不变
)

二、外部目录lib1版本信息获取

不需要bash脚本,Meson原生支持指定工作目录执行命令,结合对应内置模块即可实现:

方案1:配置阶段读取一次(适合lib1不常变更的场景)

# 查找git程序
git = find_program('git', required: true)

# 指定lib1目录执行git describe命令
lib1_git_ret = run_command(
  git, ['describe', '--tags'],
  working_directory: '../../lib1', # 替换为你的lib1实际路径
  check: true,
  capture: true
)
lib1_ver = lib1_git_ret.stdout().strip()

如果需要将LIB1_VER也写入头文件,修改infoBuild.h.in:

#define GITREF "BRANCHNAME"
#define LIB1_VER "@LIB1_VER@"

调整meson.build处理两步替换:

# 第一步替换LIB1_VER占位符
info_build_pre = configure_file(
  input: 'infoBuild.h.in',
  output: 'infoBuild.h.pre',
  configuration: {'LIB1_VER': lib1_ver}
)

# 第二步用vcs_tag替换BRANCHNAME占位符
info_dep = vcs_tag(
  command: ['git', 'describe', '--all'],
  input: info_build_pre,
  output: 'infoBuild.h',
  replace_string: 'BRANCHNAME'
)

# 同样将info_dep加入构建目标的源列表即可

方案2:每次构建自动更新lib1版本(适合lib1频繁开发的场景)

用custom_target实现每次构建时自动拉取最新版本:

git = find_program('git', required: true)

gen_lib1_ver = custom_target(
  'gen_lib1_ver',
  output: 'lib1_ver.h',
  command: [git, '-C', '../../lib1', 'describe', '--tags'],
  capture: true,
  build_always_stale: true,
  build_by_default: true
)

生成的lib1_ver.h内容就是lib1的版本号,你可以自行调整命令输出格式匹配你的代码需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:54:02