如何使用 cmake 将 git SHA1 作为定义传递给编译器? [英] How can I pass git SHA1 to compiler as definition using cmake?

查看:13
本文介绍了如何使用 cmake 将 git SHA1 作为定义传递给编译器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Makefile 中,这将通过以下方式完成:

In a Makefile this would be done with something like:

g++ -DGIT_SHA1="`git log -1 | head -n 1`" ...

这非常有用,因为二进制文件知道确切的提交 SHA1,因此它可以在出现段错误时转储它.

This is very useful, because the binary knows exact commit SHA1 so it can dump it in case of segfault.

如何使用 CMake 实现相同的效果?

How can I achieve the same with CMake?

推荐答案

我制作了一些 CMake 模块,这些模块与 git repo 用于版本控制和类似目的 - 它们都在我的存储库中 https://github.com/rpavlik/cmake-modules

I've made some CMake modules that peer into a git repo for versioning and similar purposes - they're all in my repository at https://github.com/rpavlik/cmake-modules

这些函数的好处是,每次 HEAD 提交更改时,它们都会在构建之前强制重新配置(重新运行 cmake).不像用execute_process只做一次,你不需要记住重新cmake来更新hash定义.

The good thing about these functions is, they will force a re-configure (a rerun of cmake) before a build every time the HEAD commit changes. Unlike doing something just once with execute_process, you don't need to remember to re-cmake to update the hash definition.

为此特定目的,您至少需要 GetGitRevisionDescription.cmakeGetGitRevisionDescription.cmake.in 文件.然后,在你的主要 CMakeLists.txt 文件中,你会有这样的东西

For this specific purpose, you'd need at least the GetGitRevisionDescription.cmake and GetGitRevisionDescription.cmake.in files. Then, in your main CMakeLists.txt file, you'd have something like this

list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/whereYouPutMyModules/")
include(GetGitRevisionDescription)
get_git_head_revision(GIT_REFSPEC GIT_SHA1)

然后,您可以将其添加为系统范围的定义(不幸的是,这会导致大量重建)

Then, you could either add it as a system-wide definition (which unfortunately would cause lots of rebuilding)

add_definitions("-DGIT_SHA1=${GIT_SHA1}")

或者,我建议的替代方案:制作一个生成的源文件.在源中创建这两个文件:

or, my suggested alternative: Make a generated source file. Create these two files in your source:

GitSHA1.cpp.in:

#define GIT_SHA1 "@GIT_SHA1@"
const char g_GIT_SHA1[] = GIT_SHA1;

GitSHA1.h:

extern const char g_GIT_SHA1[];

将此添加到您的 CMakeLists.txt(假设您在 SOURCES 中有源文件列表):

Add this to your CMakeLists.txt (assuming you have a list of source files in SOURCES):

configure_file("${CMAKE_CURRENT_SOURCE_DIR}/GitSHA1.cpp.in" "${CMAKE_CURRENT_BINARY_DIR}/GitSHA1.cpp" @ONLY)
list(APPEND SOURCES "${CMAKE_CURRENT_BINARY_DIR}/GitSHA1.cpp" GitSHA1.h)

然后,您有一个包含 SHA 字符串的全局变量 - 当 SHA 执行时,带有 extern 的标头不会更改,因此您可以只包含要引用该字符串的任何位置,然后仅包含生成的CPP 需要在每次提交时重新编译,以便您可以随时随地访问 SHA.

Then, you have a global variable containing your SHA string - the header with the extern doesn't change when the SHA does, so you can just include that any place you want to refer to the string, and then only the generated CPP needs to be recompiled on every commit to give you access to the SHA everywhere.

这篇关于如何使用 cmake 将 git SHA1 作为定义传递给编译器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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