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.
Cog isn't exactly a pre-processor, but it does go in-line in the code and generates stuff on the fly.
Sure, the standard C preprocessor is very limited.
I've done such a tool recently: https://github.com/d-ash/perlpp
For example this
becomes this
Syntax is similar to PHP, but it uses Perl instead, and can capture texts into Perl stings.
Edit by cxw — With @d-ash's approval, I am also a maintainer of perlpp. If you have questions, feel free to drop me a line!
You can use your favourite programming language to build a script/tool to generate source files (.c/.cpp or .h, or whatever). Simply
#include
them or compile them into your project. It may help to have comments near the#include
to identify what/where the tool is and what is generated.This may not be as handy (or clean) as using a "real" preprocessor, but it would work. Then again, it really depends on your case.
I'd be interested to see what people come up with. I've tended to do small custom things with preprocessors written in Perl. It's easy to rig up a Makefile that calls the preprocessor. For example, here's a rule to call a program named 'meta' to generate 'file.c' from 'file.c.meta'.
I'm doing fun things with 'meta' like generating custom fit C data structures. It's definitely a direction I'd suggest exploring. My hope is to eventually come up with a meta library roughly parallel to C++ templates.
If you're prepared to get your hands dirty with some C++, there's the Wave parser in Boost, which is built using the Spirit recursive descent parser. It's a complete C pre-processor that conforms to all the latest specs for C and C++ (and, by extension, Objective C, AFAICS).
It's highly modular so you can switch your own driver in that could do the extras you want.
http://www.boost.org/libs/wave/doc/introduction.html
The short answer is "no." The preprocessor is so intimately tied to the semantics of C that you can't really remove it, and in fact in some compilers isn't even a separate phase like it used to be in the old days --- compiling Objective C on a Mac just parses the Objective C syntax. So while you could certainly use another macro-processor, like m4, to process your source text before passing it to C, you wouldn't be eliminating the C preprocessor, you'd be adding another step of preprocessing.
But there's a deeper question here: what do you want to gain by eliminating the CPP phase?