所以我被打约试图了解使用静态变量,显然我的理解是还没有应用,因为我不明白以下是如何操作:访问和修改局部静态变量
主要叫我该吐出奏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