Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type name does not allow storage class to be specified

@interface Foo : NSObject

{
    extern int gGlobalVar;   
    int i;
}
-(void)setgGlobalVar:(int)val;

@end


@implementation Foo

-(void)setgGlobalVar:(int)val
{  
    i = 5;
    NSLog(@"i = %i", i);
    gGlobalVar = val;
}

@end

I can declare i in interface and use it in implementation without any errors. But I cannot declare a variable of the type extern in interface. Why is this so? Why do I get an error which says that: "Type name does not allow storage class to be specified"?

like image 579
Rutvij Kotecha Avatar asked Aug 17 '12 16:08

Rutvij Kotecha


1 Answers

Short Description: The bracketed section of a class's @interface OR @implementation is only for declaring instance variables (aka "ivar"). The extern keyword is only for use with global variable declarations (or functions, but that's another topic.)
Therefore, you cannot declare an extern ivar.

Gritty Details: Variables are first declared, and then defined. This distinction is typically blurred for variables in local scopes, as a locally declared variable without an explicit definition will often be allocated and given a default value by the compiler.

Global variables are potentially available in any scope, provided that scope knows the global exists. That's where the keyword extern comes in -- it declares that the global variable exists, and was defined elsewhere. This is only useful when you want to access a global variable in different code files.

Best Practices: Your book has some code that declares an extern variable in an implementation file (e.g. ".m" files, etc.)... that can work, but it's a bad practice because you're making potentially bad assumptions about whether that global actually has a valid definition elsewhere. (But, fancy compilers will discover this type of error.)

Instead, the best practice is to declare an extern variable once in a header file, have an accompanying implementation file that's dedicated to defining the externs in that header, and then include that header in other implementation files that want to use that global variable.

like image 160
MechEthan Avatar answered Sep 30 '22 18:09

MechEthan