Jakub Lédl
Jakub Lédl

Reputation: 1805

Help with 2 C macros

I've defined 2 macros:

#define HCL_CLASS(TYPE) typedef struct TYPE { \
                          HCLUInt rc; \
                          void (*dealloc)(TYPE*);

#define HCL_CLASS_END(TYPE) } TYPE; \
TYPE * TYPE##Alloc() { TYPE *ptr = (TYPE *)malloc(sizeof(TYPE)); if (ptr != NULL) ptr->rc = 1; return ptr; }

The purpose of these macros is to create a C struct with some predefined members (retain count and deallocator) function and automatically create an allocator function.

Now, when I use these macros as this:

HCL_CLASS(Dummy)
int whatever;
HCL_CLASS_END(Dummy)

they get expanded into this (taken directly from XCode):

typedef struct Dummy { HCLUInt rc; void (*dealloc)(Dummy*);

int whatever;

} Dummy; Dummy * DummyAlloc() { Dummy *ptr = (Dummy *)malloc(sizeof(Dummy)); if (ptr != ((void *)0)) ptr->rc = 1; return ptr; }

And when I try to compile this, I get two errors:

I cannot see a reason for these errors. I'd be grateful if you'd help me find it. Thanks.

Upvotes: 0

Views: 175

Answers (1)

Heath Hunnicutt
Heath Hunnicutt

Reputation: 19467

You need to use the struct as the parameter to dealloc, not the typedef:

#define HCL_CLASS(TYPE) typedef struct _##TYPE { \
                          HCLUInt rc; \
                          void (*dealloc)(struct _##TYPE*);  
                       /* use struct here ^^^^^^, not the typedef */

#define HCL_CLASS_END(TYPE) } TYPE; \
TYPE * TYPE##Alloc() { TYPE *ptr = (TYPE *)malloc(sizeof(TYPE));\
                       if (ptr != NULL) ptr->rc = 1; return ptr; }

This is because the typedef isn't complete where you declare dealloc.

Also, in C++ your struct name and typedef must not collide. So I added an underscore to the struct name via _##TYPE.

Upvotes: 5

Related Questions