【发布时间】:2021-10-18 17:49:30
【问题描述】:
0.c
#include <stdio.h>
struct test{
int a;
};
struct test get(int in);
int main(){
struct test t = get(1234);
printf("%d\n",t.a);
return 0;
}
1.c
struct test{
char a; // Note this is char instead of int.
};
struct test get(int in){
struct test t = {in};
return t;
}
struct test 有两种不同的定义。一种以int 为数据类型,另一种以char 作为其数据类型。
这是未定义的行为吗? C 没有像 C++ 那样正式拥有one dentition rule,这篇文章说多个定义可以吗? Are different translation units allowed to define structures with the same name?
【问题讨论】:
-
绝对是UB。也许是严格的别名违规?
-
直觉上我猜如果结构有内部链接这很好,但外部链接可能会出现问题,因为链接器可能会在两个翻译单元之间生成相同的符号名称。
-
链接的问题有什么不清楚的地方吗?那里接受的答案对我来说似乎很简单,问题中提出的情况几乎与这个相同。
-
链接的问题说这没问题,这看起来根本不行。更具体地说,我在另一个 TU 中使用了一个 TU 的结果。
-
在另一个 TU 中使用结果并具有两个单独的定义是完全不同的两件事。如果返回类型的定义对于定义函数的 TU 而言是本地的,则它不能在该 TU 之外使用,除非在外部定义了相同的类型并且完全兼容。
标签: c