所以,让我们说,我有:file1.c
int i;
static int j;
int main ()
{
for ( int k = 0; k < 10; k++ )
{
int foo = k;
}
}
file2.c
{
// the following statements are before main.
extern int i; // this is acceptable, I know since i acts as a global variable in the other file
extern int j; // Will this be valid?
extern int foo; // Will this be valid as well?
}
因此,我怀疑标有问号的陈述是否有效?
最佳答案
不! static
全局变量具有文件作用域(内部链接),因此您不能使用它们,因为它们具有外部链接...这并不意味着您不能拥有具有外部链接的同名变量,但它不能是static
。
更正 i
。j
不正确,至少它不能是 file1.c
中定义的那个。
对于 foo
不正确,至少对于 file2.c
中使用的局部变量没有外部链接(根本没有链接)。局部变量仅在声明它的块被激活时才存在,因此在外部访问它是没有意义的。
关于静态变量可以在C中声明为extern吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31244540/