Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to define a struct using macro

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

  1. You can’t use the usual () around macro values so this is extra brittle.
  2. Don’t use ‘#’ here as that will create strings but you need identifiers.
  3. (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, b is not int *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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading