[vox-tech] makefile question - auto dependencies

Mike Simons vox-tech@lists.lugod.org
Fri, 21 Mar 2003 19:16:31 -0500


On Fri, Mar 21, 2003 at 01:23:48PM -0800, Peter Jay Salzman wrote:
> begin Mike Simons <msimons@moria.simons-clan.com> 
> >   I used to use a nasty sed expression to make the .d files, but for
> > some reason decided that they were not needed.
>  
> yes again.  :)   and user supplied .h files as well.
>
> >   Here is a current sample of Makefile which I use to build programs
> > ################
> > %.o: %.c
> > 	gcc ${CFLAGS} -c $^
> > 
> > .%.d: %.c
> > 	@gcc -MM ${CFLAGS} -o $@ $^
>
> if i'm not mistaken, you're ignoring the dependencies of the .d files on
> the .c and .h files.  in other words, your .d file will look like:

  The .d on .c is handled by the second rule above.  The .d on .h's are
not handled.  It looks like I grabbed a too simple version of the
makefile from my working directories... one that doesn't handle .h's
correctly at all.

> when it should look like:
>    main.o main.d : main.c main.h
> 
> that's what the awful sed script does (i think).

  Yes, that is what the sed does... you are correct that the .d file
wouldn't reference itself in the .d, so it wouldn't be rebuilt.
  I think that sed was one I supplied... there are at least three 
generations of that expression, the current one looks like:

====
.%.d: %.c
	@$(SHELL) -ec '$(CC) -M $(CFLAGS) $< \
  | sed '\''s/\($*\)\.o[ :]*/\1.o $@ : /g'\'' > $@; \
#	@touch $@    # this touch makes the Ultrix know the file has changed
  [ -s $@ ] || rm -f $@'

====

  The rm will clean up if the gcc line builds a empty depend file...
if for some reason the file is badly broken, but it doesn't abort the
build at that point... I don't remember why I used the SHELL syntax...
The touch was for some borked Ultrix machines in the UCD CS labs, which
used NFS and for some reason didn't notice the files had changed.

  I don't see why this would not work too:
===
.%.d: %.c
	@$(CC) -MM $(CFLAGS) $< | sed 's/\($*\)\.o[ :]*/\1.o $@ : /g' > $@
#	@touch $@    # this touch makes the Ultrix know the file has changed
	@[ -s $@ ] || rm -f $@
	@[ -f $@ ]

===

  The last -f rule will cause Make to abort if the .d file isn't built.
It's an error after all.  :)

  The -MM should change to -M if your '#include <a>' entries might
change (like in a very complex source package).


> also, is the .o->.c explicit rule really necessary?  make already knows
> how to make .o files from .c files.

  It isn't really needed... but I never know for sure what the implicit
one will do so I put one in.

  Anyway I don't have time to dig through the different Makefiles and
put up one that is most good right now.  If you want to check back after
we get a projector and the lugod spring activities are worked out I
should have time then.

    TTFN,
      Mike