static的用法

总共三点:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值