Greg Hilston
Greg Hilston

Reputation: 2424

How can I make this Makefile more generic?

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:

  1. Append the name to the end of "BINARIES"

  2. 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

Answers (2)

Chris Dodd
Chris Dodd

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

Gr&#233;gory Vaumourin
Gr&#233;gory Vaumourin

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

Related Questions