全局静态变量与 全局变量的区别在于全局静态变量只能在被本源文件中使用。
[header.h]
static int i = 0;
void setStatic();
[s1.c]
#include <stdio.h>
#include "header.h"
int main(int argc, char *argv[])
{
setStatic();
printf("%d %dn",&i, i);
return 0;
}
[s2.c]
#include <stdio.h>
#include "header.h"
void setStatic()
{
i = 1;
printf("%d %dn",&i, i);
}
gcc header.h s1.c. s2.c
./a.out
就可以看到 s1 和 s2 中i 具有不同的地址空间,也就是两个不同的变量。
[header.h]
static int i = 0;
void setStatic();
[s1.c]
#include <stdio.h>
#include "header.h"
int main(int argc, char *argv[])
{
setStatic();
printf("%d %dn",&i, i);
return 0;
}
[s2.c]
#include <stdio.h>
#include "header.h"
void setStatic()
{
i = 1;
printf("%d %dn",&i, i);
}
gcc header.h s1.c. s2.c
./a.out
就可以看到 s1 和 s2 中i 具有不同的地址空间,也就是两个不同的变量。