I have the following project directory structure:
Prog
/include
/include/dir1
/include/dir2
/src
/src/dir1
/src/dir2
App1 depends on mod1 and mod2 where as App2 depends only on mod1.
With the makefile denoted below the modules and apps all build correctly - however if I make a change to mod2 and then do a 'make all', App2 gets rebuilt even though it doesn't have a dependency.
The reason for this is because OBJ being passed into the target build recipe is all of the OBJs and not just the specific ones that the current target needs.
I was wondering what change to the makefile can be made to only pass the dependent objects to the current target that's being built.
The makefile:
CC := g++
LD := g++
TARGETS := app1 app2
MODULES := mod1 mod2
INC_DIR := $(addprefix include/,$(MODULES))
SRC_DIR := $(addprefix src/,$(MODULES))
BUILD_DIR := $(addprefix build/,$(MODULES))
SRC := $(foreach sdir,$(SRC_DIR),$(wildcard $(sdir)/*.cpp))
OBJ := $(patsubst src/%.cpp,build/%.o,$(SRC))
INCLUDES := -Iinclude $(addprefix -I,$(INC_DIR))
vpath %.cpp $(SRC_DIR)
define make-goal
$1/%.o: %.cpp
$(CC) $(INCLUDES) -c $$< -o $$@
endef
.PHONY: all checkdirs clean
all: checkdirs $(TARGETS)
$(TARGETS) : %: $(OBJ)
$(CC) $(INCLUDES) -o build/$@ src/[email protected] $^
checkdirs: $(BUILD_DIR)
$(BUILD_DIR):
@mkdir -p $@
The makefile has been repurposed from the following answer:
https://stackoverflow.com/a/2484343
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…