Makefile improvements, dependency generation not functioning

僤鯓⒐⒋嵵緔 提交于 2019-11-28 20:58:22

Here goes.


Assign simply expanded variables where possible:

SRCS := $(wildcard $(SRC_DIR)/*$(SRC_EXT))

From GNU Make manual:

Another disadvantage [of recursively expanded variables] is that any functions referenced in the definition will be executed every time the variable is expanded. This makes make run slower; worse, it causes the wildcard and shell functions to give unpredictable results because you cannot easily control when they are called, or even how many times.


Use substitution references or patsubst function to convert sources into objects:

OBJS := $(SRCS:$(SRC_DIR)/%$(SRC_EXT)=$(OBJ_DIR)/%$(OBJ_EXT))

Specify proper prerequisites in compilation pattern rule. This is mandatory to get Make keeping your object files up to date and updating them on source changes.

$(OBJ_DIR)/%$(OBJ_EXT) : $(SRC_DIR)/%$(SRC_EXT)
    @echo "-> compiling $@"
    @$(CXX) $(CXXFLAGS) -o $@ -c $<

Compile sources and generate dependency files for them at the same time. Use -MMD -MP flags to get things work (just append them to CXXFLAGS).

CXXFLAGS += -MMD -MP

-include $(OBJS:$(OBJ_EXT)=.d)

From GCC manual:

-MD

-MD is equivalent to -M -MF file, except that -E is not implied. The driver determines file based on whether an -o option is given. If it is, the driver uses its argument but with a suffix of .d, otherwise it takes the name of the input file, removes any directory components and suffix, and applies a .d suffix.

-MMD

Like -MD except mention only user header files, not system header files.

-MP

This option instructs CPP to add a phony target for each dependency other than the main file, causing each to depend on nothing. These dummy rules work around errors make gives if you remove header files without updating the Makefile to match.

Also consider studying this article of Paul Smith (he is a maintainer of GNU Make). It gives a rather good overview of different autodep-generation approaches.

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