【发布时间】:2019-01-23 15:12:31
【问题描述】:
在第一个编译单元中:
/* From .h file */
struct my_struct {
int foo;
long bar;
};
void my_struct_init(struct my_struct*);
int my_struct_get_int(struct my_struct*);
long my_struct_get_long(struct my_struct*);
/* From .c file */
void my_struct_init(struct my_struct* o) {
o->foo = 0;
o->bar = 0L;
}
int my_struct_get_int(struct my_struct* o) {
return o->foo;
}
long my_struct_get_long(struct my_struct* o) {
return o->bar;
}
在第二个编译单元中:
/* From .h file */
struct my_struct {
/* Named differently */
int foo_different;
long bar_different;
};
void my_struct_init(struct my_struct*);
int my_struct_get_int(struct my_struct*);
long my_struct_get_long(struct my_struct*);
/* From .c file */
int main(void) {
struct my_struct o;
my_struct_init(&o);
if (o.foo_different != 0 || o.bar_different != 0L) {
/* (Just assume EXIT_FAILURE is 1) */
return 1;
}
o.foo_different = 1;
o.bar_different = 2L;
if (my_struct_get_int(&o) != 1 || my_struct_get_long(&o) != 2L) {
return 1;
}
return 0;
}
虽然两个结构体同名,成员的类型和顺序相同,但成员的名字不同。
这是否意味着上面没有定义?或者这会一直成功吗?
(对于上下文,如果正常包含头文件,我将使用它为成员添加前缀“_my_type_private_”,但如果它是从内部实现文件中包含的,则保持相同,因此类型不是不完整的,但它是更难意外修改结构)
编辑:这个问题不是那个问题的重复,但它确实提供了正确的答案:
此外,如果 [对于每对成员声明] 该对中的一个成员用一个名称声明,另一个用相同的名称声明,则在单独的翻译单元中声明的两个结构、联合或枚举类型是兼容的
所以它们不是兼容的类型。
【问题讨论】:
-
您是否尝试过实际操作?我怀疑如果你尝试链接这两个单元,你会得到一个关于重复符号的链接器错误。
-
@AleksG 是的,它适用于 gcc 和 clang,没有链接器错误。
-
@GovindParmar:不,不是。
-
@EricPostpischil 问题本身可能不是重复的,但 OP 正在寻找的答案(标签和成员名称会影响兼容性吗?)在该问题的接受答案中进行了讨论
-
@GovindParmar:如果一个问题与另一个问题重复,则该问题是重复的。如果它不重复另一个问题,则它不是重复的。不同问题的答案提供与问题相关的信息这一事实不会使问题重复。将来,当其他人正在寻找有关问题 A 的信息时,他们将不知道要寻找不同的问题 B。他们将搜索问题 A,并且可能找不到或可能忽略封闭的问题。他们不会因为某些不同的问题包含答案而受益。
标签: c data-structures struct types language-lawyer