- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有两个头文件,如下所述:
typedef struct can_type {
int x;
float y;
} M_can_type;
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_type
和 can_type
),但定义的结构符合要求。请记住,typedef 名称只是现有其他类型的别名(因此 M_can_type
是包含 file1.h
和 的文件中
是包含 struct can_type
的别名code>can_typefile2.h
的文件中 struct can_type
的别名。因为每个 header 都定义了结构类型,所以任何给定的源文件只能(直接或间接)包含两个 header 之一。如果你试图同时包含两者,你会重新定义结构类型,这是不允许的(即使在 C11 中,只要它定义了相同的类型,你就可以重新定义相同的 typedef 名称,但你仍然不能在单个翻译单元中具有相同范围内的结构类型的两个定义)。
确保不同翻译单元中的类型兼容的最常见方法是使用单个 header 来定义类型并将该 header 包含在两个翻译单元中。但是,如果您考虑一下,编译器不知道或不关心您是否这样做。对它来说重要的是它在预处理后看到的文本识别出相同的类型。
关于我可以在不同的文件中定义 2 个相同类型的结构,我想将一个结构传递给另一个吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40798874/
使用登录后,我想吐出用户名。 但是,当我尝试单击登录按钮时, 它给了我力量。 我看着logcat,但是什么也没显示。 这种编码是在说。 它将根据我在登录屏幕中输入的名称来烘烤用户名。 不会有任何密码。
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎是题外话,因为它缺乏足够的信息来诊断问题。 更详细地描述您的问题或include a min
我是一名优秀的程序员,十分优秀!