Bart Friederichs
Bart Friederichs

Reputation: 33521

How to set git version in .h file before build?

I am using make to build my application, and I want to set a variable when building everything, containing the git version.

My preference is to do this all inside the Makefile, so I am not dependant on any external scripts. I am trying the following:

build:
    CFLAGS=$(CFLAGS) -DBUILD=$(dotnet-gitversion /showvariable FullSemVer)

target: build
    cc $(CFLAGS) object.o -o name

This doesn't work, because the variables do not get set. How could I get this working?

Another solution would be to do something like this:

build:
    ./update-version.sh

target: build
    cc object.o -o name

where ./update-version.sh would call dotnet-gitversion and "physically" update the file where the BUILD directive is set. But this means I need an external script.

Question now is what would the best way to do this? (Is there perhaps another solution?)

Upvotes: 1

Views: 1498

Answers (1)

HardcoreHenry
HardcoreHenry

Reputation: 6387

I would suggest you do something similar to the following:

Makefile:

GIT_VERSION := $(dotnet-gitversion /showvariable FullSemVer)

git_version.h : git_version.$(GIT_VERSION).h
   ln -s $@ $^

git_version.$(GIT_VERSION).h :
    rm git_version.*.h  #get rid of any obsolete git versions
    echo "#define BUILD $(GIT_VERSION)" > $@

As to why it's done this way:

  1. If you pass the value down as a -D define to say target.c, and you build target.o, it will have the correct version the first time it is built. But then if the git version is updated, and you rebuild, you might not rebuild target.o, as target.c did not change, and target.o will be considered up to date. Thus it would hold an outdated value.

  2. If you try to do this with just git_version.h, like say:

git_version.h :
   echo "#define GIT_VERSION $(GIT_VERSION)" > $@

Then you run into the same problem (if version.h exists, it will be considered up to date, and will not be rebuilt when the GIT_VERSION changes.

  1. If you try the above, but where version.h is declared as .PHONY, then it will always rebuild version.h (and anything that depends on it), regardless of whether the git version changes (which will result in unnecessary builds).

Note: credit goes to @Andreas who first suggested this approach here

Upvotes: 3

Related Questions