m4 is a powerful macro processor that’s been around for more than thirty years. Here’s the first of two parts, introducing its many magnificent talents.

" />
x
Loading
 Loading
Hello, Guest | Login | Register

Macro Magic: m4, Part One

m4 is a powerful macro processor that’s been around for more than thirty years. Here’s the first of two parts, introducing its many magnificent talents.

A macro processor scans input text for defined symbols — the macros — and replaces that text by other text, or possibly by other symbols. For instance, a macro processor can convert one language into another.

If you’re a C programmer, you know cpp, the C preprocessor, a simple macro processor. m4 is a powerful macro processor that’s been part of Unix for some 30 years, but it’s almost unknown — except for special purposes, such as generating the sendmail.cf file. It’s worth knowing because you can do things with m4 that are hard to do any other way.

The GNU version of m4 has some extensions from the original V7 version. (You’ll see some of them.) As of this writing, the latest GNU version was 1.4.2, released in August 2004. Version 2.0 is under development.

While you won’t become an m4 wizard in three pages (or in six, as the discussion of m4 continues next month), but you can master the basics. So, let’s dig in.

Simple Macro Processing

A simple way to do macro substitution is with tools like sed and cpp. For instance, the command sed’s/XPRESIDENTX/President Bush/’ reads lines of text, changing every occurrence of XPRESIDENTX to President Bush. sed can also test and branch, for some rudimentary decision-making.

As another example, here’s a C program with a cpp macro named ABSDIFF() that accepts two arguments, a and b.

Please log in to view this content.

Not Yet a Member?

Register with LinuxMagazine.com and get free access to the entire archive, including:

  • Hands-on Content
  • White Papers
  • Community Features
  • And more.
Already a Member?
Log in!
Username

Password

Remember me

Forgotten your password?
Forgotten your username?
Read More
  1. Linux Scalability in a NUMA World
  2. Controlling Input/Output of Device Drivers
  3. Absolute Power
  4. The Inter-Integrated Circuit Protocol
  5. Advanced SCSI Drivers and Other Tales
Follow Linux Magazine
Rackspace