CMake and Git: SHA and branch name embedded in executables

Have you ever distributed many executables of one Project over the time and now someone reports you a bug, but you cannot reproduce it, because you don’t know which build he used?

If you use CMake and your versioning system is git, I have something for you which helps tracking those builds. Just add these lines to your CMakelists.txt:

# Will pass the SHA and branch strings to the executable
find_program(GIT_FOUND git)
    message(STATUS "Found Git (${GIT_FOUND}), executable will get SHA and branch used")
    execute_process(COMMAND ${GIT_FOUND} -C ${CMAKE_SOURCE_DIR} rev-parse HEAD
                    OUTPUT_VARIABLE GIT_SHA
    execute_process(COMMAND ${GIT_FOUND} -C ${CMAKE_SOURCE_DIR} branch --show-current
                    OUTPUT_VARIABLE GIT_BRANCH
    message(STATUS "GIT_SHA = ${GIT_SHA}")
    message(STATUS "GIT_BRANCH = ${GIT_BRANCH}")

With that you get the defines GIT_SHA and GIT_BRANCH to use in your sources. Just add it to where you want to see the generated strings with a code snippet like the following:

#define xstr(s) str(s)
#define str(s) #s



    printf("GIT_SHA: " xstr(GIT_SHA) "\n");
    printf("GIT_BRANCH: " xstr(GIT_BRANCH) "\n");


That’s really it. Now your user can share these values and you can go back to the exact sources git checkout <SHA> where the issue occurs. Who knows, maybe one of your later commits already fixed the problem.

Das könnte Dich auch interessieren …

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.