当我运行一些使用 extern 关键字引用实现文件中的静态变量的代码时,我看到一些奇怪的东西。因此,我在实现文件中声明静态变量 gCounter,并在同一实现文件中的两个方法中引用它(因为它是静态的)。但是,当我在方法中使用 extern 关键字时,我会得到不同的结果。我的理解(通过阅读我的书)是,当您引用与您的方法在同一文件中声明的静态变量时, extern 是不必要的。代码如下:
/** 接口(interface) **/
#import <Foundation/Foundation.h>
@interface Fraction : NSObject
+(Fraction *) allocF;
+(int) count;
@end
/**implementation**/
#import "Fraction.h"
static int gCounter;
@implementation Fraction
+(Fraction *) allocF
{
extern int gCounter;
++gCounter;
return [Fraction alloc];
}
+(int)count
{
extern int gCounter;
return gCounter;
}
@end
/**main**/
#import "Fraction.h"
int main (int argc, const char * argv[])
{
@autoreleasepool
{
Fraction *a, *b, *c;
NSLog(@"The number of fractions allocated: %i", [Fraction count]);
a = [[Fraction allocF] init];
b = [[Fraction allocF] init];
c = [[Fraction allocF] init];
NSLog(@"The number of fractions allocated: %i", [Fraction count]);
}
return(0);
}
当我在方法中使用 extern 关键字时,代码可以正常工作并打印整数 3。但是,当我删除 extern 时,会打印整数 2。这是为什么?由于 gCounter 是静态变量,因此如果没有 extern 关键字,这是否应该起作用?
最佳答案
您需要了解声明
和定义
之间的区别:
static int x
和int x
是定义。编译器为x
保留内存。
另一方面,extern int x
是一个声明。您告诉编译器有一个变量x
在其他地方定义。
此外,您可以在不同的作用域中定义具有相同变量名称的不同变量:
int x = 0;
{
int x = 1;
NSLog(@"x = %d", x); // x = 1
}
NSLog(@"x = %d", x); // x = 0
所以如果你写
int x;
void foo() {
int x;
x++;
}
您正在递增函数 local x
。
int x;
void foo() {
x++;
}
增加全局x
int x;
void foo() {
extern int x;
x++;
}
如果你的x
定义在另一个编译单元中,则需要声明extern int x
,如果在同一个编译单元中,则后两者是等效的。
关于objective-c - 使用 extern 作为静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18070928/