sharing structs

Programming, for all ages and all languages.
Post Reply
stonedzealot

sharing structs

Post by stonedzealot »

Just wondering what the procedure was to share structs between two c units, the same way you share functions (just declare the function at the beginning of the unit and the linker handles it). What is the way to handle this?
Joel (not logged in)

Re:sharing structs

Post by Joel (not logged in) »

Depends on what you're trying to do. If you're trying to share the type, then just use a header file (or retype the struct definition, but a header file is easier). If you're trying to share an actual variable, use the extern keyword. The following example will demonstrate both:

Code: Select all

/* structdefinition.h */

typedef struct MYSTRUCT
{
    int some_variable;
    int some_other_variable;
} MyStruct;

Code: Select all

/* Unit1.c */

#include "structdefinition.h"

MyStruct mystruct;

Code: Select all

/* Unit2.c */

#include "structdefinition.h"

/* the following declaration references the same
    variable that is declared in Unit1.c */

extern MyStruct mystruct;
I think that's right. I don't have time to look over it too much right now.
Post Reply