no one special
no one special

Reputation: 1766

Compile multiple file types with one rule using makefile

Lets assume I have a following makefile:

CPPFILES := $(wildcard *.cpp)
OBJFILES := $(CPPFILES:.cpp=.o)

.PHONY: all
all: $(OBJFILES)

%.o: %.cpp
    $(CXX) -c $< -o $@

Now I would like to add support for *.cc files. Is any possibility to expand line %.o: %.cpp to process both *.cpp and *.cc files in one line? I would expect something like: %.o: %.cpp %.cc.

Upvotes: 3

Views: 1262

Answers (1)

user657267
user657267

Reputation: 21000

You're really just reinventing make's builtin rules, but the following should work

CCFILES     := $(wildcard *.cc)
CPPFILES    := $(wildcard *.cpp)
CCOBJFILES  := $(CCFILES:.cc=.o)
CPPOBJFILES := $(CPPFILES:.cpp=.o)
OBJFILES    := $(CCOBJFILES) $(CPPOBJFILES)

.PHONY: all
all: $(OBJFILES)

$(CCOBJFILES): %.o: %.cc
$(CPPOBJFILES): %.o: %.cpp
$(OBJFILES):
    $(CXX) -c $< -o $@

With the builtin rules the above can be shortened to

CCFILES  := $(wildcard *.cc)
CPPFILES := $(wildcard *.cpp)

.PHONY: all
all: $(CCFILES:.cc=.o) $(CPPFILES:.cpp=.o)

Upvotes: 2

Related Questions