Handmade Hero»Forums»Code
Jari Komppa
41 posts / 1 project
Programmer, designer, writer, a lot of other things; http://iki.fi/sol
How do you do metaprogramming in C?
Nobody really asked for it, but here's a short description of the code generation I do in the SoLoud audio engine project.

The audio engine itself is c++. I have a code generator that parses the c++ header files and spits out a few files: c wrapper code that calls c++ functions (.c and .h), DLL definition and a python script with description of the c API.

These are then used to compile a 'c' api DLL, and a bunch of scripts are used to generate glue code using the DLL in python, c#, D, ruby, gamemaker, etc.

Most of the work in the code generator is parsing the c++ header - it's not a complete c++ parser naturally, only understanding the subset I happen to be using (and needs to be patched almost every time I add some completely new kind of feature).
10 posts
How do you do metaprogramming in C?
Edited by m1el on
As Casey said, you generate Abstract Syntax Trees.

Every time meta-programming is mentioned, there is going to be a post about Lisp.

You might hate Lisp, you might hate parentheses, you might hate garbage collection, you might hate linked lists.

But if you try meta-programming in Lisp, you will see how easy it is. Because Lisp's programs are represented using default data structures, which are always available to the user.

If you want to know how to do meta-programming, learn to write toy macros in Lisp.
Then try applying that knowledge to other languages. You will see that manipulating Abstract Syntax Trees for other languages is somewhat harder, but the idea *will* work. I've done it for several languages, but it is *much* easier to do in Lisps.

This is the only sane way to do meta-programming: manipulating Abstract Syntax Trees. Parsing and printing code is basically secondary.

Too many times I've seen people doing meta-programming with printf-esque techniques, C++ templates and storing logic in XML.
17 posts
How do you do metaprogramming in C?
maybe writing your own lisp
http://www.buildyourownlisp.com/ will get you on the way
29 posts
I enabled the dark theme.
How do you do metaprogramming in C?
Relevant post from Andreas Fredriksson about emitting C from Lisp:

29 posts
I enabled the dark theme.
How do you do metaprogramming in C?
Edited by drjeats on
More code gen from the ZeroMQ / nanomsg guy:


I imagine a DNA reader implementation for C wouldn't be too tough to write.
Sergey Haritonov
1 posts
How do you do metaprogramming in C?
Edited by Sergey Haritonov on
I highly recommend anything about compiling Scheme to C, "Cheney on the MTA" being a prime example.

Edit: links are not working, eh? Please Google "Cheney on the MTA" and "compiling to C" and please pay additional attention to links to the Lambda the Ultimate and the C2 wiki.