XTRAN Example — Protect C or C++ Included Files from Multiple Inclusion

It is convenient to be able to include a file multiple times without penalty, e.g. if multiple layers of includes need to include it without knowing whether it has already been included.  We provide for this by inserting preprocessor statements at the start and end of every included file before rendering the code for output.

This code re-engineering automation example uses an XTRAN rules file comprising about 135 non-comment lines of XTRAN's rules language ("meta-code").  The rules are not particularly specific to C and C++; they can be easily adapted to handle any 3GL language with a preprocessor.

The input to and output from XTRAN are untouched.




Rules:

The following is an English paraphrase of the meta-code used:

    For each statement
        If it's an %include of a non-empty file that hasn't already been protected
            Get included file's name from first included statement
            Remap special characters to "_" to make legal preprocessor name
            Insert #ifndef preprocessor statement with comment before first included statement
            Insert following #define preprocessor statement with comment
            Insert #endif preprocessor statement with comment as new last included statement



Process Flowchart

Here is a flowchart for this process, in which the elements are color coded:

process flowchart

Input to XTRAN:

incl_1.h

#define I1A 1
#define I1B 1

incl_2.h

#define I2A 2
#define I2B 2
#define I2C 2

main.c

#include "incl_1.h"
#include "incl_2.h"



Output from XTRAN:

incl_1.h

#ifndef INCL_1_INCLUDED    /*if not included yet*/
#define INCL_1_INCLUDED    /*include only once*/
#define I1A 1
#define I1B 1
#endif                     /*"not included yet"*/

incl_2.h

#ifndef INCL_2_INCLUDED    /*if not included yet*/
#define INCL_2_INCLUDED    /*include only once*/
#define I2A 2
#define I2B 2
#define I2C 2
#endif                     /*"not included yet"*/