您的位置:首页 > 编程语言 > C语言/C++

c语言中的static用法

2012-07-27 15:50 127 查看
一、作用域在函数里面定义变量用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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  语言 c function types gcc each