C/C++ Preprocessor Metaprogramming


To start off, I want to give credit where credit is due. I want to thank Paul Fultz and his description of C Preprocessor tricks, tips, and idioms (which I recommend reading!). This is pretty much based off that and I used that as a tutorial to do it myself.

Next, there is also Pauls Cloak library and a Boost Library to do many of these features and I encourage you to check them out.

There's also other macro languages that are probably more powerful. One of my friends has been recommending m4 and so I would recommend looking into it as its pretty cool!.

I have also created a similar library with a couple of extra features. The goal of this post is not to advertise the library however it is to explain how they work, how they are created and how they can be used.


The preprocessor is tool to achieve meta-programming in C/C++. A lot of times I've heard how preprocessor is generally a bad thing especially if you're using macros. I wanted to show how we can use the preprocessor to help write less repetitive code, potentially faster code and potentially cleaner code. I'm not going to lie, the preprocessor macros we're going to define are pretty horrible to look at however I'm going to try explaining it as best as I can. However, once we have these macros defined they can be used to create nicer code.

Preprocessor as a programming language

The preprocessor is has a surprising number of features it can provide us. The problem is we need to implement most of these functions. The best way to describe the preprocessor is that it is a pattern matching language that doesn't have stack. As a result, there’s no concept of local (only parameters to macros), recursion (only tail recursion is allowed), addition/subtraction, loops etc.

However pattern matching can let us implement a bunch of stuff such as conditionals/recursion/arithematic/list comprehension/etc. The first set of tutorials are meant to explain how to generate these functions and the latter part is applications of these features. Since there’s a lot to discuss, I have split it into multiple posts:


Advanced Concepts


Leave a Reply

Your email address will not be published. Required fields are marked *