C 中兼容的类型和结构 [英] Compatible types and structures in C

查看:34
本文介绍了C 中兼容的类型和结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

int main(void)
{
    struct { int x; } a, b;
    struct { int x; } c;
    struct { int x; } *p;

    b = a;   /* OK */
    c = a;   /* Doesn't work */
    p = &a;  /* Doesn't work */

    return 0;
}

在GCC(3.4.6)下编译失败,报错:

which fails to compile under GCC (3.4.6), with the following error:

test.c:8: error: incompatible types in assignment
test.c:9: warning: assignment from incompatible pointer type

现在,据我了解(诚然来自 C99 标准),ac 应该是兼容的类型,因为它们满足第 6.2 节中的所有标准.7,第 1 段.我尝试使用 std=c99 进行编译,但无济于事.

Now, from what I understand (admittedly from the C99 standard), is that a and c should be compatible types, as they fulfill all the criteria in section 6.2.7, paragraph 1. I've tried compiling with std=c99, to no avail.

大概我对标准的解释是错误的?

Presumably my interpretation of the standard is wrong?

顺便说一句,这个问题的出现是因为我想声明一些类似模板的宏来包装各种数据类型,而无需在任何地方声明命名类型/类型定义的开销,例如一个简单的例子:

Incidentally, this question arises because I wanted to declare some template-like macros to wrap various datatypes without the overhead of having to declare named types/typedefs everywhere, e.g. a trivial example:

#define LINKED_LIST(T)   
    struct {             
        T    *pHead;     
        T    *pTail;     
    }

...

LINKED_LIST(foo) list1;
LINKED_LIST(foo) list2;

...

LINKED_LIST(foo) *pList = &list1;  /* Doesn't work */

推荐答案

规范草案 我猜你依赖于声明之后的条件:

Looking at the draft specification I'm guessing you're relying on the conditions that come after the statement:

此外,如果它们的标签和成员满足以下要求,则在单独的翻译单元中声明的两种结构、联合或枚举类型是兼容的...

Moreover, two structure, union, or enumerated types declared in separate translation units are compatible if their tags and members satisfy the following requirements ...

我认为这些都在同一个 C 文件中声明的事实意味着它们在一个翻译单元中.

I think that the fact that these are all decared in the same C file means that they are in a single translation unit.

据推测,这似乎保证了当两个 C 文件包含一个声明类型的标头时,该类型的实例将是兼容的.

At a guess it would seem that this guarantees that when two C files include a header that declares a type then instances of that type will be compatible.

这篇关于C 中兼容的类型和结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆