recently I’ve being working on stm32, dealing with some msg issues. I am trying to construct a queue to store messages from usart and can, then it comes to me that I should build a generic type for them. I tried to use a macro to define different kind of queues but errors yield.
here are my codes, I am expecting to use "USART_QUEUE2" as a type:
#define DEF_QUEUE(ITEM_TYPE,NAME) \
typedef struct #NAME \
{\
(ITEM_TYPE)* buffer; \
void (*Push)((ITEM_TYPE)* src, struct #NAME * queue);\
}#NAME;\
DEF_QUEUE(u8,USART_QUEUE2)
the errors here are "message": "expected either a definition or a tag name" "message": "expected identifier or '(' before string constant"
I don’t know what to do to fix it. may someone help me out with this?
I tried ask ChatGPT, but clearly it can’t deal with macro problems properly lol.
I’ve rolled in related questions, didn’t find a precise solution.
>Solution :
- You can’t use the usual
()around macro values so this is extra brittle. - Don’t use ‘#’ here as that will create strings but you need identifiers.
- (Not fixed) I don’t like the style of having the ‘*’ next to the type instead of the variable as it doesn’t generalize (
int* a, bis notint *a, *b).
#define DEF_QUEUE(ITEM_TYPE,NAME) \
typedef struct NAME \
{ \
ITEM_TYPE* buffer; \
void (*Push)(ITEM_TYPE* src, struct NAME* queue); \
} NAME
DEF_QUEUE(u8,USART_QUEUE2);
and here is the corresponding output:
typedef struct USART_QUEUE2 { u8* buffer; void (*Push)(u8 *src, struct USART_QUEUE2 *queue); } USART_QUEUE2;