0

Here is my simple Makefile. I am trying to set the C macro "GIT_COMMIT" in my Makefile and pass it to the C program.

all: control

control: control.cpp serial_port.cpp
    GIT_COMMIT=5
    g++ -g -DGIT_COMMIT=$(GIT_COMMIT) -Wall $^ -o control -lpthread

Unfortunately, when I run make, I see this and make is completely ignoring my GIT_COMMIT variable. What am I doing wrong? Thanks.

GIT_COMMIT=5
g++ -g -DGIT_COMMIT= -Wall control.cpp serial_port.cpp -o control -lpthread
Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
  • 2
    Does this answer your question? [Makefile set variable in target](https://stackoverflow.com/questions/36174028/makefile-set-variable-in-target) – Eugene Sh. Jan 18 '22 at 15:24
  • Yes, but in a much more complicated and unclear example. My question is superior for this problem due to its simplicity. – define_makefile Jan 18 '22 at 17:26

1 Answers1

0

placing the setting of GIT_COMMIT as an action inside the 'control' rule will, as you discovered, not work to produce a macro. suggest:

all: control

GIT_COMMIT := 5

control: control.cpp serial_port.cpp
    g++ -g -DGIT_COMMIT=$(GIT_COMMIT) -Wall $^ -o control -lpthread
user3629249
  • 16,402
  • 1
  • 16
  • 17
  • Thank you for restoring my sanity. I had no idea that variables "didn't work" inside rules. – define_makefile Jan 18 '22 at 16:09
  • 1
    @define_makefile, they don't work *to produce a macro*. But in your particular case, the line in question works fine (as a shell command) to produce a *shell* variable. `make` runs each recipe line in a separate shell, however, so it's not useful for a line to do nothing but set a (shell) variable. – John Bollinger Jan 18 '22 at 16:14
  • Okay, that explains why. I'm surprised there is no warning! – define_makefile Jan 18 '22 at 17:10
  • 1
    How can there be a warning? It's perfectly acceptable to assign a shell variable in a shell script, which is what you're doing here. In any event, make doesn't even know that that's what you're doing: make doesn't have a shell script interpreter built into it. It just takes the commands in the recipe and runs a shell and gives it that text: only the shell knows whether it's valid syntax (and again, this is perfectly valid syntax). – MadScientist Jan 18 '22 at 18:37