【发布时间】:2016-03-17 09:38:54
【问题描述】:
我有两个共享全局变量的文件。
在 main.c 中
#include<stdio.h>
static int b;
extern int b;
main()
{
extern int a;
printf("a=%d &a:%p\n",a,&a);
printf("b=%d &b:%p\n",b,&b);
fn();
}
在 fun.c 中
#include<stdio.h>
int b=25;
int a=10;
fn()
{
printf("in fna=%d &a:%p\n",a,&a);
printf("in fnb=%d &b:%p\n",b,&b);
}
如果我编译这两个文件。我没有收到任何编译错误。它很好。输出是
a=10 &a:0x804a018
b=0 &b:0x804a024
in fna=10 &a:0x804a018
in fnb=25 &b:0x804a014
但是,在 main.c 中,如果我像这样更改 extern int b 和 static int b 行
#include<stdio.h>
extern int b;
static int b;
main()
{
extern int a;
printf("a=%d &a:%p\n",a,&a);
printf("b=%d &b:%p\n",b,&b);
fn();
}
在编译时,我收到了这个错误。
main.c:6:12: error: static declaration of ‘b’ follows non-static declaration
main.c:5:12: note: previous declaration of ‘b’ was here
这里的问题在于存储静态和外部变量的内存。但是我无法得出第二次编译错误的确切原因
注意:我使用的是 gcc 编译器。
【问题讨论】:
-
问题是?你应该把问题分解成编译器错误的原因和编译器对特定变量的分配策略。
-
也许你的意思是写
static int a;!
标签: c static compiler-errors declaration extern