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)
if(GIT_FOUND)
    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
                    OUTPUT_STRIP_TRAILING_WHITESPACE)
    execute_process(COMMAND ${GIT_FOUND} -C ${CMAKE_SOURCE_DIR} branch --show-current
                    OUTPUT_VARIABLE GIT_BRANCH
                    OUTPUT_STRIP_TRAILING_WHITESPACE)
    ADD_DEFINITIONS(-DGIT_SHA=${GIT_SHA})
    ADD_DEFINITIONS(-DGIT_BRANCH=${GIT_BRANCH})
    message(STATUS "GIT_SHA = ${GIT_SHA}")
    message(STATUS "GIT_BRANCH = ${GIT_BRANCH}")
else(GIT_FOUND)
    ADD_DEFINITIONS(-DGIT_SHA=none)
    ADD_DEFINITIONS(-DGIT_BRANCH=none)
endif(GIT_FOUND)

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.