Tuesday, September 6, 2011

Preprocesing C with python

Heh, I cooked together a small shellscript that allows you to pre-process C code (technically also C++-code, if you make a minor alteration to the script) with python.

It's set up to echo everything that doesn't begin with "%%", and pass those lines to python.


cat $1 |
sed 's/^\([^\%]\+[^\\]*\)\\\(.*\)$/\1\\\\\2/g' |
sed 's/^\([^\%]\+.*\)$/print """\1"""/g' |
sed 's/^[\%][\%]\(.*\)$/\1/g' | python - > $tmpsource
gcc -x c $@ $tmpsource
rm $tmpsource

It's used like this:

./cppy.sh sourcefile.c (flags-for-gcc)

For example, the following code prints "Hello World".

#include <stdio.h>

%%print "char* c = \"Hello World\";";

int main(int argc, char* argv[]) {
printf("%s\n", c);
return 0;

No comments:

Post a Comment