sicheng mao
sicheng mao

Reputation: 85

How to write a general pattern in makefile

I have multiple programs which share the same structure of compilation.

test_variance : test_variance.o
    $(CPP) -o test_variance.exe $(CFLAGS) test_variance.o $(LIBDIR) $(LIBS)

test_variance_incremental: test_variance_incremental.o 
    $(CPP) -o test_variance_incremental.exe $(CFLAGS) test_variance_incremental.o $(LIBDIR) $(LIBS)

test_hyper: test_hyper.o 
    $(CPP) -o test_hyper.exe $(CFLAGS) test_hyper.o $(LIBDIR) $(LIBS)

test_hyper.o: test_hyper.cpp
    $(CPP)  $(CFLAGS) $(INCLUDES) -c test_hyper.cpp

test_variance_incremental.o: test_variance_incremental.cpp
    $(CPP)  $(CFLAGS) $(INCLUDES) -c test_variance_incremental.cpp

test_variance.o : test_variance.cpp 
    $(CPP)  $(CFLAGS) $(INCLUDES) -c test_variance.cpp

So for compling .o, I can use the pattern

%.o: %.cpp
    $(CPP)  $(CFLAGS) $(INCLUDES) -c $<

I wonder if there is a general pattern for compling the executive. I've tried

TARGETS = test_variance test_variance_incremental test_hyper

$(TARGETS): [email protected]
    $(CPP) -o [email protected] $^ $(CFLAGS) $(LIBDIR) $(LIBS)

But Make tells me there is no input files and I think my usage of $@ is wrong. Any advice?

Upvotes: 0

Views: 38

Answers (1)

MadScientist
MadScientist

Reputation: 100866

You should use CC and CFLAGS for compiling C code, and CXX and CXXFLAGS for compiling C++ code. CPP (in make) is used for running the C preprocessor (only). The standard variable to hold libraries is LDLIBS.

If you use these variables then you don't even need to define your own rules at all: there are built-in rules in make that already know how to compile and link C++ programs. All you need is this:

TARGETS = test_variance test_variance_incremental test_hyper

all: $(TARGETS)

Anyway, if you want to write it explicitly you can write:

TARGETS = test_variance test_variance_incremental test_hyper

all: $(TARGETS)

% : %.o
        $(CXX) -o $@ $^ $(CXXFLAGS) $(LDFLAGS) $(LDLIBS)

(you should definitely not name the target test_variance, but then have your link line build test_variance.exe: the target name and the file that the recipe builds must always be the same).

Upvotes: 1

Related Questions