Trouble with Unions in C program.
- by Jordan S
I am working on a C program that uses a Union. The union definition is in FILE_A header file and looks like this...
// FILE_A.h****************************************************
xdata union
{
long position;
char bytes[4];
}CurrentPosition;
If I set the value of CurrentPosition.position in FILE_A.c and then call a function in FILE_B.c that uses the union, the data in the union is back to Zero. This is demonstrated below.
// FILE_A.c****************************************************
int main.c(void)
{
CurrentPosition.position = 12345;
SomeFunctionInFileB();
}
// FILE_B.c****************************************************
void SomeFunctionInFileB(void)
{
// After the following lines execute I see all zeros in the flash memory.
WriteByteToFlash(CurrentPosition.bytes[0];
WriteByteToFlash(CurrentPosition.bytes[1];
WriteByteToFlash(CurrentPosition.bytes[2];
WriteByteToFlash(CurrentPosition.bytes[3];
}
Now, If I pass a long to SomeFunctionInFileB(long temp) and then store it into CurrentPosition.bytes within that function, and finally call WriteBytesToFlash(CurrentPosition.bytes[n]... it works just fine.
It appears as though the CurrentPosition Union is not global. So I tried changing the union definition in the header file to include the extern keyword like this...
extern xdata union
{
long position;
char bytes[4];
}CurrentPosition;
and then putting this in the source (.c) file...
xdata union
{
long position;
char bytes[4];
}CurrentPosition;
but this causes a compile error that says:
C:\SiLabs\Optec Programs\AgosRot\MotionControl.c:76: error 91: extern definition for 'CurrentPosition' mismatches with declaration.
C:\SiLabs\Optec Programs\AgosRot\/MotionControl.h:48: error 177: previously defined here
So what am I doing wrong? How do I make the union global?