I wouldn't call myself a makefile expert--nobody wants to admit to that, but I probably am one. When you are known as a makefile expert, people tend to come to you with makefile problems because they don't want to learn how to use them. And I don't blame them.
Nobody really likes makefiles. People learn just enough to create one and then copy it from project to project and never think about it again.
@dutch's makefile is pretty good. The only non-trivial thing I see in it that I would change is the DEPS value. In this makefile, all source files will be recompiled when any header file changes. For small toy projects and homework assignments, that's fine. However, in a large production, this could lead to huge wastes of time.
Better would be to dynamically calculate the dependencies when compiling the source code. Roughly, you need to add something similar to the following
1 2 3 4 5 6 7 8 9
|
DEPDIR := dep
DEPS = $(SRCS:%.cpp=$(DEPDIR)/%.dep)
$%.o : %.cpp
mkdir -p $(DEPDIR)
$(CXX) $(CXXFLAGS) -MMD -MF $(DEPDIR)/$(*F).dep -o $@ $<
-include $(DEPS)
|
Note: This is copied from one of my projects where things are in different directories, so things might have been messed up a bit in the simplification. (You could do it without the DEPDIR, but then all of your dependency files would end up in the directory with the source and object files.)
The important things are the -MMD and -MF flags to the compiler which tell it to generate dependency files. Then the -include line AT THE END OF THE MAKEFILE telling make to include these files if they exist.
It's worth knowing that these options exist so when you get involved in large projects where you don't want to recompile everything for a minor header change, you can improve your makefiles to avoid the issues.