Using extren with structures

Discussion in 'General Electronics Chat' started by aamirali, Nov 26, 2012.

  1. aamirali

    Thread Starter Member

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

    1. main.c

    Code ( (Unknown Language)):
    1. typedef struct
    2. {
    3.     int a;
    4.     int b;
    6. } my_str;
    9. void main()
    10. {
    11.    my_str v;
    13.    v.a = 10;
    14. }
    2. other.c

    Code ( (Unknown Language)):
    1. extern my_str j;              // shows error
  2. WBahn


    Mar 31, 2012
    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.