How do I declare, versus define a struct, such as for data shared between multiple files. I understand the idea when defining primitives. So, for example, I might have:
extern int myvalue; /* in shared header file */
and
int myvalue = 5; /* in data.c file */
But, how do I do the same thing for structs. For example, if I have the following type:
typedef struct {
size_t size;
char * strings[];
} STRLIST;
If I then use the statement:
STRLIST list;
This is both a declaration and definition. So, how do apply the same principle of using an extern?
To declare an instance of a struct (or a pointer to one):
extern STRLIST* ptrList;
extern STRLIST list;
To define it:
STRLIST* ptrList;
STRLIST list;
To declare a struct type:
typedef struct STRLIST;
To define it:
typedef struct {
size_t size;
char * strings[];
} STRLIST;
Note that you can use a pointer to a struct with only a declaration, but you must have a definition to use the struct directly.
Every name in C, before it is used, has to be declared. To declare is (just) to explain what type the name describes. This is information for the compiler how to treat the object of this name.
Definition, on the other hand, instructs the compiler to reserve memory for the object. A definition is always also a declaration.
In your case, the statement:
STRLIST* list;
is indeed a definition but it is a definition of a pointer to your (earlier declared) struct. It declares the name 'list' and it also reserves memory for the address that may point to an object of your struct after it is defined. So it does not in fact define the actual struct. It does not create an object described by your structure — it does not reserve/allocate memory for such an object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With