Hanfei Sun
Hanfei Sun

Reputation: 47051

Is there anyway to reduce the duplicate prerequisites pattern in GNU make?

Current way is like this, which looks quite clumsy..

ex1_test : ex1.o ex1_test.o
    cc -o ex1_test ex1.o ex1_test.o
ex2_test : ex2.o ex2_test.o
    cc -o ex2_test ex2.o ex2_test.o
ex3_test : ex3.o ex3_test.o
    cc -o ex3_test ex3.o ex3_test.o

Is there a variable that I can use to represent the current target and reduce the duplicate?

Thanks!

Upvotes: 1

Views: 174

Answers (2)

Beta
Beta

Reputation: 99094

Step 1, introduce automatic variables:

ex1_test : ex1.o ex1_test.o
    cc -o $@ $^
ex2_test : ex2.o ex2_test.o
    cc -o $@ $^
ex3_test : ex3.o ex3_test.o
    cc -o $@ $^

Step 2, realize that these rules all look the same, and replace them with a pattern rule:

ex%_test: ex%.o ex%_test.o
    cc -o $@ $^

Upvotes: 6

Digikata
Digikata

Reputation: 1959

$@ and $^ are your friend. $@ is the target, and $^ the list of prerequisites.

ex1_test : ex1.o ex1_test.o
    cc -o $@ $^

There are more useful make variables in the GNU Make documentation in the automatic variables section.

Upvotes: 2

Related Questions