简体   繁体   中英

extern structs in C Error: array type has incomplete element type

I have two files, main.c and other.h . I declare a few global variables in main.c , and most of them are fine. I can say extern whatever in other.h and access those variables. However, I defined a struct like this (in main.c ):

struct LSA {
     int myID;
     int seqNum;
     int neighborID[256];
     int costs[256];
 } local_LSA[256];

And when I try to access it in other.h like this

extern struct LSA local_LSA[256];

I get this error message

other.h:27:19: error: array type has incomplete element type ‘struct LSA’
extern struct LSA local_LSA[256];

I've been playing around with for a while, but... I appreciate any help anyone is able to provide!

The structure type needs to be defined before any instances of it can be created.

You need to move the struct definition into other.h before local_LSA is defined.

The header file isn't aware of the struct definition of struct LSA . What you should do instead is to declare the struct in some "lsa.h" then define and allocate the variables of that type in some .c file.

Please note that the design you suggest is spaghetti programming. There should never be a reason for another file to extern access some variable in main.c, which is the top level of your program - or otherwise your program design is flawed. Use setter/getter functions instead of spaghetti.

According to the C Standard (6.7.6.2 Array declarators)

  1. ... The element type shall not be an incomplete or function type .

In this declaration of an array within the file other.h

extern struct LSA local_LSA[256];

the element type struct LSA is incomplete type because the structure definition at this point is unknown.

So the compiler issues the corresponding error message.

other.h:27:19: error: array type has incomplete element type ‘struct LSA’
extern struct LSA local_LSA[256];

What you need is to place the structure definition in the header before the array declaration.

You could write for example in the header file other.h

struct LSA {
     int myID;
     int seqNum;
     int neighborID[256];
     int costs[256];
 };
 
 extern struct LSA local_LSA[256];

Pay attention to that this record

 extern struct LSA local_LSA[256];

is a declaration of an array not a definition.

Then in main.c you could place one more declaration of the array like

struct LSA local_LSA[256];

in this case the declaration of the array will generate the so-called tentative definition of the array.

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