Change Makefile variable value inside the target body

Is there a way to reassign Makefile variable value inside of the target body?

What I am trying to do is to add some extra flags for debug compilation:

%.erl: %.beam
    $(ERLC) $(ERLFLAGS) -o ebin $<

test: clean debug_compile_flag compile compile_test

debug_compile:
    $(ERLCFLAGS) += -DTEST

So if I invoke test target I would like to clean up my environment, add some new flags (like -DTEST to the existing ones), compile the whole code once again (first sources, then test modules).

I do not want to copy/paste the code for compiling with some new flags set since there is a lot of logic put here and there.

Is there some easy way to redefine the variable value so I can reuse the existing code?


Solution 1:

Yes, there is an easy way to do it, and without rerunning Make. Use a target-specific variable value:

test: clean debug_compile

debug_compile: ERLCFLAGS += -DTEST
debug_compile: compile compile_test;

Solution 2:

Another answer is here: Define make variable at rule execution time.

For the lazy, you can have rules like the following (FLAG and DEBUG are my variables):

.DBG:
    $(eval FLAG += $(DEBUG))

Solution 3:

Here is the solution I use:

PASSWORD = abc123

main: sub
    @echo "in main" $(PASSWORD)

sub:
    @echo "in sub" $(PASSWORD)
    $(eval PASSWORD=qwerty)
    @echo "in sub" $(PASSWORD)

If you run make main then the output is:

in sub abc123
in sub qwerty
in main qwerty

You can see that the original value "abc123" is overwritten in the sub and the new value "qwerty" is visible at the main level.