Search code examples
gnu-makevariable-expansion

Early Expansion of Variables in Recipes


I know about the distinction between the two kinds of variables in GNU Make.

I am currently writing a build system where certain variables are defined in sub directories (e.g., VERSION). To make the life simpler for authors of subdirectories, I do not want to force them to make their variables globally unique. I also would like to avoid recursive make.

My problem is now that I need a way to provide some simple library targets that expand these common variables when the target is defined. As a simple example:

FOO := Bar
PHONY: $(FOO)
$(FOO):
    @echo $(FOO)

FOO := Definitely not Bar

PHONY: test2
test2: Bar
    @echo $(FOO)

I would need the output of make test2 to be

Bar
Definitely not Bar

I could, of course, use a temporary variable to force the expansion of FOO in the first rule, but then I need a way to reliably define a new temporary variable. Is there a way to expand a target, e.g. using eval?

edit: Made the curious expansion of FOO more clear in the example code.


Solution

  • It looks as if you simply want target-specific variables, e.g.

    Makefile

    .PHONY: Bar test2
    
    Bar: FOO := Bar
    Bar:
        @echo $(FOO)
    
    test2: FOO := Definitely not Bar
    test2: Bar
        @echo $(FOO)
    

    which runs like:

    $ make test2
    Bar
    Definitely not Bar
    

    (Note that .PHONY, like all special targets, begins with .)