Using extren with structures

Thread Starter

aamirali

Joined Feb 2, 2012
412
I want to access struct elements in othe rfile:

1. main.c

Rich (BB code):
typedef struct
{
    int a;
    int b;

} my_str;


void main()
{
   my_str v;

   v.a = 10;
}
2. other.c

Rich (BB code):
extern my_str j;              // shows error
 

WBahn

Joined Mar 31, 2012
30,071
The purpose of the extern qualifier on a variable is to tell the compiler that somewhere out there is a variable of this type with this name, so don't define it (meaning, don't allocate memory for it), just declare it (meaning, be aware of it) and somewhere else I will define it (meaning, actually cause memory to be allocated to it) exactly once at a location in the code where the various instances of declaration can see it within their scope.

If you are just wanting to be able to declare variables of that structure type, then simply put the typedef statement and struct definition (which you have combined, here) into a header file that is included in any source code file that needs to use that structure.

A better way of doing it is to declare the structure in a file along with functions that act on the elements of that structure in one file. In the header file for that file, declare the typedef (just the typedef, do NOT provide the internal stucture of the, well, structure in the header file). Also in the header file, provide prototypes for functions that manipulate the information (not the data, but what that data represents) structure that you want people (even if it's only just you) using in their code. This give you tremendous freedom to make changes to how you store information in the structure.
 
Top