Sunday, November 28, 2010

Collections in C

Inspired by Minecraft (like countless other people out there) I decided to give a clone a try to see how this can be accomplished. My last few adventures into the 3D world went through C++ but that always presented me with a problem: The C++ code I write does not scale well to computer games. This time I thought I can probably try to work around the problem by forcing myself to simple C.
This worked really well up to the point where I needed two kinds of lists. One that accepted floats and another one that works with arbitrary pointers.
The C++ way for this is obvious: use templates. That's also one of the best features in C++ and works surprisingly well for the (I imagine) great hack it is. However in C we don't have that but the closest to templates in C (or code generation in general) is the preprocessor.
A warning upfront: all these examples use very generic names. This is a very bad idea. If you want to use something like this in your own code, make sure to prefix all macros, functions, types etc. with a unique prefix. (For instance instead of CAT name it MYLIB_CAT).

Abusing the Preprocessor
Generally there are two ways to do code generation for C. One involves external tools that create new C files, the other involves the C preprocessor which is normally intended to expand macros, include other files or remove comments before the compiler goes over your code.
I normally like to avoid tools that generate new C files for the very simple reason that these usually generate ugly looking code I then have to look at which is annoying or at least require yet another tool in my toolchain which causes headaches when compiling code on more than on operating system. A simple Python script that generates a C file sounds simple, but it stops being simple if you also want that thing to be part of your windows installation where Python is usually not available or works differently.

Read more: Armin Ronacher's Thoughs and Writings