`Makefile` rule to regenerate object files directory without recompiling from scratch?

人盡茶涼 提交于 2020-01-06 14:01:33

问题


I have the following Makefile which works great but everytime it is recompiling from start evenif nothing has changed.

CXX = g++

CXXFLAGS = -std=c++11
INC_PATH = `pkg-config --cflags ../openCV/build/lib/pkgconfig/opencv.pc` \
    `pkg-config --cflags ../SDL2-2.0.8/instDir/lib/pkgconfig/sdl2.pc` \
    `pkg-config --cflags ../jsoncpp/build/pkg-config/jsoncpp.pc` \
    -I ../poco/instDir/include/

#LIB_PATH = -L../cmake_bin_dir/lib/ ./gainput/build/lib -L../SDL2-2.0.8/build/ -L../SDL2-2.0.8/build/lib
LIBS =  `pkg-config --libs ../openCV/build//lib/pkgconfig/opencv.pc` \
    `pkg-config --libs ../SDL2-2.0.8/instDir/lib/pkgconfig/sdl2.pc` \
    `pkg-config --libs ../jsoncpp/build/pkg-config/jsoncpp.pc` \
    -L../poco/instDir/lib/ -lPocoNetd -lPocoUtild -lPocoFoundationd \

SOURCEDIR := ./
SOURCES := $(wildcard $(SOURCEDIR)/*.cpp)
OBJDIR=$(SOURCEDIR)/obj

OBJECTS := $(patsubst $(SOURCEDIR)/%.cpp,$(OBJDIR)/%.o, $(SOURCES))
DEPENDS := $(patsubst $(SOURCEDIR)/%.cpp,$(OBJDIR)/%.d,$(SOURCES))

# ADD MORE WARNINGS!
WARNING := -Wall -Wextra

# .PHONY means these rules get executed even if
# files of those names exist.
.PHONY: all clean

# The first rule is the default, ie. "make",
# "make all" and "make parking" mean the same
all: parking

clean:
    $(RM) $(OBJECTS) $(DEPENDS) parking

# Linking the executable from the object files
parking: $(OBJECTS)
    $(CXX) $(WARNING) $(CXXFLAGS) $(INC_PATH) $^ -o $@ $(LIBS)

-include $(DEPENDS)

$(OBJDIR):
    mkdir -p $(OBJDIR)

$(OBJDIR)/%.o: $(SOURCEDIR)/%.cpp Makefile $(OBJDIR)
    $(CXX) $(WARNING) $(CXXFLAGS) $(INC_PATH) -MMD -MP -c $< -o $@

The problem seems to be these lines

$(OBJDIR)/%.o: $(SOURCEDIR)/%.cpp Makefile $(OBJDIR)
    $(CXX) $(WARNING) $(CXXFLAGS) $(INC_PATH) -MMD -MP -c $< -o $@

and particularly the dependency from $(OBJDIR) (where *.o and *.d files are saved) in fact when I remove it seems not to recompile. The problem is that if I remove the $(OBJDIR), the directory is not regenerated again.

What is the Makefile rule to regenerate the directory where object files are stored without starting all the compilation from scratch?


回答1:


$(OBJDIR) is a prerequisite of your object files. As with any directory, its last modification time changes every time its content changes... Declare it as an order-only prerequisite instead:

$(OBJDIR)/%.o: $(SOURCEDIR)/%.cpp Makefile | $(OBJDIR)

This way, if it exists already, its last modification time will not be considered by make to decide which targets need to be re-built.



来源:https://stackoverflow.com/questions/52643785/makefile-rule-to-regenerate-object-files-directory-without-recompiling-from-sc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!