I\'m currently trying to build a proper Makefile.
What I want is full control of what\'s happening, so I don\'t want any third party software.
My current att
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 thewildcard
andshell
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 theMakefile
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.