英文:
how to define a struct using macro
问题
I've identified the code you want to be translated. Here it is in Chinese:
最近,我一直在处理stm32,解决一些消息问题。我试图构建一个队列来存储来自usart和can的消息,然后我想我应该为它们构建一个通用类型。我尝试使用宏来定义不同种类的队列,但是出现了错误。
以下是我的代码,我希望使用"USART_QUEUE2"作为类型:
#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)
这里的错误是:
"message": "expected either a definition or a tag name"
"message": "expected identifier or '(' before string constant"
我不知道该怎么办来修复它。有人可以帮我解决这个问题吗?
我尝试过向ChatGPT提问,但显然它不能正确处理宏问题,哈哈。我查阅了相关的问题,但没有找到精确的解决方案。
英文:
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.
答案1
得分: 2
- 你不能在宏值周围使用通常的
()
,因此这会使它更加脆弱。 - 不要在这里使用 '#',因为那会创建字符串,但你需要标识符。
- (未修复)我不喜欢将 ' * ' 放在类型旁边而不是变量旁边的风格,因为它不具有一般性('int* a, b' 不是 '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);
这是相应的输出:
typedef struct USART_QUEUE2 { u8* buffer; void (*Push)(u8 *src, struct USART_QUEUE2 *queue); } USART_QUEUE2;
英文:
- 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, b
is 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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论