How to use m4 and still stay mostly sane

The UNIX macro processor m4 has a really bad reputation. They say that m4 is cryptic and that you will grow hair on your palms for using it. They are wrong.

M4 needs protection

The first key to using m4 for success is that m4 requires you to quote text that should not be expanded. Words like "include", "Unix", and "define" are m4 keywords and will be consumed by m4 without comment if used inappropriately.

To prevent this we must begin a m4'd file with an open quote (`) like this:

	`# Makefile for the grumf product
	# this program begins the cranking with a bandage...
	#
	...
And end the file with a m4 trick to suppress the extra newline:
	...
	foo.o: foo.c barg.h grumf.h
	'dnl

The file needs expansion

Now to expand a macro within the file we must drop quotes, do the expansion, and raise quotes once more. This ends up looking like:

	CDEFS= -D'HOSTTYPE`
The inverted quotes on HOSTTYPE allow the expansion of just that word without any danger to the surrounding text.

Space, the final culture

The clever use of the m4 ifelse construct at the end of a text line is the last trick we need to explore. To make the expanded text look proper we format the ifelse like this:

	${PROG}:$P ${OBJ}
		${CC} -o $@ ${CFLAGS} ${OBJ}'ifelse(
	HOSTTYPE,`SUN5',` -lgen',
	HOSTTYPE,`IRIX5',` -lgen')`

Note that take advantage of the m4 ifelse() function to eat the embedded newlines. This makes the comparison stick out at the beginning of each line.


Return to index.