所以我被打約試圖瞭解使用靜態變量,顯然我的理解是還沒有應用,因爲我不明白以下是如何操作:訪問和修改局部靜態變量
主要叫我該吐出奏x和y中的內容從other.c
//main.c
#include <stdio.h>
#include <stdint.h>
#include "other.h"
int main (void)
{
printf("Main - X: %d, Y: %d\r\n\n",x,y);
func();
printf("Main - X: %d, Y: %d\r\n\n",x,y);
func();
printf("Main - X: %d, Y: %d\r\n\n",x,y);
printf("Main - X: %d, Y: %d\r\n\n",++x,++y);
return 0;
}
other.h
//other.h
void func(void);
uint8_t x;
static uint8_t y;
other.c
有用的功能//other.c
#include <stdio.h>
#include <stdint.h>
#include "other.h"
void func(void)
{
x += 1;
y += 2;
printf("Func - X: %d Y: %d\r\n",x,y);
}
我的輸出:
Main - X: 0, Y: 0
Func - X: 1 Y: 2
Main - X: 1, Y: 0
Func - X: 2 Y: 4
Main - X: 2, Y: 0
Main - X: 3, Y: 1
兩件事情我無法解釋;爲什麼從main訪問y不會導致警告/錯誤? 如何/在哪裏存儲設置爲y的值,當它等於0和1在主?
如果我想通過意外地訪問其範圍之外的靜態變量而導致問題,我該怎麼做不同?
作爲一般規則,確保頭文件中的任何變量聲明被聲明爲'extern'。 – 2014-12-05 05:52:53