Search code examples
cunionsextern

Can I access a union in my source.c from main.c in PIC C18?


I am in a position in which I have got an anonymous structure containing several elements. In order to access them by index I have placed them in a union, like this:

union
{
    struct
    {
        unsigned char COMMAND;      //STRUCT_ARRAY[0]
        unsigned char ADDR_H;       //STRUCT_ARRAY[1]
        unsigned char ADDR_M;       //STRUCT_ARRAY[2]
        unsigned char ADDR_L;       //STRUCT_ARRAY[3]
        unsigned char DATA;         //STRUCT_ARRAY[4]
        unsigned char CHECKSUM;     //STRUCT_ARRAY[5]
    };
    unsigned char STRUCT_ARRAY[6];
    //all of the struct members can be accessed from STRUCT_ARRAY by index
}MY_UNION;

This union currently resides inside a file source.c. I need to access it from main.c. I have a header which both files include, lets call it header.h.

How can I read the value of, for instance, ADDR_H and ADDR_M in main.c while modifying it periodically from source.c?

The code works a bit like this:

source.c:

#include "header.h"

union
{
    struct
    {
        unsigned char COMMAND;      //STRUCT_ARRAY[0]
        unsigned char ADDR_H;       //STRUCT_ARRAY[1]
        unsigned char ADDR_M;       //STRUCT_ARRAY[2]
        unsigned char ADDR_L;       //STRUCT_ARRAY[3]
        unsigned char DATA;         //STRUCT_ARRAY[4]
        unsigned char CHECKSUM;     //STRUCT_ARRAY[5]
    };
    unsigned char STRUCT_ARRAY[6];
    //all of the struct members can be accessed from STRUCT_ARRAY by index
}MY_UNION;

void modify(void)
{
    MY_UNION.ADDR_H = somevalue;
    MY_UNION.ADDR_M = somevalue;
    MY_UNION.ADDR_L = somevalue;
}

In main.c:

#include "header.h"

void main(void)
{
    modify();
    print(MY_UNION.ADDR_H);    //custom function to print values to a screen
    print(MY_UNION.ADDR_M);
    print(MY_UNION.ADDR_L);
}

Solution

  • The easiest way is to typedef the union

    in header.h

    typedef union
    {
        struct
        {
            ...
        };
        unsigned char STRUCT_ARRAY[6];
    }MyUnionType;
    
    extern MyUnionType MY_UNION;
    

    Then in source.c define the variable

    MyUnionType MY_UNION;
    

    This variable now can be used in any source file. (main.c etc)