Mr M.
Mr M.

Reputation: 735

Makefile not always rebuilds

I have a makefile which takes a variable from the commandline and passes it to compiler (for C++ preprocesor).

Here is the code:

bar=0
file.o: foo.cpp    
ifeq($(bar), 0)
    g++ file.cpp -D foo=1 -o file.o
else
    g++ file.cpp -D foo=0 -o file.o
endif

The problem is that after running

make bar=0 

and then

make bar=1

It says that foo.o is up to date (which it is, but I would want it rebuilt since a variable is changed inside the code).

Upvotes: 0

Views: 102

Answers (3)

downhillFromHere
downhillFromHere

Reputation: 1977

If you want to keep it simple and don't mind having an extra file as a marker, you could do

bar = 0
MARKER = compiled_with_foo_
file.o: $(MARKER)_$(bar)    
ifeq($(bar), 0)
    rm -f $(MARKER)_1
else
    rm -f $(MARKER)_0   
endif
    g++ -c file.cpp -D foo=$(bar) -o file.o

$(MARKER)_$(bar): file.cpp
    touch $@

and have your clean remove both markers.

Upvotes: 1

Mark Galeck
Mark Galeck

Reputation: 6385

There is no point in using Make at all if one resorts to forced rebuilds or cleaning. The correct approach here is to implement a "dependable variable", that behaves like a file. If bar were such a variable, you could just say

file.o: foo.cpp bar
    (your recipe here)

and that would mean, if the "contents" (value) of bar change, you rebuild.

For details on how to implement dependable variables, see my post

How do I add a debug option to Makefile

Upvotes: 2

incogn1to
incogn1to

Reputation: 427

You can use Phony target for forcing compiler to rebuild it. The good idea is to define clean function. Then to recompile project using:

make clean
make all

Upvotes: 1

Related Questions