Simple C++ Macro Processor

Thomas Wang, July 1997

Introduction

I needed a basic library for my project. I determined that STL is not exactly the thing I wanted. I went ahead, and developed a simple template library of my own. During testing, I detected our C++ compiler does not support template features very well. Simple cases compiled, but complicated cases would not.

At this time, I figured my strategy was sound, but bugs in the compiler ruined my plan. I needed a work around for the lack of template support. The solution was a simple macro processor that translates macro templates to generated C++ source.

Parameterized Classes

Suppose you want a single linked list of cars, you can code this way.

#ifndef SLINKCAR_H
#define SLINKCAR_H

#include <car.h>

struct slinkcar
{
  car first;
  slinkcar *next;
};

#endif

However, some information are hardwired into this file. If you want a single linked list of airplanes, then you have to copy and rewrite the source. This is a tedious task.

If you have a macro processor, then you can write a single version of template file that can be used to generate a number of different source files.

#ifndef $cap($myclass)_H
#define $cap($myclass)_H

#include <$inc>

struct $myclass
{
  $type first;
  $myclass *next;
};

#endif

To generate a source file, you would simply run the macro processor, given the template name, and the definitions for its parameters.

cmacro.exe slink.h myclass=slinkcar inc=car.h type=car > slinkcar.h

Macro Processor

I have written the macro processor in a language called Icon. The Icon language is well suited for writing simple text translators. The Icon compiler can be obtained from the University of Arizona. The source code for the macro processor is only about five pages long.


* Visit Icon compiler site
* Read cmacro.icn source

Simple C++ Macro Library

With the macro processor done, the next task is the writing of the macro library. The simple C++ macro library is available now. They contain a number of container classes. You can read about them in the article named Simple C++ Macro Library.


HOME

Give feedbacks to wang@cup.hp.com