Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to include git commit-number into a c++ executable?

Tags:

c++

git

makefile

i use git as a version tracker for my c++ project.

sometimes i need to repeat a calculation and i would like to know which version of the program i used.

what would be a good way to put a # of the commit into the main executable? in other words. i'd like the program to tell me the # of the current commit in an introductory message as i run the program.

one way i can think of is to make the c++ program lunch "git log" from shell and extract the commit # but i'm not sure how to do it during make.

(I use linux)

like image 922
kirill_igum Avatar asked Jun 29 '11 19:06

kirill_igum


People also ask

How do I add a commit to a repository?

To add and commit files to a Git repository Create your new files or edit existing files in your local project directory. Enter git add --all at the command line prompt in your local project directory to add the files or changes to the repository. Enter git status to see the changes to be committed.

How do you get details of a commit?

`git log` command is used to view the commit history and display the necessary information of the git repository. This command displays the latest git commits information in chronological order, and the last commit will be displayed first.

What is a commit number?

Commit hashes It's unique identifier generated by Git. Every commit has one, and I'll show you what they're used for shortly. Note: The “commit hash” is sometimes called a Git commit “reference” or “SHA”.


2 Answers

Probably the easiest way to do this would be to add to your makefile a rule to generate a .c file with the current git commit ID:

gitversion.c: .git/HEAD .git/index     echo "const char *gitversion = \"$(shell git rev-parse HEAD)\";" > $@ 

Now simply add gitversion.c to your build process as normal. Make sure to remove it on make clean, and add it to .gitignore so it's not added to the git repository accidentally. Add an extern const char *gitversion; to a header somewhere, and you can access it like that.

like image 53
bdonlan Avatar answered Sep 18 '22 14:09

bdonlan


I do the following in CMakeLists.txt:

IF(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git)   FIND_PACKAGE(Git)   IF(GIT_FOUND)     EXECUTE_PROCESS(       COMMAND ${GIT_EXECUTABLE} rev-parse --short HEAD       WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"       OUTPUT_VARIABLE "kml2maps_BUILD_VERSION"       ERROR_QUIET       OUTPUT_STRIP_TRAILING_WHITESPACE)     MESSAGE( STATUS "Git version: ${kml2maps_BUILD_VERSION}" )   ELSE(GIT_FOUND)     SET(kml2maps_BUILD_VERSION 0)   ENDIF(GIT_FOUND) ENDIF(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/.git)  CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/kml2mapsVersion.h.in ${CMAKE_CURRENT_BINARY_DIR}/kml2mapsVersion.h @ONLY) 

So the git rev-parse --short HEAD's output is good to build in the binary.

like image 37
Naszta Avatar answered Sep 20 '22 14:09

Naszta