The m4 Macro Package
When you installed Linux, you installed a lot of cool programs, many of which you use every day. At the same time hundreds of little utilities also got installed, simply because they were required by the bigger, more elaborate applications. However, many of these little utilities are extremely useful in their own right. This article describes one of these second-class utilities: m4.
m4 is a macro processor, meaning that it copies its input to the output, expanding macros along the way. In this regard it's similar to another macro processor you're probably already familiar with: cpp (C Pre-Processor). Like cpp, m4 originally was written as the pre-processor for a programming language (Rational FORTRAN); however, m4 is much more powerful and feature-rich than cpp, which makes it much more useful than just defining constants in programs.
Being a macro processor, m4 certainly provides the ability to define simple macros, but it goes much further. You also can define parameterized macros (macros with arguments), conditionally include text into the output stream, do looping via recursion, run a shell command and insert its output into the output stream, include a file, perform simple string operations (length, substring search, regexp search, etc.), perform simple integer arithmetic and much more.
The examples that follow illustrate many of the features of m4, but this article can't do justice to everything m4 can do for you. Take a look at the info page (see Resources) for a complete description. Also, the examples below are abbreviated versions of m4 macros that I actually use. You can find the full source at my web page listed in Resources.
A word of warning from the m4 info page:
Some people [find] m4 to be fairly addictive...learning how to write complex m4 sets of macros....Once really addicted, users pursue writing of sophisticated m4 applications even to solve simple problems....Beware that m4 may be dangerous for the health of compulsive programmers.
The basic tool of m4 is the macro. Macros are defined with the define command. For example, define(`hello', `Hello, World') defines a macro called hello. Notice the quote characters ` and '. These group words together to form phrases, and when they surround a single word they inhibit macro expansion. Usually, m4 will expand macros within both the macro name and the macro body unless you tell it not to by quoting.
Like cpp, you don't need any special commands or prefix characters to use macros. Everywhere the macro name appears in the input stream, m4 will substitute the macro body.
To run m4, simply give it the name of the file(s) to use as input. It reads through the input, expanding macros as it goes, and generates text on the standard output.
Assume we have the following file called sample.m4:
define(`hello', `Hello, World') hello, welcome to m4!
If we run this file through m4 with the command
m4 sample.m4 > sample.txtit produces the following output:
Hello, World, welcome to m4!
As I said above, m4 goes beyond simple macros. This example demonstrates some of m4's advanced features by defining some macros to ensure that HTML pages all have the same look and feel. HTML purists probably could do this with JavaScript and CSS, but it's so easy with m4 and doesn't require anything special from the browser.
Four macros are defined: one to produce the HTML header, a second to create a banner at the top of the HTML page, a third to create banners within an HTML page (like section headers) and a final one to do some housekeeping at the end of the page. We put these macros into a file called html.m4 and use it as a macro package later.
First, the macro to start an HTML page:
define(`START_HTML',
`<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<meta name="Author" content="D. Robert Adams">
<title>$1</title>
</head>
<body text="#000000"
ifdef(`BACKGROUND_IMAGE',
`background="BACKGROUND_IMAGE"')
bgcolor="#e5e5e5" link="#3333ff"
vlink="#000099"
alink="#ffffff">
')
Line one defines a macro called START_HTML that expands to all the text that follows. Note the use of $1 on line seven. This expands to the first macro argument, which will become the page's title (see the next section for how these macros are used). Also note the use of m4's ifdef macro on line 11. ifdef checks if a macro has been defined. If it has, it includes the text given in the second argument. In this case, ifdef checks if BACKGROUND_IMAGE has been defined. If it has, we include the HTML code to use the image as the web page's background.
Next comes the page header macro:
define(`PAGE_HEADER',
`<table border="0" background="steel.jpg"
width="100%">
<tr>
<td align="left">$1</td>
<td align="right">$2</td>
</tr>
</table>
<div align=right>
Last Modified: esyscmd(`date')
</div>
')
Again, note the use of $1 and $2 on lines four and five that get expanded with macro arguments. Further, note the esyscmd() macro on line nine. esyscmd() tells m4 to run the given shell command and insert its output at the given location. In this case, we run “date” to produce a timestamp in our document.
Next, we create the macro to make a section banner within the page. This uses nothing you haven't seen before:
define(`HTML_BANNER',
`<table border="0"
background="steel.jpg"
width="100%">
<tr>
<td>
<img src="$2">
<h2>$1</h2>
</td>
</tr>
</table>
')
The final piece necessary is the macro to close the HTML “body” and “html” tags:
define(`END_HTML', `</body></html>')Given the above four macros, creating a web page is extraordinarily easy. Create a file (index.m4) that contains calls to our HTML macros. The only thing new is the include macro that inserts our HTML macros:
include(`html.m4') define(`BACKGROUND_IMAGE', `bg.jpg') START_HTML(`Sample Page') PAGE_HEADER(`computer.jpg', `Sample HTML Page') HTML_BANNER(`img1.jpg', `News') HTML_BANNER(`img2.jpg', `Downloads') END_HTMLOnce we've declared the macros and a file that uses them, the final step is to run m4 to create the HTML page. The command is:
m4 index.m4 > index.htmlThat's it! With just seven lines of code we create a fully functional HTML document. By using the macros to create other HTML pages, every page will have the same look and feel. Furthermore, we can change the look by simply changing the macro definitions and re-creating the HTML files.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- RSS Feeds
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Drupal Is a Framework: Why Everyone Needs to Understand This
- Home, My Backup Data Center
- A Topic for Discussion - Open Source Feature-Richness?
- What's the tweeting protocol?
- Dart: a New Web Programming Experience
- Developer Poll
- Trying to Tame the Tablet
- Reply to comment | Linux Journal
41 min 15 sec ago - Reply to comment | Linux Journal
3 hours 13 min ago - Reply to comment | Linux Journal
4 hours 31 min ago - great post
5 hours 5 min ago - Google Docs
5 hours 28 min ago - Reply to comment | Linux Journal
10 hours 16 min ago - Reply to comment | Linux Journal
11 hours 3 min ago - Web Hosting IQ
12 hours 37 min ago - Thanks for taking the time to
14 hours 14 min ago - Linux is good
16 hours 11 min ago
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.




Comments
Re: Take Command: The m4 Macro Package
Extolling the virtues of m4. In 2002.
Wow.
Has anyone noticed that the whole using two different quote
markers is unpleasant, out of use, and hard to read? Not to
mention that nearly all scripting languages like python or perl
provide convenient means of text replacement already and
are generally better known, more well behaved quoting-wise
and end up being easier to read?
Let m4 die.
you can use the following to
you can use the following to redfine quotes:
angequote([,])
Correction
There's some typo here. The m4 builtin function for this is actually "Changequote()".
Exhaustive documentation is available for m4 -- try running "info m4" on your system. If that doesn't work, then try visiting
http://www.gnu.org/software/m4/manual/html_node/index.html.
m4 is amazingly configurable. If you don't like the way it works, chances are good that you re-configure to work in a way that you do like.
Re: Take Command: The m4 Macro Package
I disagree to "let m4 die". Look, i can define a macro within a multiline comment of a java file. Since it is comment, java compiler does not protest. This macro is used to generate an aspectj file, compiled together with the ajc compiler. Thus, using m4 i can have a variety of application versions, by only pointing the compilers to the list of automatically generated files. And for production code i can go without aspectj. Try to do it with perl :)
sincerely,
Jacek Kempski