简体   繁体   English

头文件中的typedef结构体c文件中的结构体定义

[英]typedef struct in header file struct definition in c file

I have a typedef for a struct in sampleHeader.h that is similar to: 我在sampleHeader.h中有一个结构的typedef,类似于:

typedef struct example Example;

and I have in my sampleSource.c: 我在sampleSource.c中:

struct example{
    char a[4];
    char b[4];
    char c[5];
}

Now for some reason when I return a pointer back to my main function which references a struct that has been created ( and malloc'd) and try to print out the values of each member I get an error along the lines of "cannot derefence incomplete type" 现在由于某种原因,当我返回指向主函数的指针时,该主函数引用了已创建(和malloc'd)的结构,并尝试打印出每个成员的值时,出现了一条错误消息,内容为“无法取消引用不完整类型”

Any ideas? 有任何想法吗?

In the header file you have only forward declared the struct. 在头文件中,您仅向前声明了该结构。 That's fine and you'll be able to declare pointers and references to the struct in the header (and any other header or cpp file that includes this header too). 很好,您将能够在标头(以及包含此标头的任何其他标头或cpp文件)中声明结构的指针和引用。

As the compiler has only seen the definition in the cpp module, this is the only place that you'll be able to declare variables of type struct example by value or to dereference pointers to access members. 由于编译器仅在cpp模块中看到了定义,因此这是您唯一可以通过值声明struct example类型变量或取消引用访问成员指针的地方。 Outside of the cpp file the compiler doesn't know how big the struct is or what is members are. 在cpp文件之外,编译器不知道结构的大小或成员的大小。

If you need to use the struct in multiple modules declare and define the struct together in the header. 如果需要在多个模块中使用该结构,请在标头中一起声明和定义该结构。

Hard to say for sure without seeing the actual code, but.... 在没有看到实际代码的情况下很难确定,但是...

struct example{
    char a[4];
    char b[4];
    char c[5];
};
 ^ note the new semi colon.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM