Martin G
Martin G

Reputation: 18109

How to compile multiple file types in the same way using Make

In a Makefile i have the following two semi-generic targets to handle compilation of any .cc and .cpp files:

$(OBJ_DIR)/%.o: %.cc
    mkdir -p $(dir $@)
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(INCDIRS) -c $< -MD -o $@

$(OBJ_DIR)/%.o: %.cpp
    mkdir -p $(dir $@)
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(INCDIRS) -c $< -MD -o $@

Seeing as they are very similar (only the file extension differs), could i merge them somehow to create one generic target for both file types?

Upvotes: 2

Views: 285

Answers (1)

MadScientist
MadScientist

Reputation: 100781

In general, no, you cannot combine them. You have two options. The first is to use an eval statement as in the answer linked to by Amon Zilca.

The other is to just keep the recipe in a variable and re-use that:

define COMPILE
  mkdir -p $(dir $@)
  $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(INCDIRS) -c $< -MD -o $@
endef

$(OBJ_DIR)/%.o: %.cc
        $(COMPILE)

$(OBJ_DIR)/%.o: %.cpp
        $(COMPILE)

Personally I like this method better; the eval method just feels like overkill to me unless you have a LOT of extensions, or you want to make it easy to add more just by tweaking a variable.

Oh, note you can use $(@D) instead of $(dir $@), as well.

Upvotes: 3

Related Questions