删除Makefile主目标后执行make未重建主目标的问题排查
Hey there, let's dig into why your Makefile isn't rebuilding the app target after you delete it. That error about main.o being up to date when you expect app to be rebuilt is definitely confusing, so let's break this down.
First, let's recall how Make works: when you run make without a target, it builds the first target defined in your Makefile (which is all in your case), and all depends on app. Since you deleted app, Make should immediately recognize that app is missing and run the link command to rebuild it—unless something in your Makefile is throwing it off.
Looking at your Makefile, I notice a couple of potential issues:
- Order of definitions and includes: Your
-includestatement for.ddependency files comes before you defineTARGETand thealltarget. While this shouldn't break things in theory, it's possible the included.dfiles are interfering with Make's ability to prioritize thealltarget. - Redundant object rule syntax: Prefixing the pattern rule with
$(OBJECT_FILE)is unnecessary and might lead to unexpected target prioritization, since pattern rules alone can handle all.cppto.oconversions.
Here's a revised, cleaner version of your Makefile that fixes these problems:
# Explicitly set default goal to ensure Make prioritizes 'all' .DEFAULT_GOAL := all CXX := g++ FLAGS := -std=c++11 TARGET := app # Main target chain all: $(TARGET) # Discover source and object files INCLUDE_DIR := $(shell find . -type d) SOURCE_DIR := $(INCLUDE_DIR) SOURCE_FILE := $(foreach dir, $(SOURCE_DIR), $(wildcard $(dir)/*.cpp)) OBJECT_FILE := $(SOURCE_FILE:%.cpp=%.o) # Include auto-generated dependency files -include $(OBJECT_FILE:%.o=%.d) # Link the final executable $(TARGET): $(OBJECT_FILE) $(CXX) $(FLAGS) -o $@ $(OBJECT_FILE) # Compile individual source files to objects %.o: %.cpp | $(SOURCE_DIR) $(CXX) $(FLAGS) -c $< -o $@ -MD -MF $(@:.o=.d)
To verify your file discovery is working correctly, add this debug target to check which files Make is picking up:
debug: @echo "Discovered source files: $(SOURCE_FILE)" @echo "Corresponding object files: $(OBJECT_FILE)"
Run make debug to confirm both main.cpp and test/func.cpp are listed, along with their .o counterparts.
If the issue still persists, double-check:
- That you've actually deleted the
appexecutable (runlsto confirm it's gone before runningmakeagain) - That you're using a recent version of GNU Make (run
make --version—4.x or newer is recommended)
内容的提问来源于stack exchange,提问作者Rhysol

