我正在尝试使用 _may_alias 属性转发声明一个类,但当我尝试这样做时,GCC 给出了错误:
struct __attribute__((__may_alias__)) MyType;
MyType* foo();
typedef struct __attribute__((__may_alias__)) MyType { ... } MyType;
MyType* foo() {}
报错:
testc.c:4: 错误:重新定义 typedef ‘A’
testc.c:1:注意:之前的“A”声明在这里
testc.c:5: 错误:‘foo’的类型冲突
testc.c:2:注意:之前的“foo”声明在这里
有办法做到这一点吗?
最佳答案
C 不允许执行两次 typedef
。此外,您必须区分 struct
的前向声明和 typedef
的前向声明。最简单的方法是使用与 struct 标记和 typedef 标识符相同的标记。如果没有属性,在标准 C 中这将如下所示:
/* this is a forward declaration of struct and typedef */
typedef struct MyType MyType;
MyType* foo(void);
/* declare the struct as a struct */
struct MyType { };
MyType* foo(void) { return NULL; }
现在开始玩属性了。您必须找出它适用于 struct
声明或 typedef
。我的猜测是针对 struct
,但是快速查看一下 gcc 信息应该会告诉您这一点。
/* this is a forward declaration of struct and typedef */
typedef __attribute__((__may_alias__)) struct MyType MyType;
/* declare the struct as a struct */
__attribute__((__may_alias__)) struct MyType { };
关于c - GCC 前向声明和 __may__alias,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3867007/