Isaac Woods
Isaac Woods

Reputation: 1163

Makefile builds everything each time

I have the following Makefile (reduced to ignore irrelevant stuff):

BUILD_DIR=./build
OBJS = \
  $(BUILD_DIR)/main.o \
  $(BUILD_DIR)/common.o \
  ...

roo: $(OBJS)
    $(CXX) -o $@ $(OBJS) $(LFLAGS)

.PHONY: $(BUILD_DIR)
$(BUILD_DIR):
    mkdir -p $(BUILD_DIR)/passes

$(BUILD_DIR)/%.o: src/%.cpp $(BUILD_DIR)
    $(CXX) -o $@ -c $< $(CFLAGS)

However, every object file is recompiled every time, even thought I'm following the rule to directly use $@ in each non-phony target.

I don't think this is a duplicate of this because I'm applying the subdirectory in the rule rather than in the recipe, but I may be wrong? How do I get Make to correctly track the dependencies in the build directory?

Upvotes: 0

Views: 225

Answers (1)

Norman Gray
Norman Gray

Reputation: 12514

You've stated that $(BUILD_DIR)/%.o depends on $(BUILD_DIR), but that directory will be touched every time a file is added to that directory (for example by this rule itself). That is, $(BUILD_DIR) will always be newer than its target.

It looks like you want to create the build directory automatically. The best way to do that, I think, is

$(BUILD_DIR)/%.o: src/%.cpp
    mkdir -p $(BUILD_DIR)/passes
    $(CXX) -o $@ -c $< $(CFLAGS)

Upvotes: 1

Related Questions