To generate dependency files I can use something like this to generate dependency files:
-include $(patsubst %.cpp,build/%.d,$(SRC))
build/%.o: %.cpp
$(CC) $(CXXFLAGS) -c -o $@ $<
$(CC) $(CXXFLAGS) -MM -MT $@ -MF $(patsubst %.o,%.d,%@) $<
This generates everything and puts both the object and dependency files into the build dir where I want them. But this makes two dependency lines for the <file>.o targets, one from the -include rule and with all the header dependencies, and one which is from the pattern rule. Will this get interpreted correctly, i.e. when a header is modified, the object will be recompiled via the command specified for the pattern rule?
Edit: So this approach does in fact work quite well. I guess I’d like somebody to provide an answer which gives me some insight into what it is exactly that make does in these situations. For instance, what if a different command was given for both rules for the same target? My guess would be that it gives an error since it wouldn’t be obvious which command to execute.
You should add one more pattern rule to express the dependency between the
.cppand.dfiles and use that rule to create the.dfiles (second line in the pattern rule of your question) instead of creating the.dfiles unconditionally. It might make sense to introduce another dependency between all.hand.cppfiles and all.dfiles to force re-creating the.dfiles if a header or source file changes.Here’s the separate rule for .d files (hope I got it right):
I’m afraid currently it would only work by chance (or you have not given all relevant pieces from the make file). See, you have not expressed any dependency between
.dfiles and.cppfiles. This, however, is needed so that your.dfiles get updated before inclusion as make file fragment.With that syntax it wouldn’t make a difference. But there are some special cases where splitting the rules into two (though otherwise identical rules) has merit. I strongly recommend you get the book “Managing Projects with GNU Make” to get a grip on the various ways of working with GNU Make. The only other recommendation in connection with GNU Make is to read to read the paper here.