Thomson Karnel
Thomson Karnel

Reputation: 23

Why isn't this variable expanded with eval?

I have a question about the following makefile. I use GNU Make v4.1.

define code
    foo:=hello
    bar:=${foo}
endef

$(eval ${code})
default:
    #${foo}
    #${bar}

${foo} echoes hello, but ${bar} echoes nothing. Why is this happening? I expected ${bar} to echo hello too, because I think this is equivalent to the following makefile:

foo:=hello
bar:=${foo}
default:
    #${foo}
    #${bar}

Upvotes: 1

Views: 49

Answers (2)

Thomson Karnel
Thomson Karnel

Reputation: 23

I'm original poster.I found another function 'value' which return value without expansion.

define code
    foo:=hello
    bar:=${foo}
endef

$(eval $(value code))
default:
    #${foo}
    #${bar}

This also works too.

Upvotes: 1

Add $(info ${code}) to see what's going on.

${foo} was expanded when the definition of code was build, so code contains

    foo:=hello
    bar:=${foo}

If you want ${foo} to be expanded when you run $(eval ${code}), which is what makes eval useful, then you need to make the value of code contain a dollar sign.

define code
    foo:=hello
    bar:=$${foo}
endef

In this case, you could achieve the same result by making bar a late-expansion definiton:

bar=${foo}
foo:=hello
default:
    #${foo}
    #${bar}

eval is useful in more complex cases, especially when string being eval'ed is built dynamically.

Upvotes: 0

Related Questions