如何使用宏定义一个结构体

huangapple go评论70阅读模式
英文:

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

  1. 你不能在宏值周围使用通常的 (),因此这会使它更加脆弱。
  2. 不要在这里使用 '#',因为那会创建字符串,但你需要标识符。
  3. (未修复)我不喜欢将 ' * ' 放在类型旁边而不是变量旁边的风格,因为它不具有一般性('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;
英文:
  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;

huangapple
  • 本文由 发表于 2023年6月13日 15:07:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76462427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定