c语言中的static用法



一、作用域在函数里面定义变量用static修饰

#include <stdio.h>


void getNum();


main(){
 	getNum();
 	getNum();
}




void getNum(){
  static num = 0;
  
  num = num + 1;
  
  printf("%d\n",num);


}


其输出为:
12pateo@pateo-B86N53X:~/work/study$ gcc test.c -o test
pateo@pateo-B86N53X:~/work/study$ ./test
1
2

比较下面这个

#include <stdio.h>

void getNum();

main(){
 	getNum();
 	getNum();
	getNum2();
}


void getNum(){
  static num = 0;
  
  num = num + 1;
  
  printf("%d\n",num);

}

void getNum2(){

  
  num = num + 1;
  
  printf("%d\n",num);

}





pateo@pateo-B86N53X:~/work/study$ gcc test.c -o test
test.c:21: warning: conflicting types for ‘getNum2’
test.c:8: warning: previous implicit declaration of ‘getNum2’ was here
test.c: In function ‘getNum2’:
test.c:24: error: ‘num’ undeclared (first use in this function)
test.c:24: error: (Each undeclared identifier is reported only once
test.c:24: error: for each function it appears in.)


再看看下面这个

二、作用域为全局定义变量用static修饰

#include <stdio.h>

static num = 0;
void getNum();

main(){
 	getNum();
 	getNum();
	getNum2();
}


void getNum(){

  
  num = num + 1;
  
  printf("%d\n",num);

}

void getNum2(){

  
  num = num + 1;
  
  printf("%d\n",num);

}




pateo@pateo-B86N53X:~/work/study$ gcc test.c -o test
test.c:22: warning: conflicting types for ‘getNum2’
test.c:9: warning: previous implicit declaration of ‘getNum2’ was here
pateo@pateo-B86N53X:~/work/study$ ./test
1
2
3


三、有关static修饰的函数

test.c

#include <stdio.h>

 int getNum(int num){

  num = num + 1;
  
  return num;

}

main.c

#include <stdio.h>
#include "test.h"


int main(){
  getNum(1);
	
}

int getNum(int num){

  num = num + 1;
  printf("%d\n",num);
  return num;

}

test.h

int getNum(int num);

以上编译会报错,如下:

pateo@pateo-B86N53X:~/work/study$ cc main.c test.c -o main
/tmp/ccSlvPI5.o: In function `getNum':
test.c:(.text+0x0): multiple definition of `getNum'
/tmp/cc6nT5zz.o:main.c:(.text+0x26): first defined here
collect2: ld returned 1 exit status
pateo@pateo-B86N53X:~/work/study$ 


现在我们修改下test.c文件在那个函数前面增加一个static

#include <stdio.h>

static int getNum(int num){

  num = num + 1;
  
  return num;

}


这样就不会报错了


说明:static的作用域只在本文件中

            同样,如果是变量在一个文件中定义了,在另外一个文件中也编译了,如果他们一起编译,则也会报错,除非在另一个文件中此变量私有化即在此变量前面加一个static









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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值