I don\'t know why the Make recompiles all the files every time including the unchanged files, it takes a long time. I searched the Stack Overflow and found some solutions, b
You're repeating yourself a lot in that Makefile – that's what make
is supposed to avoid.
Consider the following
MODULES=parser compiler test token lex util main
COMPILER_OBJS=$(MODULES:%=$(OBJ)/%.o)
$(OBJ)/%.o: %.c
@test -d $(OBJ) || mkdir $(OBJ)
$(CXX) $(CXXFLAGS) -c -o $@ $<
compiler: $(COMPILER_OBJS)
$(CXX) $(CXXFLAGS) -o $(COMPILER) $(COMPILER_OBJS)
That is, you're using a ‘pattern rule’ to tell Make how to make an object file from a .c
file and, slightly non-standardly but reasonably, having that file placed in another directory.
Using the pattern-based variable reference to set COMPILER_OBJS
means that you only have to specify the list of modules in one place.
The end result should be (I haven't tested this) that make compiler
(or indeed just make
, as long as compiler
remains the first target in the file) will build the compiler
binary, rebuilding whichever .o
files are out of date at that point.
There's a constant tendency to make Makefiles over-complicated, but using pattern rules and pattern-based variable references are useful core functionality, so you should make sure you understand how those lines work (though note that both of these features are specific to GNU Make).