简体   繁体   中英

typedef struct in header file struct definition in c file

I have a typedef for a struct in sampleHeader.h that is similar to:

typedef struct example Example;

and I have in my 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"

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

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. Outside of the cpp file the compiler doesn't know how big the struct is or what is members are.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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