Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

PrevUpHomeNext

Example: 1-to-1 generator

Say you're writing an application that generates C++ code. If you ever did this, you know that it's not nice. Embedding large portions of C++ code in string literals is very awkward. A much better solution is:

  1. Write the template of the code to be generated, leaving placeholders at the points that will change
  2. Access the template in your application and replace placeholders with appropriate text.
  3. Write the result.

It's quite easy to achieve. You write special verbatim files that are just C++, except that the very first line of the file contains the name of a variable that should be generated. A simple tool is created that takes a verbatim file and creates a cpp file with a single char* variable whose name is taken from the first line of the verbatim file and whose value is the file's properly quoted content.

Let's see what Boost.Build can do.

First off, Boost.Build has no idea about "verbatim files". So, you must register a new target type. The following code does it:

import type ;
type.register VERBATIM : verbatim ;

The first parameter to type.register gives the name of the declared type. By convention, it's uppercase. The second parameter is the suffix for files of this type. So, if Boost.Build sees code.verbatim in a list of sources, it knows that it's of type VERBATIM.

Next, you tell Boost.Build that the verbatim files can be transformed into C++ files in one build step. A generator is a template for a build step that transforms targets of one type (or set of types) into another. Our generator will be called verbatim.inline-file; it transforms VERBATIM files into CPP files:

import generators ;
generators.register-standard verbatim.inline-file : VERBATIM : CPP ;

Lastly, you have to inform Boost.Build about the shell commands used to make that transformation. That's done with an actions declaration.

actions inline-file
{
    "./inline-file.py" $(<) $(>)
}

Now, we're ready to tie it all together. Put all the code above in file verbatim.jam, add import verbatim ; to Jamroot.jam, and it's possible to write the following in your Jamfile:

exe codegen : codegen.cpp class_template.verbatim usage.verbatim ;

The listed verbatim files will be automatically converted into C++ source files, compiled and then linked to the codegen executable.

In subsequent sections, we will extend this example, and review all the mechanisms in detail. The complete code is available in the example/customization directory.

PrevUpHomeNext