krystian71115
krystian71115

Reputation: 1937

Why Makefile detects file even if it does not exist?

Here is my code:

%.o: %.cpp 
    @mkdir -p bin/obj/$(@D) 
ifeq ($(wildcard bin/obj/$@),)
    $(CC) -c -o bin/obj/$@ $< $(CFLAGS) $(FLAGS)
else
    @echo "bin/obj/$@ exists"
endif

And I have a problem, when directory obj exists I always get false.

I'm talking about this condition:

($(wildcard bin/obj/$@),)

I don't know how to fix it.

Makefile always prints that file exists even if i remove it from disk.

It works only when I remove obj directory.

How can I fix it?

Upvotes: 0

Views: 57

Answers (1)

Beta
Beta

Reputation: 99124

The trouble is that Make evaluates the conditional before executing the rule, when $@ has not been defined (and when the file may not yet have been created). The wildcard statement evaluates to $(wildcard /bin/obj/), which will produce "bin/obj/" if the directory exists, which I suppose it does.

There's more than one way to solve this. The most direct is to put the conditional in the command, so that Make will pass it to the shell:

%.o: %.cpp
    @mkdir -p bin/obj/$(@D)
    @if [ -e bin/obj/$@ ]; then echo it exists; else $(CC) ...; fi

Upvotes: 2

Related Questions