You can use .SECONDEXPANSION
for this. Here's an executable example:
OBJ_DIR:=obj
SRC_DIR:=src
TARGETS:=obj/foo.o obj/bar.o
all: $(TARGETS)
.SECONDEXPANSION:
$(OBJ_DIR)/%.o: $$(wildcard $(SRC_DIR)/%.cpp) $$(wildcard $(SRC_DIR)/%.cc)
@$(CXX) $(CPPFLAGS) -I. -o $@ -c $<
Create src/foo.cc
and src/bar.cpp
, and issue make -n
, and you'll get:
g++ -I. -o obj/foo.o -c src/foo.cc
g++ -I. -o obj/bar.o -c src/bar.cpp
If you have both foo.cc
and foo.cpp
this will behave just like the version in the question asked here (foo.cpp
will have precedence over foo.cc
, which will be ignored).
The $
signs are doubled for $$(wildcard...
to prevent evaluation during the first expansion. You could have $$(SRC_DIR)
just as well as $(SRC_DIR)
since it does not matter (in the code above) when this variable is expanded.