当我尝试:
#include <stdio.h>
static int c1 = 10;
int main(){
{
extern int c1; //c1 here still has internal linkage
printf("%d",c1);
}
return 0;
}
一切正常。但是当我尝试像这样修改它时:
#include <stdio.h>
static int c1 = 10;
int main(){
int c1 = 20; //This is where I modified.
c1++;
{
extern int c1;
printf("%d",c1);
}
return 0;
}
突然,出现错误。它说:“变量以前声明为'静态'再声明为'外部'”。为什么?
逐字错误消息:
prog.c: In function ‘main’:
prog.c:11:20: error: variable previously declared ‘static’ redeclared ‘extern’
extern int c1;
答案 0 :(得分:-1)
第一个extern
关键字只能应用于函数和全局变量。而且,如果您使用它的意思,那就是告诉编译器您不想保留一个内存块,因为它已经存在于内存中,在您的情况下为static int c1 = 10;
。但是,如果要修改c1,则可以只写c1=20
而不是int c1 = 20;
,否则,如果无法从main修改c1,则将c1设置为全局是没有意义的。