NielsGM
NielsGM

Reputation: 577

Generate makefile targets from a list of source files

I'm trying to create a build system using make and would like to do the following:

have a list of source files specified in the makefile, e.g.

SOURCES = a.cpp b.cpp c.cpp

Automatically create build targets that depend on each file separately

I.e a single rule that would automatically expand into:

a.o: a.cpp
   $(CC) $(CFLAGS) -c a.cpp -o a.o

b.o: b.cpp
   $(CC) $(CFLAGS) -c b.cpp -o b.o

c.o: c.cpp
   $(CC) $(CFLAGS) -c c.cpp -o c.o

I've tried the following:

SOURCES = a.cpp b.cpp c.cpp
OBJECTS = $(SOURCES:.cpp=.o)

$(OBJECTS): $(SOURCES)
   $(CC) $(CFLAGS) -c $< -o $@

However, this seems to expand into the following

a.o: a.cpp b.cpp c.cpp
   $(CC) $(CFLAGS) -c a.cpp -o a.o

b.o: b.cpp b.cpp c.cpp
   $(CC) $(CFLAGS) -c a.cpp -o b.o

c.o: c.cpp b.cpp c.cpp
   $(CC) $(CFLAGS) -c a.cpp -o c.o

Which is not right

Is there a simple way to achieve the result that i wrote earlier?

Upvotes: 1

Views: 1952

Answers (1)

MadScientist
MadScientist

Reputation: 101051

Make already has built-in rules that convert a .cpp file to a .o file. Just write:

SOURCES = a.cpp b.cpp c.cpp

all: $(SOURCES:.cpp=.o)

and it will work. If you want to know how to write your own rules, read about implicit rules, in particular pattern rules.

Upvotes: 1

Related Questions