ANSI C Templates

Did you ever wanted to write a template like in C++ in ANSI C? Like e.g. “list<int> mylist;”

I did, but as everybody knows ANSI C has no template support, but it has a powerful preprocessor. So after reading something about x-macros I realized how to achieve that. It’s not the same as x-macros but uses the same ideas.

Here is an example ringbuffer implementation that can be instantiated by type and size:

/** Create RingBufferDouble from type double and size 100 */
#define TYPE double /* datatype for ringbuffer values */
#define SIZE 100 /* static size of ringbuffer array */
#define SUFFIX Double /* type suffix for RingBuffer<Suffix> */
#include "ringbuffer-x.c"
#undef TYPE
#undef SIZE
#undef SUFFIX

/** Create RingBufferInt from type int and size 100 */
#define TYPE int
#define SIZE 100
#define SUFFIX Int
#include "ringbuffer-x.c"
#undef TYPE
#undef SIZE
#undef SUFFIX

/* some sample code for using the new ringbuffer types. */
int main(int argc, char **argv) {
    struct RingBufferDouble rbd;
    struct RingBufferInt rbi;
    double d;
    int i;

    RingBufferDouble_Push(&rbd, 5.0);
    RingBufferDouble_Push(&rbd, 6.0);
    RingBufferDouble_Pop(&rbd, &d);
    RingBufferDouble_Pop(&rbd, &d);

    RingBufferInt_Push(&rbi, 5);
    RingBufferInt_Push(&rbi, 6);
    RingBufferInt_Pop(&rbi, &i);
    RingBufferInt_Pop(&rbi, &i);

    return 0;

The implementation of the ringbuffer “template” is in ringbuffer-x.c. It uses macros as template aguments and the include statement instantiates it. But the code speaks for it self.

Download the complete example here:


0 Responses to “ANSI C Templates”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: