Makefile: How do I use variables in the left hand side of the rule?

Let's say I want to rewrite this:

main.o: main.cpp
    g++ -c main.cpp

factorial.o: factorial.cpp
    g++ -c factorial.cpp

hello.o: hello.cpp
    g++ -c hello.cpp

in a more generic way as something like this:

SOURCES = main factorial hello

$(SOURCES).o: $(SOURCES).cpp
    g++ -c $(SOURCES).cpp

How do I do that?

Upvotes: 2

Views: 2085

Answers (1)

Beta
Beta

Reputation: 99094

First we tell the compiler how to nme the output files, just to avoid misunderstanding:

main.o: main.cpp
    g++ -c main.cpp -o main.o

factorial.o: factorial.cpp
    g++ -c factorial.cpp -o factorial.o

hello.o: hello.cpp
    g++ -c hello.cpp -o hello.o

Then we put in automatic variables, to reduce redundancy:

main.o: main.cpp
    g++ -c $< -o $@

factorial.o: factorial.cpp
    g++ -c $< -o $@

hello.o: hello.cpp
    g++ -c $< -o $@

Then we realize that these rules all look the same, so we combine them as a static pattern rule:

main.o factorial.o hello.o: %.o : %.cpp
    g++ -c $< -o $@

Then we use a variable to store the names of the objects:

OBJECTS := main.o factorial.o hello.o

$(OBJECTS): %.o : %.cpp
    g++ -c $< -o $@

Upvotes: 7

Related Questions