Reputation: 1990
I am trying to create a C macro, that given a typename will append _info
to it, take the address of that and a call a function with it. Example code (doesn't work):
#define new(X) __new(&(X_info))
struct classInfo
{
size_t size;
void* (*constructor)(void* p);
};
void* __new(struct classInfo* info, ...)
{
return info->constructor(malloc(info->size));
}
void* queue_constructor(void* p)
{
return p;
}
typedef struct
{
uint64_t data;
} queue_t;
const struct classInfo queue_t_info = { .size = sizeof(queue_t),
.constructor = &queue_constructor};
int main(int argc, char** argv)
{
queue_t* p = new(queue_t);
return 0;
}
The preprocessor doesn't seem to want to expand X, as it's error'ing about an undefined symbol X_info
. Not sure what I should change on the macro to fix this.
Upvotes: 3
Views: 1418
Reputation: 37950
You need to use the token concatenation feature of the preprocessor; otherwise it thinks that X_info
is a token by itself:
#define new(X) __new(&(X ## _info))
The reason the preprocessor won't expand the X
in X_info
is that this would have created big problems if there actually was an identifier called X_info
that you needed to refer to in the macro.
As a side note, there is also the stringification feature: if X
is e.g. Person
, "X"
will remain "X"
, while #X
will expand to the string constant "Person"
.
Upvotes: 8