Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

c++ - Make recipe to prevent rebuilding of non-dependent targets

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

there are three targets listed in the phony 'all' target.

Each of those should have a separate rule listed, rather than lumping two of the targets 'app1' and 'app2' together.

Note: any common file changes/compiles will result in both targets being re-created.

break the 'SRC' into SRC_APP1 SRC_APP2 then use the appropriate SRC_APPx macro in each of the app1 and app2 targets.

use similar separation for the 'OBJ' macro and the 'INCLUDES' macro

Do not use the 'foreach' rules as that is asking for all the targets to be built

there are several other details that need addressing, but the above should point you in the right direction.

One thing that should greatly help.

Have the object files for app1 and app2 placed in separate directors and have the makefile look in the appropriate directory for each appx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...