How do I add revision and build date to source?

I have a GCC project and would like to automatically add defines for build date and revision number (from git) to my sources. What’s the best way to do this?

My goal is simple to be able to do something like this on startup:

  • Couldn't find any revision to build. Verify the repository and branch configuration for this job. Finished: FAILURE
  • Gitlab CI - How to trigger a build only if changes happen on particular set of files
  • Is it a good practice to make a tag in git for every deployment build?
  • How to not trigger a build in Teamcity if only a specific file changed
  • Trigger hudson build when svn commit
  • 404 error when building Git project in TFS2013
  • printf("Test app build on %s, revision %d", BUILD_DATE, REVISION)

    For building I’m using make with a simple, not autoconf or anything like this.

  • Jenkins marks good build as failure because of test failed
  • How to get only the git date format as YYYY/MM/DD?
  • Jenkins and maven-buildnumber-plugin
  • Building Eclipse IDE from scratch - how to choose CDT over JDT?
  • How to pass a build number within the MultiJob plugin?
  • What is “workspace polling” in the context of Jenkins?
  • 2 Solutions collect form web for “How do I add revision and build date to source?”

    I ended up using a simple command like this in my Makefile:

    echo "#define GIT_REF \"`git show-ref refs/heads/master | cut -d " " -f 1 | cut -c 31-40`\"" > git_ref.h

    RCS keyword substitution is not natively supported by Git, but can be added with a gitattributes filter driver: See “Git equivalent of subversion’s $URL$ keyword expansion”.

    alt text

    For example (not exactly relate to your question, but illustrates the general principle):

    git config filter.rcs-keyword.clean 'perl -pe "s/\\\$Date[^\\\$]*\\\$/\\\$Date\\\$/"'
    git config filter.rcs-keyword.smudge 'perl -pe "s/\\\$Date[^\\\$]*\\\$/\\\$Date: `date`\\\$/"'

    You will base your filter script on the result of git describe --tags called from your Makefile.

    As mentioned in this answer to “Git equivalent of subversion’s $URL$ keyword expansion”, smudge/clear filter driver is not a perfect solution, and adding any kind of meta-data directly in the data (source) is generally a bad idea (you have a debate about it in “What are the basic clearcase concepts every developer should know?”).

    Yet you have a good example of such Git keyword expansion in this answer in “How do I enable ident string for Git repos?”.

    Git Baby is a git and github fan, let's start git clone.