Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct declaration versus definition

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?

like image 772
Tyler Durden Avatar asked Jul 05 '16 01:07

Tyler Durden


2 Answers

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.

like image 160
dbush Avatar answered Sep 23 '22 06:09

dbush


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.

like image 34
Walt Avatar answered Sep 23 '22 06:09

Walt