mbrandalero
mbrandalero

Reputation: 416

Makefile variable expansion with wildcard when rule creates new file

I'm having trouble understanding how Makefile deals with variable expansion when a rule creates a file that should modify the behaviour of a wildcard expansion.

For instance, I have the following Makefile:

TEXT_FILES = $(wildcard *.txt)

all: create test

create:
    @touch hello.txt

test:
    @printf "The files are $(TEXT_FILES)\n"

What I expected to get when running make is

The files are hello.txt

because TEXT_FILES should be evaluated when it is called, not when defined. However, I actually get (running make twice)

The files are (variable is empty when executing for the first time)

The files are hello.txt (found next time)

How can I get the desired behavior?

Upvotes: 2

Views: 3044

Answers (1)

MadScientist
MadScientist

Reputation: 100856

This behavior is the result of make's internal cache. For performance reasons, make will cache the state of the filesystem that it believes to be true, based on what it was before plus the changes it knows have been made (because of rules that have been invoked).

Functions like wildcard will query the internal cache, if it's available.

However, in your situation you're not describing the actual behavior of your rules to make: you didn't tell make that this rule generates the extra file. As a result make won't update its cache and the wildcard function never finds this secret file.

You don't say what you want to do precisely, but why don't you just use the shell's wildcarding facilities instead of make's wildcard function? The shell obviously has no idea about make's internal caches:

TEXT_FILES = *.txt

all: create test

create:
        @touch hello.txt

test:
        @echo The files are $(TEXT_FILES)

Upvotes: 4

Related Questions