Reputation: 2424
I'm brushing up on C++ by completing many small programs, each contained in a single cpp file. I also want to learn a little bit more about Makefiles, and decided to write a Makefile that will compile all of my little programs and produce an executable per program. With my current Makefile, I have to:
Append the name to the end of "BINARIES"
Copy the repeated target and replace the target name with the binary name
How can I edit this Makefile to be even more generic, so that I can simply append the name of my new program to the end of "BINARIES" and not have to continue to copy and paste the repeated targets?
BIN=./bin/
SOURCE=./src/
CXX=g++
CXXFLAGS=-g -c -Wall
BINARIES=sums-in-loop sum-in-loop sum-of-two
RM=rm -f
all: sums-in-loop sum-in-loop sum-of-two
sums-in-loop:
$(CXX) $(CXXFLAGS) $(SOURCE)[email protected] -o $(BIN)$@
sum-in-loop:
$(CXX) $(CXXFLAGS) $(SOURCE)[email protected] -o $(BIN)$@
sum-of-two:
$(CXX) $(CXXFLAGS) $(SOURCE)[email protected] -o $(BIN)$@
clean:
$(RM) $(BIN)*
Upvotes: 3
Views: 248
Reputation: 126203
The usual way is to use pattern rules:
BIN=bin
SOURCE=src
CXX=g++
CXXFLAGS=-g -Wall
BINARIES=sums-in-loop sum-in-loop sum-of-two
RM=rm -f
all: $(addprefix $(BIN)/,$(BINARIES))
$(BIN)/%: $(SOURCE)/%.cpp
$(CXX) $(CXXFLAGS) $< -o $@
clean:
$(RM) $(BIN)/*
Upvotes: 3
Reputation: 312
With loops in Makefile, you can do something like :
$(foreach bin,$(BINARIES),$(CXX) $(CXXFLAGS) $(SOURCE)$(dir).cpp -o $(BIN)$dir;)
You can find some info --> http://www.gnu.org/software/make/manual/make.html#Foreach-Function
Upvotes: 0