Question

Replacements for the C preprocessor

I'm interested in using something other than the C preprocessor to preprocess my C and Objective-C source code. Are there good alternatives?

An example would be something that allowed one to escape out into a python or perl snippet in the middle of C code, and where the snippet spit out C that is then compiled as normal.

 45  16411  45
1 Jan 1970

Solution

 83

You can use PHP as a C preprocessor. The advantages are:

  • very similiar syntax, so syntax highlighting works.
  • <? and ?> are not used in standard C (with non-standard C, the only thing that gets broken is old GCC extension operator that returns min/max)
  • it's rich in libraries.
  • it's turing complete.
  • usage of macros is very explicit. (compared to sneaky C preprocessor macros)

For serious use though, making PHP print the #line directives is needed for debugging preprocessed code.

<?php include_once "stdio.h"; ?>

int main()
{
    <?php
        for($i = 0; $i < 20; $i++)
            echo 'printf("%d\n", '.$i.');';
    ?>
}
2013-04-27

Solution

 11

Cog isn't exactly a pre-processor, but it does go in-line in the code and generates stuff on the fly.

2008-12-28