【发布时间】:2013-06-11 10:08:23
【问题描述】:
我正在尝试一个小例子来了解静态外部变量及其用途。静态变量是局部作用域,外部变量是全局作用域。
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;不应该在函数体之外吗? -
m 在 static5.c 中被声明为静态,因此范围在文件内。所以错误。
-
那么问题是什么? m 对 static5.c 文件是静态的,因此即使使用
extern声明它也无法在其他任何地方访问 -
在头文件中包含任何函数定义是不寻常的并且具有潜在危险。
标签: c