我怎样才能让我的 C 代码自动打印出它的 Git 版本哈希? [英] How can I get my C code to automatically print out its Git version hash?

查看:17
本文介绍了我怎样才能让我的 C 代码自动打印出它的 Git 版本哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法来编写可以访问其 Git 版本哈希的 C 代码?

Is there an easy way to write C code that can access its Git version hash?

我用 C 语言编写了软件,用于在实验室环境中收集科学数据.我的代码将它收集的数据记录在一个 .yaml 文件中以供以后分析.我的实验每天都在变化,我经常不得不修改代码.为了跟踪修订,我使用了一个 git 存储库.

I wrote software in C to collect scientific data in a laboratory setting. My code records the data it collects in a .yaml file for later analysis. My experiments change from day-to-day and I often have to modify the code. To keep track of revisions, I use a git repository.

我希望能够将 Git 修订哈希作为注释包含在我的 .yaml 数据文件中.这样,我就可以查看 .yaml 文件并确切知道用​​于生成该文件中显示的数据的代码.有没有一种简单的方法可以自动执行此操作?

I would like to be able to include the Git revision hash as a comment in my .yaml data files. That way, I could look at the .yaml file and know exactly what code was used to generate the data shown in that file. Is there an easy way to do this automatically?

推荐答案

在我的程序中,我将 git 版本号和构建日期保存在一个名为 version.c 的单独文件中,看起来像这样:

In my program, I hold the git version number and the date of the build in a separate file, called version.c, which looks like this:

#include "version.h"
const char * build_date = "2009-11-10 11:09";
const char * build_git_sha = "6b54ea36e92d4907aba8b3fade7f2d58a921b6cd";

还有一个头文件,长这样:

There is also a header file, which looks like this:

#ifndef VERSION_H
#define VERSION_H
extern const char * build_date; /* 2009-11-10 11:09 */
extern const char * build_git_sha; /* 6b54ea36e92d4907aba8b3fade7f2d58a921b6cd */
#endif /* VERSION_H */

头文件和 C 文件都是由 Perl 脚本生成的,如下所示:

Both the header file and the C file are generated by a Perl script which looks like this:

my $git_sha = `git rev-parse HEAD`;
$git_sha =~ s/s+//g;
# This contains all the build variables.
my %build;
$build{date} = make_date_time ();
$build{git_sha} = $git_sha;

hash_to_c_file ("version.c", \%build, "build_");

这里 hash_to_c_file 完成了创建 version.cversion.hmake_date_time 的所有工作字符串如图所示.

Here hash_to_c_file does all the work of creating version.c and version.h and make_date_time makes a string as shown.

在主程序中,我有一个例程

In the main program, I have a routine

#include "version.h"

// The name of this program.
const char * program_name = "magikruiser";
// The version of this program.
const char * version = "0.010";

/* Print an ID stamp for the program. */

static void _program_id_stamp (FILE * output)
{
    fprintf (output, "%s / %s / %s / %s
",
             program_name, version,
             build_date, build_git_sha);
}

我对 git 不是很了解,所以如果有更好的方法来做到这一点,我欢迎评论.

I'm not that knowledgeable about git, so I'd welcome comments if there is a better way to do this.

这篇关于我怎样才能让我的 C 代码自动打印出它的 Git 版本哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆