-1

Im trying to pass my git commit hash into my C program but im keep getting errors.

this is part of my makefile:

GIT_COMMIT := $(shell git rev-parse --verify HEAD)
Defines += -DGIT_COMMIT=\"$(GIT_COMMIT)\"\

and then I'm passing "Defines" to icc compiler.

in my C code , the following line causes error - "error: extra text after expected end of number"

printf("GIT COMMIT HASH: %s", GIT_COMMIT);

any idea what I'm doing wrong here?

Guy
  • 33
  • 5
  • 1
    Why the extra backslash in the end? – Eugene Sh. Nov 12 '20 at 16:55
  • not really needed here, but it also does not work without it. – Guy Nov 12 '20 at 17:01
  • 1
    Please post a full error message. You can also try hardcoding GIT_COMMIT in the makefile to isolate the error. Also `echo` the resulting `Defines` to see if something is wrong. Looking at the commands generated would also help. – Eugene Sh. Nov 12 '20 at 17:02
  • This is the entire error the compiler gives. i tried to compile with - DGIT_COMMIT=\"ABCDEFG"\" and now im getting - "error: identifier "ABCDEFG" is undefined", seems like it emits the "" – Guy Nov 12 '20 at 17:07
  • 1
    Not sure if it is makefile or shell issue, but you can probably add `#define STR(x) #x` to your code and use `STR(GIT_COMMIT)` instead. – Eugene Sh. Nov 12 '20 at 17:13
  • 1
    In fact there is a duplicate https://stackoverflow.com/questions/2410976/how-to-define-a-string-literal-in-gcc-command-line – Eugene Sh. Nov 12 '20 at 17:16

1 Answers1

1

Use

Defines += -DGIT_COMMIT=\"$(GIT_COMMIT)\"

instead of

Defines += -DGIT_COMMIT=\"$(GIT_COMMIT)\"\

Always prefer to stringify when passing strings to the preprocessor, otherwise passing values with # at the begining or containing quotes will fail, you can use something like:

#define GET_GIT_COMMIT_(x) #x
#define GET_GIT_COMMIT(x) GET_GIT_COMMIT_(x)

printf("GIT COMMIT HASH: %s", GET_GIT_COMMIT(GIT_COMMIT));

Then, in the Makefile:

Defines += -DGIT_COMMIT="$(GIT_COMMIT)"
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • now it compiles but it prints - :"GIT COMMIT HASH: GIT_COMMIT", it does not recognize it as define – Guy Nov 12 '20 at 17:45
  • Which form are you using? `"\"$(GIT_COMMIT)\\"` or `"$(GIT_COMMIT)"`? you only need to stringify in the second case, `"\"$(GIT_COMMIT)\\"` is already stringified. – David Ranieri Nov 12 '20 at 17:47
  • it didnt work with - "$(GIT_COMMIT)" and with - "\"$(GIT_COMMIT)\\" there was a makefile error. i managed to do it with - \"$(GIT_COMMIT)\" thanks for the help! – Guy Nov 12 '20 at 18:06
  • It works fine, at least on `gcc`: https://coliru.stacked-crooked.com/a/81e34f559e8fafe4 – David Ranieri Nov 12 '20 at 18:18
  • Ah, ok, it was already expanded in a variable in the Makefile, I didn't pay atention to that :) – David Ranieri Nov 12 '20 at 18:25