总共三点:
1、变量前面加static,则此变量只能在本模块中使用,本地全局变量。
2、函数内变量加static,其他函数调用此函数,其值保持上次修改的不变。
3、函数前面加static,此函数只能被本模块中的函数调用,其他函数不能调用。
相应的测试代码如下:(本模块,本人理解为相应的.c源文件)
文件main.c:
#include <stdio.h>
#include "common.h"
static int a=1;
int b=2;
void test()
{
static int c=1;
c=c+1;
printf("c=%d\n",c);
}
void main()
{
//test();
testa();
printf("%s,%d\n",__FILE__,__LINE__);
printf("b=%d\n",b);
test();
test();
//testb();
}
文件Makefile:
all:main.o a.o
gcc main.o a.o -o main
main.o:main.c
gcc -c main.c -o main.o
a.o:a.c
gcc -c a.c -o a.o
clean:
rm -rf *.o main
文件a.c
#include "common.h"
//extern void test();
static void testb()
{
printf("%s,%d\n",__FILE__,__LINE__);
printf("b=%d\n",b++);
}
void testa()
{
printf("%s,%d\n",__FILE__,__LINE__);
printf("b=%d\n",b++);
testb();
}
文件common.h
#ifndef __COMMON__H__
#define __COMMON__H__
#include <stdio.h>
extern int b;
void testa();
//extern static void testb();
#endif
运行结果:
[root@liu aaa]# ./main
a.c,10
b=2
a.c,5
b=3
main.c,15
b=4
c=2
c=3