Hacker News new | ask | show | jobs
by radialbrain 4093 days ago
To anyone implementing the automatic dependency generation mentioned in this article, you can actually make things even simpler by combining the compiling and dependency steps.

This works because if you add a new dependency to a file, that information will only be needed for the next build - the current file will already be considered out of date seeing as it was edited to add the #include.

  gcc -MD -MP foo.c -o foo.o
Will compile foo.c into foo.o, and also generate foo.d (-MD). Foo.d will contains make style dependencies, and also a phony target for every dependency (-MP). This allows you to delete dependant files, as make considers the target of a rule that has no perquisites or commands to be up to date if said target does not exist.
1 comments

I second this, using CFLAGS=-MMD or -MD makes writing a Makefile a lot more simpler. This also gets rid of the need to add a rule for building dependency files and you can rely on the built-in rules (see `make -p`) to build object files.

A good Makefile should have any rules for building object files if you're using a language like C or C++, which Make has built-in rules for. If using another language, adding a few generic rules should be enough.

Here's a Makefile template I've been using for some time. It may look complicated initially but only the first 70 or so lines are the actual beef. The rest of the Makefile is helpful rules for tooling (tags, cscope, coverage, profile) but that doesn't work too well at the moment. It also supports out-of-source-tree builds (using vpath to locate source files, object files and other outputs go under $PWD, vpath is does not work for object files).

https://github.com/rikusalminen/makefile-for-c

I can't say I share your love for make's built in rules. I find using them often just makes the build system harder to understand and debug. I usually disable all of the built in ones using:

  # Disable built in suffix rules
  .SUFFIXES:

  # Disable builtin pattern rules
  MAKEFLAGS+=-r
> I can't say I share your love for make's built in rules.

Yes they can be a bit limiting, but even if you do not want to use built-in rules it's still a good idea to use generic rules using wildcards.

This is what lots of "Makefile tutorials" get wrong, they start by writing rules to build individual object files and targets.

Even if you want to write your own build rules, you should not need more than a few good rules for building and linking your object files.

Completely agree with you here - there should never be the need to hardcode file names in a makefile or repeat a rule multiple times - just use pattern rules.