全局静态变量在本地函数中突然变为0 - 为什么?

时间:2012-12-21 10:50:44

标签: c

我有一些通用的标题,我在其中声明它(在std.h中):

static volatile unsigned int timestamp;

我在中断的地方增加了它(在main.c中):

void ISR_Pit(void) {
    unsigned int status;
    /// Read the PIT status register
    status = PIT_GetStatus() & AT91C_PITC_PITS;
    if (status != 0) {
        /// 1 = The Periodic Interval timer has reached PIV since the last read of PIT_PIVR.
        /// Read the PIVR to acknowledge interrupt and get number of ticks
        ///Returns the number of occurrences of periodic intervals since the last read of PIT_PIVR.
        timestamp += (PIT_GetPIVR() >> 20);
        //printf(" --> TIMERING :: %u \n\r", timestamp);
        }
    }

在另一个模块中,我有一个必须使用它的程序(在meta.c中):

void Wait(unsigned long delay) {
    volatile unsigned int start = timestamp;
    unsigned int elapsed;
    do {
        elapsed = timestamp;
        elapsed -= start;
        //printf(" --> TIMERING :: %u \n\r", timestamp);
        }
    while (elapsed < delay);
    }

首先printf显示正确增加timestamp但等待printf始终显示0。为什么呢?

1 个答案:

答案 0 :(得分:4)

您将变量声明为static,这意味着它包含在其中的文件的本地变体。timestamp中的main.cmeta.c中的timestamp不同。

您可以通过在main.c中声明volatile unsigned int timestamp = 0; 来解决此问题:

meta.c

extern volatile unsigned int timestamp; 一样:

{{1}}