开发者

embed git describe string in c++ binary

开发者 https://www.devze.com 2023-03-19 12:55 出处:网络
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.

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 << 开发者_Python百科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.


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);


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;
}


The mercurial wiki contains different possibilities how to gather this information with make.


It's maybe not the best but a way. You can write the string or anything else to the end of a binary file. One tutorial to achieve this is: http://edn.embarcadero.com/article/27979

The code is not c++ though. However you may port the examples to c++.

0

精彩评论

暂无评论...
验证码 换一张
取 消