我怎样才能 运行 在介子构建时自定义命令?

How can I run a custom command at build time in meson?

在我的项目中,我采用了遵循 semver 描述的标准的语义版本控制方案。我得到这样的东西:product_v1.2.3-alpha-dirty.elf .

我使用嵌入式系统和 make 我通常在编译时生成一个 version_autogen.h 文件,其中包含版本号的信息,例如 1.4.3.1,和当前的 git 存储库,例如--dirty、--clean 等等,使用 shell 命令。

我开始使用介子,它非常简单灵活,但自定义命令如

run_command('command', 'arg1', 'arg2', 'arg3')

仅在 配置 时可用,而我在 编译 时需要它们来检索 git 状态等类似信息.

我该怎么做?

经过更深入的研究,我发现 custom_target()(如 nielsdg 所建议)可以完成我的工作。我做了这样的事情:

# versioning
version_autogen_h = custom_target(
    'version_autogen.h',
    output : 'version_autogen.h',
    input : 'version_creator.sh',
    command : ['@INPUT@', '0', '0', '1', 'alpha.1', '@OUTPUT@' ],
)

其中 version_creator.sh 是我的 bash 脚本,它检索 git 信息并根据作为命令参数传递的版本号创建文件 version_autogen.h。自定义目标是在编译时创建的,因此我的脚本也在编译时执行,正好是我想要的时间。

我还发现在介子中有可能使用 generators 来做类似的事情,但在那种情况下它们 transform一个或多个输出文件中的输入文件,因此它们不适合我不需要文件作为输入而只需要版本号的情况。

介子对这项工作有专门的指挥 - vcs_tag

This command detects revision control commit information at build time and places it in the specified output file. This file is guaranteed to be up to date on every build. Keywords are similar to custom_target.

,所以它看起来会更短一些,可以避免生成脚本并且只有

git_version_h = vcs_tag(input : 'version.h.in',
                       output : 'version.h')

其中 version.h.in 文件,您应该提供 @VCS_TAG@ 将被替换的字符串,例如

#define MYPROJ_VERSION "@VCS_TAG@"

当然,您可以根据您的项目风格设置文件头和命名,也可以添加其他定义。也可以使用另一个替换字符串和自己的命令行来生成版本,例如

vcs_tag(command: [
        'git', '--git-dir', meson.build_root(),
        'describe', '--tags', '--long',
        '--match', '?.*.*', '--always'
    ],
    ...
    )

我发现并改编自 here