2010-10-05 88 views
0

我试图向前声明一个类与_ 可以 _alias属性,但是当我试图这样做GCC给出了一个错误:GCC向前声明和__may__alias

struct __attribute__((__may_alias__)) MyType; 
MyType* foo(); 

typedef struct __attribute__((__may_alias__)) MyType { ... } MyType; 
MyType* foo() {} 

给出了错误: testc.c:4:错误:1:注:typedef的 'A'
testc.c的重新定义的 'A' 先前的声明在这里
testc.c:5:错误:冲突的类型 '富'
testc.c:2:注意:之前的'foo'声明在这里

有没有办法做到这一点?

回答

3

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 { }; 
+0

对不起,我修复了我的代码,使其具有适当的属性,而不是用于生成它的宏。这可能会让你感到困惑。 – 2010-10-05 20:38:03

+0

@Nathaniel:好的,更清楚,相应地编辑我的回复 – 2010-10-05 21:16:59