c - GCC 前向声明和 __may__alias

标签 c gcc

我正在尝试使用 _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/

相关文章:

c - 如何在没有 dlsym 的情况下调用具有相同名称但在另一个共享库中的函数?

c - 如何解释这个c typedef

c - 无锁算法的指针对齐

c - MISRA C 2012 规则 15.4 并用 break 替换 goto

c - 如何告诉 GCC 忽略某些源文件中的警告?

c - 结构类型数组

c - 在位域中声明不同的数据类型有什么用?

c++ - 海湾合作委员会错误?链接方法,断序列点

c++ - gcc 不会编译缺少的 sys/cdefs.h

c++ - 禁用删除析构函数的生成