我在头文件data.h中创建结构类型

 struct student{
    float tutFee;
};
struct employees{
    float salary;
};
struct person{
    char firstName[10];
    char type; //s for student //e for employee
    union {
        struct student student;
        struct employees employ;
    }/*EDIT ->*/common;
};


然后当我尝试在menu.c文件中声明person类型的结构时

    #include "menu.h"
    #include "data.h"

    int initateProgram(){
        struct person temp;
    }


这给我一个错误的说法


menu.c:25:19:错误:“温度”的存储大小未知


这使我相信,由于某种原因,menu.c无法访问data.h,或者我声明结构错误,因此不胜感激

编辑

在上面的代码中为联合添加了名称。
还是给我错误
我正在如下编译


gcc -o a2 uni_personal.c menu.c


uni_personal.c是在menu.c中调用函数initateProgram()的主文件
尝试在任一位置声明一个结构仍然会给我一个错误
感谢你目前的帮助

编辑2

我仍然会收到错误,但是当我简化程序时,它消失了,因此显然错误与该特定代码无关

最佳答案

程序中的struct person temp;声明没有问题。出现“'...'的存储大小未知”错误的原因是,编译器仅看到该类型的前向声明,而没有看到实际的定义。另一方面,假设"data.h"文件中包含的menu.c文件是您在文章顶部显示的文件,则您的代码完全有效。您可以通过仅运行编译器的预处理器状态并检查输出来检查是否是这种情况。这可以通过传递特定于编译器的标志(-Egcc)来实现。

在编辑问题之前:您会看到此问题,因为union的定义不符合编译器使用的C标准(C11之前的版本),因为union成员没有名称。在C11之前,某些编译器(例如gcc)支持匿名联合作为编译器扩展。

给它添加名称应解决与C99兼容的编译器的问题:

struct person{
    char firstName[10];
    char type; //s for student //e for employee
    union {
        struct student student;
        struct employees employ;
    } common; // <<== Here
};

关于c - 使用头文件C中定义的结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28564442/

10-11 23:00
查看更多