c语言基础-外部变量,static变量的使用
简单栈的实现:
stack.c
#define MAX 100
int sp = 0;
int val[MAX];
void push(int value){
?if(sp<MAX){
? ?val[sp++]=value;
}else{
? ?printf("wrong");
}
}
?
int pop(){
? if(sp>0){
? ?return val[--sp];
}else{
? return 0;
}
}
?
ceshi.c
#include<stdio.h>
int main(){
? void push(int val);
?//对外部变量的使用?
extern int sp; ?
int pop();
? push(3);
? push(4);
? push(5);
? push(6);
? printf("the sp is%d",sp);
?
}
?
同时编译stack.c和ceshi.c,会看到sp为4,证明确实在ceshi.c中引用到了stack.c中的外部变量。
?
将statck.c中的外部变量用static修饰,ceshi.c不做改动,然后同时编译两个文件,你会看到undefined的报错,这就很好的验证了static只对源文件可见。