一种解决方案是让构建系统提取值并让它生成一些带有此值的C头(或源文件).
例如,如果使用CMake,您可以使用FindGit模块执行以下操作:
project(...)
# load module.
find_package(Git)
# create "${GIT_HEAD_HASH}" variable that contains
# the SHA-1 of the current tree. This assumes that the
# root CMakeLists is in the root of the Git repository.
git_tree_info(${CMAKE_SOURCE_DIR} GIT_HEAD)
# generate a 'version.h' file based on the 'version.h.in'
# file. replace all @...@ strings with variables in the
# current scope.
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/version.h.in
${CMAKE_CURRENT_SOURCE_DIR}/version.h
@ONLY
)
然后,添加以下version.h.in文件:
#ifndef _version_h__
#define _version_h__
static const char VERSION[] = "@GIT_HEAD_HASH@";
#endif
CMake将使用get_tree_info()将其提取的值替换为@ GIT_HEAD_HASH @字符串.
然后,从您的常规代码:
#include "version.h"
#include
#include
#include
int main(int argc, char ** argv)
{
if ((argc == 2) && (std::strcmp(argv[1],"--version") == 0))
{
std::cerr
<< VERSION
<< std::endl;
return (EXIT_FAILURE);
}
// ...
}
这是一个简化且绝对未经测试的例子.如果你看看FindGit CMake模块的源代码,你会发现它只是在构建时运行execute_process()命令来提取信息.您可以修改它以根据Git命令行界面的调用提取任何内容.