gpt4 book ai didi

我可以在不同的文件中定义 2 个相同类型的结构,我想将一个结构传递给另一个吗?

转载 作者:太空狗 更新时间:2023-10-29 16:10:43 25 4
gpt4 key购买 nike

我有两个头文件,如下所述:

文件1.h

typedef struct can_type {
int x;
float y;
} M_can_type;

文件2.h

typedef struct can_type {
int x;
float y;
} can_type;

我可以在上面给出的不同文件中定义相同类型的两个结构,我想将一个结构传递给另一个吗?还有如何将两种不同类型的结构映射到同一类型,以便我可以将一种结构的元素传递给另一种结构?

最佳答案

是的,这是合法的。的确,这是必要的。它在标准中是明确的,但它位于标准中较为冗长且几乎难以理解的部分之一。

ISO/IEC 9899:2011 §6.2.7 Compatible type and composite type

¶1 Two types have compatible type if their types are the same. Additional rules for determining whether two types are compatible are described in 6.7.2 for type specifiers, in 6.7.3 for type qualifiers, and in 6.7.6 for declarators.55) Moreover, two structure, union, or enumerated types declared in separate translation units are compatible if their tags and members satisfy the following requirements: If one is declared with a tag, the other shall be declared with the same tag. If both are completed anywhere within their respective translation units, then the following additional requirements apply: there shall be a one-to-one correspondence between their members such that each pair of corresponding members are declared with compatible types; if one member of the pair is declared with an alignment specifier, the other is declared with an equivalent alignment specifier; and if one member of the pair is declared with a name, the other is declared with the same name. For two structures, corresponding members shall be declared in the same order. For two structures or unions, corresponding bit-fields shall have the same widths. For two enumerations, corresponding members shall have the same values.

55) Two types need not be identical to be compatible.

从“更多”开始的部分讨论了您所询问的情况。

请注意,虽然您的两个 header 中有两个不同的 typedef 名称(M_can_typecan_type),但定义的结构符合要求。请记住,typedef 名称只是现有其他类型的别名(因此 M_can_type 是包含 file1.h 的文件中 struct can_type 的别名code>can_type 是包含 file2.h 的文件中 struct can_type 的别名。因为每个 header 都定义了结构类型,所以任何给定的源文件只能(直接或间接)包含两个 header 之一。如果你试图同时包含两者,你会重新定义结构类型,这是不允许的(即使在 C11 中,只要它定义了相同的类型,你就可以重新定义相同的 typedef 名称,但你仍然不能在单个翻译单元中具有相同范围内的结构类型的两个定义)。

确保不同翻译单元中的类型兼容的最常见方法是使用单个 header 来定义类型并将该 header 包含在两个翻译单元中。但是,如果您考虑一下,编译器不知道或不关心您是否这样做。对它来说重要的是它在预处理后看到的文本识别出相同的类型。

关于我可以在不同的文件中定义 2 个相同类型的结构,我想将一个结构传递给另一个吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40798874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com