Dynamic Makefile Rules with GNU-make Pattern

I have a set of .cpp files that I want to compile. These .cpp files are located in a hierarchical directory structure. I want the corresponding .o files to all fall into the same build folder.

Here's how I can get GNU to list files ...

SRCS = \
    $(wildcard $(CODE)/**/*.cpp) \
    $(wildcard $(CODE)/AlgebraLibraries/**/*.cpp) \
    $(wildcard $(CODE)/Calculator/Environments/**/*.cpp)

BARE_SRCS = $(notdir $(SRCS))
BARE_OBJS = $(BARE_SRCS:.cpp=.o)
OBJS = $(addprefix $(BUILD)/, $(BARE_OBJS))

Having done this, I have no idea how to create rules that will create .o files from .cpp files. Intuitively, what I want to do is the following psuedo code.

for i=0, N do  # <-- a for-loop!
  $(OBJS)[i]: $(SRCS)[i]   # <-- the rule!
    $(CPP) -c $(SRCS)[i] -o $(OBJS)[i] # <-- the recipe
end

Of course, this is not valid GNU make code, but I hope you understand what exactly I'm trying to do here. The following steps will not work.

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

This does not work because GNU make matches the% signs, assuming the .o files live with the .cpp files.

, , , , , - . ! .

GNU , , , . , , , . GNU-make?

, , GNU make? , ?

!

+5
2

:

all: $(OBJS)

define ruletemp
$(patsubst %.cpp, $(BUILD)/%.o, $(notdir $(1))): $(1)
    $$(CPP) -c $$< -o $$@
endef

$(foreach src,$(SRCS),$(eval $(call ruletemp, $(src))))
+12

$(BUILD) , :

$(BUILD)/%.o: %.cpp
    $(CPP) -c $< -o $@
+1

All Articles