Ravi Gupta
Ravi Gupta

Reputation: 6470

Directory as a dependency in make rule

Is it possible to specify a directory as a dependency in a Makefile rule? Actually I have a Makefile in a directory and another directory containing all the source files.

.
.
|_ Makefile
|_ src
    |_a.c
    |_a.h

Now I want that whenever I make any change in the src directory i.e. in either of a.c or a.h , a particular rule in my Makefile get called on issuing make command. Something like

Makefile
.
.
.
build: src
    <commands>

clean:
    <commands>

Upvotes: 8

Views: 8161

Answers (2)

starfry
starfry

Reputation: 9983

While it is possible to have a directory as a dependency, there are a few things to be aware of. Consider this:

directory:
        @mkdir -p directory

directory/file : directory
        commands-to-make-the-file

This will do what you think. However, it executes the commands-to-make-the-file whenever file is older than directory, which may not be what you want.

You need to consider the scenarios where the timestamp of directory gets updated. That happens whenever files are added into or removed from the directory but it doesn't happen when an existing file is modified.

So, some unrelated action that updates the directory will cause the file to become out of date, perhaps needlessly so, which will trigger the commands to re-make it.

Upvotes: 8

Beta
Beta

Reputation: 99144

It is possible to have a directory as a dependency, in the sense that if it does not exist it will be rebuilt. It's even possible to arrange a rule that will execute when anything in the directory changes, but it's tricky. And in this case it's almost certainly overkill.

If your intent is ordinary, the usual method will suffice:

OBJ_FILES = foo.o bar.o baz.o
# There are ways to be more succinct, but for now we'll keep it simple.

build: $(OBJ_FILES)
    <commands...>

%.o: src/%.c src/%.h
    <commands for building something.o>

clean: # This should not require prerequisites
    <commands...>

Upvotes: 2

Related Questions