C程序中的联盟遇到麻烦

PIC*_*ain 3 c global unions

我正在开发一个使用Union的C程序.联合定义在FILE_A头文件中,看起来像这样......

// FILE_A.h****************************************************
xdata union  
{
long position;
char bytes[4];
}CurrentPosition;
Run Code Online (Sandbox Code Playgroud)

如果我在FILE_A.c中设置CurrentPosition.position的值然后调用FILE_B.c中使用union的函数,则union中的数据将返回Zero.这在下面说明.

// 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];
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我将一个long传递给SomeFunctionInFileB(long temp)然后将它存储到该函数中的CurrentPosition.bytes中,最后调用WriteBytesToFlash(CurrentPosition.bytes [n] ......它的工作正常.

似乎CurrentPosition Union不是全球性的.所以我尝试更改头文件中的联合定义以包含这样的extern关键字......

extern xdata union  
{
long position;
char bytes[4];
}CurrentPosition;
Run Code Online (Sandbox Code Playgroud)

然后把它放在源(.c)文件中......

xdata union  
{
    long position;
    char bytes[4];
}CurrentPosition;
Run Code Online (Sandbox Code Playgroud)

但这会导致编译错误,说:

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

那么我做错了什么?如何使联盟全球化?

Mic*_*urr 7

FILE_A.h真的MotionControl.h?如果是这样,我认为修复是在标头中定义一个联合类型:

typedef
union xdata
{
    long position;
    char bytes[4];
} xdata;
Run Code Online (Sandbox Code Playgroud)

并在头文件中的其他地方声明该类型的全局变量(可能是同一个):

extern xdata CurrentPosition;   // in a header file
Run Code Online (Sandbox Code Playgroud)

最后在C文件中定义一次全局变量.也许在file_a.c:

xdata CurrentPosition;
Run Code Online (Sandbox Code Playgroud)

当然,一个更好的修复方法可能是将xdata您想要写出的变量传递给flash,SomeFunctionInFileB()这样您就不必依赖全局变量,众所周知,当不是非常非常谨慎地使用时,这个变量是有问题的.似乎没有充分的理由不将数据作为参数传递:

// in a header file
void SomeFunctionInFileB( xdata const* pPosition);


void SomeFunctionInFileB( xdata const* pPosition)
{
    // After the following lines execute I see all zeros in the flash memory.
    WriteByteToFlash(pPosition->bytes[0];
    WriteByteToFlash(pPosition->bytes[1];
    WriteByteToFlash(pPosition->bytes[2];
    WriteByteToFlash(pPosition->bytes[3];
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

int main.c(void)
{
    CurrentPosition.position = 12345;
    SomeFunctionInFileB( &CurrentPosition);
}
Run Code Online (Sandbox Code Playgroud)