user9098083
user9098083

Reputation:

folder's content as makefile rule dependency

I would like to have all folder's content in dependency. My folder is created when the rule is called.

create-content:
 mkdir -p sample_dir/subdir1
 touch sample_dir/file1
 touch sample_dir/subdir1/file2

list-content: create-content $(shell find sample_dir)
 echo $^

I would like this output:

 make list-content
 create-content sample_dir sample_dir/file1 sample_dir/subdir1 sample_dir/subdir1/file2

But I have:

make list-content
create-content

The problem is that the shell function is called on make and not when the rule is running. So shell is called before create-content, so the directory doesn't exist yet. Is it possible to solve this?

Thank you.

Upvotes: 2

Views: 116

Answers (1)

Renaud Pacalet
Renaud Pacalet

Reputation: 29250

The answer is no... and yes.

No, you can't because make builds all its dependency graph before it runs the first recipe. So, if a recipe creates new nodes of the dependency graph, it is too late for make to notice.

But there is a simple workaround: tell make to invoke make (recursive make). Despite what many people say, recursive make is not always harmful. It is even sometimes the only solution to a specific problem. This is your case. And with a bit of make magic (conditionals) you can hide this with two different behaviors depending on the existence of sample_dir:

create-content:
    @mkdir -p sample_dir/subdir1 && \
    touch sample_dir/file1 && \
    touch sample_dir/subdir1/file2

ifeq ($(wildcard sample_dir),)
list-content: create-content
    @$(MAKE) --no-print-directory $@
else
list-content: create-content $(shell find sample_dir)
    @echo $^
endif

Now, the prerequisites of list-content are complete. Demo:

$ rm -rf sample_dir
$ make list-content
create-content sample_dir sample_dir/file1 sample_dir/subdir1 sample_dir/subdir1/file2
$ make list-content
create-content sample_dir sample_dir/file1 sample_dir/subdir1 sample_dir/subdir1/file2

Upvotes: 1

Related Questions