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

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

问题描述

我有以下的code:

  INT主要(无效)
{
    结构{INT X; } A,B;
    结构{INT X; } C;
    结构{INT X; } * P;    B = A; /* 好 */
    C = A; / *不*工作/
    P =&放大器;一个; / *不*工作/    返回0;
}

而失败GCC(3.4.6)下进行编译,并出现以下错误:

  test.c以8:错误:不兼容的类型赋值
test.c的:9:警告:分配从兼容的指针类型

现在,从我的理解(当然从C99标准),是 A C 应兼容类型,因为他们履行6.2.7节的所有标准,第1款。我试着 STD = C99 编译,都无济于事。

presumably标准间我pretation是错的?

附录

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

 的#define LINKED_LIST(T)\\
    结构{\\
        T * PHEAD; \\
        T * PTAIL; \\
    }...LINKED_LIST(富)list1的;
LINKED_LIST(富)列表2;...LINKED_LIST(富)* PLIST =安培; list1的; / *不*工作/


解决方案

综观的 我猜你是依靠语句后随之而来条件的规定草案:


  

此外,二元结构,联合或枚举在不同的翻译单位申报类型是兼容的,如果他们的标签和成员符合下列要求...


我认为,事实上,这些都是在同一个C文件decared意味着他们是在一个单一的翻译单元。

在猜测它似乎,这保证了当两个C文件包含一个声明类型的标题则该类型的实例将是兼容的。

I have the following code:

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;
}

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

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?

Addendum

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 ...

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

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天全站免登陆