Saturday, March 1, 2008

Automatic make dependencies without sed

I'm currently working with plain GNU Make based projects and - again - I tried to find a nice way to automatically track dependencies and finally found a nice solution when skimming over the g++ manpage. There is a lot of black art flowing around, e.g. this gem is from the GNU Make manual:
%.d: %.c
@set -e; rm -f $@; \
$(CC) -M $(CPPFLAGS) $< > $@.$$$$; \
sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \
rm -f $@.$$$$


Not for the faint of heart, also the thing done by sed is quite trivial. If all you have to support is gcc (portability is overrated!), there's a much more simple way to achieve the same (and more):
%.o: %.c
$(CC) -MMD -MP -MT '$*.d' -c $(CFLAGS) $< -o $@