![](/img/trans.png)
[英]C11: Typedef of an anonymous struct works with pointers to the typedef as a member?
[英]How is typedef redefinition meant to work in C11?
我读到在 C11 typedef 中允许重新定义,只要定义相同。 但是下面的代码
typedef struct {
int x;
} a_t;
typedef struct {
int x;
} a_t;
int main(int argc, char* argv[]) {
a_t a;
return a.x + argc;
}
使用 C11 标志编译时给我一个重新定义错误:
% clang -std=c11 -o x x.c
x.c:7:3: error: typedef redefinition with different types ('struct a_t' vs 'struct a_t')
} a_t;
^
x.c:3:3: note: previous definition is here
} a_t;
^
1 error generated.
有趣的是,如果 typedef 只是一个原始类型(即 'typedef int a_t;'),那么即使没有 '-std=c11' 标志,重新定义也不会引发错误。
为什么不能重新定义具有结构的类型?
这是来自第 3 方标头的定义的问题。
即使它们具有相同的字段,这两个结构也不是同一类型。 使用命名结构可以更清楚地看到这一点:
struct first {
int x;
};
struct second {
int x;
};
显然,这是两个不同的结构,即使它们具有相同的字段。
因此,在您的情况下,可以定义一个命名结构,然后 typedef 重新定义将起作用。
$ cat test.c
struct A {
int x;
};
typedef struct A a_t;
typedef struct A a_t;
int main(void)
{
}
$ clang -std=c99 test.c
test.c:6:18: warning: redefinition of typedef 'a_t' is a C11 feature
[-Wtypedef-redefinition]
typedef struct A a_t;
^
test.c:5:18: note: previous definition is here
typedef struct A a_t;
^
1 warning generated.
$ clang -std=c11 test.c
$
在这些声明中
typedef struct {
int x;
} a_t;
typedef struct {
int x;
} a_t;
使用了两种未命名的结构,它们被视为两种不同的类型。
所以别名a_t
是为两种不同的类型定义的。
如果想象 typedef 使用相同的类型,那么无论如何都会重新定义未命名的结构,即它被定义了两次。
也就是说,如果你会写例如
struct A
{
int x;
};
struct A
{
int x;
};
那么编译器也会发出类似的错误消息,在这种情况下结构 A 被重新定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.