Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

embed git describe string in c++ binary

Tags:

git

gcc

g++

How can I have the result of the git describe command embedded into my c++ binary so that I can access it at run time.

I know I can do something like this

g++ -DVERSION_NUMBER=2345

And then in my code I can do:

std::cout << VERSION_NUMBER << std::endl;

This is great but won't work if the value of version number is a string such as the output of the git describe command.

So is there way to do such a thing?

Thanks.

like image 348
anio Avatar asked Feb 23 '23 14:02

anio


2 Answers

I wanted to do the same thing. I was able to get the -D flag to work just fine by using GNU Make's "shell" command like this:

Makefile:

VERSION=\"$(shell git describe)\"
CFLAGS=-DVERSION_NUMBER=$(VERSION) # etc

Then in the code I can reference the VERSION_NUMBER define with no problems, e.g.

test.c:

printf("Version string: %s\n", VERSION_NUMBER);
like image 75
Tom Avatar answered Feb 26 '23 20:02

Tom


If you use automake, then you can use something like the following. I have been using it for a long time now, and it works fine to achieve what you are asking for.

In Makefile.am:

BUILT_SOURCES = git_info.h
EXTRA_DIST = echo_git_info.sh win_config.h

.
.
(main build recipes)
.
.

git_info.h: $(HEADERS) $(SOURCES)
    echo_git_info.sh > git_info.h

In echo_git_info.sh:

#! /bin/sh

function echo_git_info {
    if [[ $(which git 2> /dev/null) ]]
    then
        local STATUS
        STATUS=$(git status 2>/dev/null)
        if [[ -z $STATUS ]]
        then
            return
        fi
        echo "`git symbolic-ref HEAD 2> /dev/null | cut -b 12-`-`git log --pretty=format:\"%h\" -1`, "
        return
    fi
}

echo "// Auto-generated source/build information."
echo "#define GIT_SOURCE_DESC \"`echo_git_info``date`\""

The above will result in the the variable GIT_SOURCE_DESC being defined in the file git_info.h. Thus, in your main.cpp you can then:

#include <iostream>
#include "ginkgo_info.h"

int main(int argc, char* argv[]) {
    std::cout << "Source is: " << $GIT_SOURCE_DESC << std::endl;
}
like image 43
Jeet Avatar answered Feb 26 '23 21:02

Jeet