我正在尝试一个小例子来了解静态外部变量及其用途。静态变量是局部作用域的,而外部变量是全局作用域的。
static5.c
#include<stdio.h>
#include "static5.h"
static int m = 25;
int main(){
func(10);
return 0;
}
static5.h
#include<stdio.h>
int func(val){
extern int m;
m = m + val;
printf("\n value is : %d \n",m);
}
gcc static5.c static5.h
o/p :
static5.c:3: error: static declaration of m follows non-static declaration
static5.h:3: note: previous declaration of m was here
已编辑
正确的程序:
a.c:
#include<stdio.h>
#include "a1_1.h"
int main(){
func(20);
return 0;
}
a1.h:
static int i = 20;
a1_1.h:
#include "a1.h"
int func(val){
extern int i;
i = i + val;
printf("\n i : %d \n",i);
}
这个工作得很好。但是它被编译成了一个单一的编译单元。因此可以访问静态变量。在编译单元之间,我们不能使用extern变量来使用静态变量。
extern int m;
不应该放在函数体内吗? - Kninnugextern
关键字声明也无法在其他地方访问。 - greydet